Quantitative transaction strategy generation method and device

By generating quantitative trading strategies through a multi-task language model and a financial logic rule base, the problem of low efficiency due to reliance on manual labor in traditional quantitative trading is solved. This enables automated and intelligent strategy development, lowers the professional threshold, and improves market adaptability and investment returns.

CN121481718APending Publication Date: 2026-02-06SHANGHAI XIYUE INVESTMENT MANAGEMENT CO LTD

Patent Information

Application Number
CN202511616888.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-11-06
Publication Date
2026-02-06

AI Technical Summary

Technical Problem

Traditional quantitative trading strategy development relies on manual labor, which is inefficient, makes it difficult to respond quickly to market changes, and has a high professional threshold, limiting the participation of non-professionals and small and medium-sized asset management companies as well as the speed of strategy iteration.

Method used

A multi-task language model is used to identify and supplement user needs. Combined with financial logic rules and strategy template library, structured semantic objects are generated and compiled into executable strategy files through framework code generator, realizing intelligent and automated management from strategy conception to deployment.

Benefits of technology

It significantly improves the efficiency and accuracy of quantitative trading, lowers the professional threshold, enables more people to participate in strategy development, and helps professional investors maintain a competitive edge in the market.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121481718A_ABST
    Figure CN121481718A_ABST
Patent Text Reader

Abstract

The invention discloses a quantitative transaction strategy generation method and device. The generation method comprises the following steps: receiving a demand input by a user and preprocessing the demand; utilizing a multi-task language model to extract the entity and intention of the preprocessed demand; generating a structured semantic object according to the entity and the intention; reasoning the structured semantic object to generate abstract strategy description; compiling the abstract strategy description by utilizing a framework code generator to generate an executable strategy file; according to the scheme, intelligent and automatic management of the whole process from strategy conception to deployment is realized, and efficiency, accuracy and market adaptability are remarkably improved; according to the method, the professional threshold of quantitative transactions can be greatly reduced, more financial professionals with non-programming backgrounds can also participate in strategy development, and professional investors can be helped to keep competitive advantages in the market which changes instantaneously through continuous optimization so as to realize better return on investment.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The present application relates to the field of big data processing, in particular to a method and device for generating a quantitative trading strategy. BACKGROUND

[0002] With the increasing complexity and high frequency of global financial markets, and the explosive growth of data volume, quantitative trading has evolved from traditional methods based on artificial experience and statistical models to complex systems relying on advanced computing technology and big data analysis. However, the current development, verification and optimization process of quantitative trading strategies still faces many challenges, which seriously restricts the efficiency, flexibility and popularity of quantitative trading.

[0003] The traditional development process of quantitative trading strategies highly depends on the comprehensive ability of developers, including deep financial market knowledge, rigorous statistical background, professional programming skills and proficiency in specific trading frameworks. A complete strategy usually needs to go through a long and resource-intensive cycle, from the initial market insight, the conception of trading ideas, to the precise design of strategy logic, the implementation of code, the rigorous debugging, the backtesting of large-scale historical data, the complex parameter optimization, the fine risk management model construction, and finally the deployment and monitoring. Each link may consume weeks or even months of time and a large amount of human resources. This highly manual mode leads to extremely low development efficiency of strategies, making it difficult to quickly respond to the rapidly changing market environment, and greatly limiting the threshold for non-professionals or financial practitioners lacking programming background to enter the field of quantitative trading. For individual investors, the lack of professional quantitative development ability and expensive software tools is the main obstacle for them to participate in quantitative trading. For small and medium-sized asset management companies, it is costly to form a quantitative team with full-stack ability, and talents are scarce. Even large financial institutions face the problems of slow strategy iteration speed, difficulty in quickly adapting to market changes, and high maintenance cost of existing systems. SUMMARY

[0004] To solve the above problems, the present application provides a scheme with low secondary development difficulty, high intelligence and accurate quantitative trading strategy.

[0005] To achieve the above purpose, the present application provides a method for generating a quantitative trading strategy, comprising: receiving user input requirements and preprocessing the requirements; extracting the entities and intents of the preprocessed requirements using a multi-task language model; generating structured semantic objects according to the entities and intents; generating abstract strategy descriptions by reasoning on the structured semantic objects; and compiling the abstract strategy descriptions to generate executable strategy files using a framework code generator.

[0006] Optionally, the preprocessing includes: removing invalid information from the requirements and unifying the format; splitting the unified formatted continuous text into processable basic semantic units; mapping the basic semantic units to numeric IDs; and performing sequence processing on the numeric IDs to generate attention masks.

[0007] Optionally, the multi-task language model includes: multiple domain adapters for lightweight parameter training of corresponding domains, with the domain router determining which domain adapter to activate or with what weights during forward pass; an intent classification head that uses hierarchical multi-label classification to identify multi-level intents defined in the CTA strategy ontology; an entity extraction head that uses a pointer generation hybrid mechanism to extract entities across spans, adaptively choosing between original text copying and terminology normalization; and market state awareness that calculates a state vector through external signals, which is then appended to cue or latent states as additional conditions during fine-tuning and inference, enabling the multi-task language model to adapt its understanding of cycles, thresholds, and risk control to market states.

[0008] Optionally, the gating and mixing in the plurality of register adapters are determined by the following formula:

[0009] (1)

[0010] (2)

[0011] Where K represents the number of register adapters, Indicates temperature. This represents the gating weight for the k-th register adapter, and exp(*) represents the logarithmic calculation. , This indicates the routing network's score for each domain. This represents the vector after register adaptation. This represents the vector before register adaptation. This represents the adapter for the k-th register, where k represents the adapter for the k-th register.

[0012] The state vector is calculated using the following formula:

[0013] (3)

[0014] (4)

[0015] (5)

[0016] Where T represents the time window, t represents the current time, rt represents the profit sequence, and vt represents the trading volume. Indicates quantile calculation, This indicates the trading volume indicator within the window. Indicates the energy intensity within the window. Indicates the strength of the trend. This indicates the calculation of the exponential moving average, where L(p) represents the long-term trend and S(p) represents the short-term trend. Represents a constant;

[0017] The state vector and injection are determined by the following formula:

[0018] (6)

[0019] (7)

[0020] (8)

[0021] Where z represents the state vector and c represents the condition vector. Represents a state-mapping network. This represents the latent vector after the injected state. Let represent the implicit vector at the initial position.

[0022] Optionally, the abstract strategy description is generated by reasoning on the structured semantic object, including: verifying the structured semantic object to determine whether there is a logical contradiction; determining whether the structured semantic object is complete, and if incomplete, completing it; and using a strategy template and a best practice library to reason on the completed structured semantic object to generate an abstract description strategy, wherein the reasoning process is limited to the rules of the financial logic rule base, which contains multiple rules based on financial transaction practices and risk management theories.

[0023] Optionally, the abstract description strategy is generated by reasoning about the structured semantic objects to be completed using strategy templates and best practice libraries. This includes: selecting and sorting suitable templates from the strategy templates and best practice libraries; instantiating and populating the slot list of the highest-scoring template or combined templates to obtain a filled slot list; performing conflict detection and constraint solving on the filled slot list to obtain the final slot set; generating a strategy graph structure based on the slot set; validating the strategy graph structure and generating structured text; and compiling the structured text to obtain the abstract description strategy.

[0024] Optionally, the abstract strategy description is compiled into an executable strategy file using a framework code generator, including: parsing the abstract strategy description to generate configuration code; translating the logic in the abstract strategy description line by line into executable code using the framework code generator; commenting on the executable code and outputting the executable strategy file.

[0025] Optionally, parsing the abstract strategy description to generate configuration code includes: performing static analysis on the abstract strategy description to obtain the tags and summary fields of the abstract strategy description; using the tags and summary fields to search for logically similar historical strategies; and filtering out relevant results from the database.

[0026] On the other hand, the present invention also provides a quantitative trading strategy generation apparatus, comprising: a preprocessing unit for receiving user input requirements and preprocessing the requirements; an extraction unit for extracting entities and intentions of the preprocessed requirements using a multi-task language model; a generation unit for generating structured semantic objects based on the entities and intentions; a reasoning unit for reasoning on the structured semantic objects to generate an abstract strategy description; and a compilation unit for compiling the abstract strategy description using a framework code generator to generate an executable strategy file.

[0027] The advantages of this invention compared to existing technologies are as follows: This invention identifies and supplements user needs through a multi-task language model, and then infers the trading strategies required by users based on financial logic rules and strategy template libraries. This revolutionizes the traditional development paradigm of quantitative trading strategies, realizing intelligent and automated management of the entire process from strategy conception to deployment, significantly improving efficiency, accuracy, and market adaptability. It not only significantly lowers the professional threshold for quantitative trading, enabling more financial professionals without programming backgrounds to participate in strategy development, but also helps professional investors maintain a competitive advantage and achieve better investment returns in a rapidly changing market through continuous optimization. Attached Figure Description

[0028] Figure 1 This is a flowchart of a method for generating a quantitative trading strategy provided by the present invention;

[0029] Figure 2 This is a flowchart of step S40 in a method for generating a quantitative trading strategy provided by the present invention;

[0030] Figure 3 This is a structural diagram of a quantitative trading strategy generation device provided by the present invention. Detailed Implementation

[0031] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of the present invention, and not all of them. Based on the embodiments of the present invention, all other embodiments obtained by those of ordinary skill in the art without creative effort are within the scope of protection of the present invention.

[0032] Reference Figure 1This implementation provides a method for generating quantitative trading strategies, including the following steps:

[0033] S10: Receive user input requests and preprocess the requests.

[0034] The purpose of preprocessing is to clean up invalid information in the natural language input requirements. Specifically, this includes removing invalid information from the requirements and standardizing the format; then, splitting the standardized continuous text into processable basic semantic units; next, mapping the basic semantic units to numeric IDs; and finally, performing sequence processing on the numeric IDs to generate attention masks.

[0035] S20: Use a multi-task language model to extract the preprocessed entities and intents of the requirements.

[0036] Specifically, the construction and training process of the multi-task language model is as follows:

[0037] First, it is necessary to obtain data samples for training the multi-task language model. In this embodiment, the data samples consist of multi-source data, including:

[0038] Professional corpora: such as brokerage research reports and macro / quantitative papers (emphasizing precise definitions and logical chains).

[0039] Community corpora: such as Xueqiu, Eastmoney stock forum, Reddit (emphasizing colloquialisms, slang, emotions, and vague expressions).

[0040] Conversational data: such as trader Q&A, investment research discussion segments (multiple rounds of reference, omissions).

[0041] After obtaining the data samples, the samples need to be semi-automatically labeled and cleaned. The semi-automatic labeling includes: first, pre-extracting elements that can be "regularly matched" based on the quantitative trading strategy (Commodity Trading Advisors, CTA) task ontology; then, using the teacher model to generate pseudo-labels on the weakly labeled data, and the student model to refine them a second time; finally, constructing positive / hard negative samples from similar expressions (such as "going long on breakout" vs "don't chase upper shadow breakout") to improve boundary discrimination.

[0042] In this embodiment, data cleaning includes: financial dictionary standardization (synonym aggregation: such as "Treasury bond futures = TBF" "10-year bond = 10-year CGB").

[0043] Domain labels: Each sample is labeled {report|paper|community} and used as conditional input during training.

[0044] Noise auditing: Remove triggers (ads, ASCII emojis), extreme repetitions, and low-confidence pseudo-labels.

[0045] In this embodiment, after obtaining the data samples, the main architecture of the multi-task language model is constructed, as follows:

[0046] This multi-task language model includes multiple domain adapters (three in this embodiment) for lightweight parameter training of the corresponding domains (professional reports, academic papers, community Q&A). During forward pass, the domain router (lightweight classifier or gating network) determines which domain adapter to activate or with what weights to mix them.

[0047] In this embodiment, gating and mixing in multiple register adapters are determined by the following formula:

[0048] (1)

[0049] (2)

[0050] Where K represents the number of register adapters, Indicates temperature. This represents the gating weight for the k-th register adapter, and exp(*) represents the logarithmic calculation. , This indicates the routing network's score for each domain. This represents the vector after register adaptation. This represents the vector before register adaptation. This represents the adapter for the k-th register, where k represents the adapter for the k-th register.

[0051] The above approach can reduce the parameter strain caused by a single model trying to accommodate three language styles, while maintaining the logical rigor of research reports and tolerating the noise of community slang.

[0052] In addition, the multi-task language model architecture also includes an intent classification head and an entity extraction head. The intent classification head uses hierarchical multi-label classification to identify multi-level intents (such as strategy type, time scale, entry / exit logic, filters, risk control intent, etc.) defined in the CTA strategy ontology. The entity extraction head uses a pointer generation hybrid mechanism to extract span entities (such as "ATR 14", "20-day moving average", "Bollinger Band upper rail +1σ"), adaptively choosing between original text copying and terminology normalization.

[0053] In this embodiment, the structured decoder of the multi-task language model describes the complete slots and type constraints of the CTA IR using JSON Schema (such as instrument:string, signal:{type, lookback, threshold, confirmers}, risk:{stop, take, sizing}, etc.). Simultaneously, during inference, a restricted vocabulary / state machine / validator ensures that the output is a fully formed structured JSON in one step, avoiding secondary errors caused by "natural language → re-parsing".

[0054] In this embodiment, the multi-task language model also includes market state perception, which calculates a state vector through external signals and splices it to the cue or hidden state as an additional condition during fine-tuning and inference, so that the multi-task language model's understanding of cycles, thresholds and risk control adapts to the market state.

[0055] In this embodiment, the state vector is calculated using the following formula:

[0056] (3)

[0057] (4)

[0058] (5)

[0059] Where T represents the time window, t represents the current time, and r t Represents the profit sequence, v t Indicates transaction volume. Indicates quantile calculation, This indicates the trading volume indicator within the window. Indicates the energy intensity within the window. Indicates the strength of the trend. This indicates the calculation of the exponential moving average, where L(p) represents the long-term trend and S(p) represents the short-term trend. Represents a constant;

[0060] The state vector and injection are determined by the following formula:

[0061] (6)

[0062] (7)

[0063] (8)

[0064] Where z represents the state vector and c represents the condition vector. Represents a state-mapping network. This represents the latent vector after the injected state. Let represent the implicit vector at the initial position.

[0065] It should be noted that after the multi-task language model is built, it needs to be trained using preprocessed data samples until it converges. The training process is as follows:

[0066] Phase A: Terminology and Logic Indoctrination (Specialist Priority), using research report / paper samples for intent and entity monitoring, and learning rigorous definition and combinatorial logic.

[0067] Phase B: Spoken Language Robustness (Community Alignment), introducing spoken language / slang data, and incorporating noise robustness loss and contrastive learning.

[0068] Phase C: Structured reinforcement, strengthens constrained decoding, introduces structured consistency loss (aligns the JSON with the original evidence span), and reduces the illusion of "slots without evidence".

[0069] Phase D: State perception refinement, a second fine-tuning on samples containing market states, to make the output cycle / threshold / risk control more in line with the habitual expressions of different fluctuation / trend situations.

[0070] S30: Generate a structured semantic object based on the entity and intent.

[0071] Specifically, the entities and intents identified by the multi-task language model are encapsulated into a standardized, machine-readable JSON object. This object structures all the parsed information, laying a solid foundation for subsequent processing.

[0072] S40: Reason about the structured semantic object to generate an abstract strategy description.

[0073] Reference Figure 2 Step S40 specifically includes the following steps:

[0074] S401: Validate the structured semantic object to determine if there are any logical contradictions.

[0075] It should be noted that the completeness of the structured semantic object includes whether the logic is contradictory and whether the structure is complete. Logical contradiction is to judge whether a complete CTA strategy has logical conflicts or obviously violates natural laws and common sense. For example, I want a CTA strategy with 100% return and no drawdown (which is completely illogical).

[0076] In addition, the integrity of the structure is judged through four levels: structure layer, domain layer, dependency layer, and executable layer.

[0077] In this embodiment, the structure layer needs to validate the JSON structure, field types, enumeration validity, and range. The tool used is JSON Schema / Pydantic, and the final output is a list of missing fields plus a list of types / value errors.

[0078] In this embodiment, the domain layer needs to determine the CTA domain constraints, including strategy instruments: futures, options, etc.; backtracking windows (10 days, 1 year, 10 years); strategy logic; indicator type; trading session; transaction costs, slippage units, and matching with the underlying asset (tick / lot / contract); and other fields deemed necessary by the model. The final output includes any unincluded domain rule items and correction suggestions (such as automatic unit conversion).

[0079] In this embodiment, the dependency layer needs to verify the conditions required for CTA execution. For example, using ATR stop loss requires atr.period & atr.multiplier; using equity curve drawdown stop loss requires max_drawdown.pct or max_drawdown.cash; using cross-asset hedging requires hedge.symbols + hedging ratio or covariance window.

[0080] In this embodiment, the executability layer needs to determine the following: data availability (whether the symbols exist in the data source and in the historical interval); whether the strategy entry point is defined (the signal set must contain at least one executable entry point / exit rule); and whether the trading unit can be a whole lot (contract multiplier, minimum price fluctuation). The final output is an executability flag plus a reason for non-executability.

[0081] S402: Determine whether the structured semantic object is complete; if incomplete, complete it.

[0082] Specifically, when a structured semantic object is found to be incomplete, it needs to be completed, and there are several ways to do so.

[0083] 1. Each layer has a judgment statement based on the multilingual task model built from the previous layer, used to check whether the parameters of the current layer are complete (the prompt is short and the feedback is fast).

[0084] 2. Autocomplete (suitable for situations where the user does not wish to continue the conversation), specifically as follows: based on the default parameters of the policy template (RAG retrieval), the default parameters given by LLM (model thinking), and the backtracking of the historical dialogue memory (RAG retrieval). It should be noted that each autocomplete item must record the source label: source ∈ {default, heuristic, inferred, org_policy, user_provided}, and retain the confidence level (0–1) and the original value that can be rolled back.

[0085] 3. Multi-round dialogue completion: Each round should include a maximum of three questions, prioritizing those deemed important by the LLM (Leadership Management System). Provide 2-4 options plus 1 custom entry point. Before each question, display the "current gap" and "assumed default values." Link questions with pre-answered questions, such as, "Hello, to accurately construct your strategy, a few details need confirmation: 1. Based on how many past periods is the 'previous high' you mentioned calculated? For example, 30 periods. 2. Is the 20-day moving average a Simple Moving Average (SMA) or an Exponential Moving Average (EMA)? 3. Do we need to configure a risk management module for you, such as stop-loss or take-profit?" When `readiness=true`, stop asking follow-up questions and display the final structured semantic object summary for the user to confirm in one go.

[0086] S403: Use strategy templates and best practice libraries to reason about the completed structured semantic objects to generate abstract description strategies, wherein the reasoning process is limited to the rules of the financial logic rule base, which contains multiple rules based on financial transaction practices and risk management theories.

[0087] The specific process is as follows:

[0088] S4031: First, the structured semantic object is processed through standardization to produce a field mapping table (SSO field → ontology slot name).

[0089] S4032: Next, based on factors such as strategy type, signal paradigm, target market conditions, and risk control intent, a set of candidate templates is recalled from the template library, along with corresponding best practice snippets and anti-pattern entries. Templates that do not fit the scenario are removed during this process (e.g., the cycle is not in the supported set, or the template application instructions conflict with SSO). Then, the templates are weighted and sorted according to ontology matching degree, parameter coverage, applicable condition matching degree, and anti-pattern penalty score to obtain the top few templates.

[0090] S4033: Next, instantiate the slot list of the highest-scoring template or combination template (e.g., signal parameters, entry / exit rule parameters, position sizing parameters, stop-loss parameters, cost model parameters, execution parameters, portfolio and risk parameters). Simultaneously, populate each slot in priority: user-defined value → compliance and safety minimum → best practice default → template default → leave blank if undetermined. Record the source category and relative confidence level for each filled slot; unfilled items are added to the gap list.

[0091] S4034: Next, conflict detection and constraint resolution are performed. Specifically, type conflict is checked first: for example, the order type is limit order but no cancellation strategy is specified; the stop loss type is volatility method but no volatility window is specified. Then, cross-field dependency is checked: for example, using the equity curve for stop loss requires a drawdown threshold; cross-product hedging requires hedging set and ratio. Then, executability is checked: the availability of data corresponding to historical intervals and frequencies; whether the trading unit meets the requirement of whole lots; whether there are active contracts for the product; whether the time period matches the exchange. Next, constraint resolution is performed, and parameters that cannot be simultaneously satisfied are resolved with minimal modifications, generating a finite number of repair solutions (each solution includes changes and impact descriptions). Finally, the final slot set after constraints is used; if it exists, the repair solution is recorded; if it exists, the question package is clarified.

[0092] S4035: Generate component nodes according to the fixed node type of the ontology: Signal Module, Entry Module, Exit Module, Position Module, Stop Loss Module, Execution Module, Cost Module, Portfolio Module, Risk Limitation Module, and Report Module. Next, establish causal and constraint relationships (dependency, constraint, portfolio, influence) for the nodes. Then, verify the minimum executable chain to ensure the existence of a complete link: "Signal → Entry → Exit → Position → Stop Loss → Execution → Portfolio → Risk Limitation". Finally, output the strategy graph structure (a directed acyclic graph of nodes and edges).

[0093] S4036: Static Verification: Verify the parameter domain, unit, time zone, whole lot rule, and minimum price fluctuation for each module; ensure that every Entry has an Exit; and that at least one triggerable exit mechanism exists. Next, perform data confirmation: check the existence and continuity of historical data by instrument and cycle; if using main contract continuous or index contracts, confirm the splicing method. Recheck leverage and concentration, drawdown limits, and disallowed combinations (such as excessive parallel signals exceeding the preset limit). Finally, output an executability pass flag; if it fails, list the module-level failure reasons and suggested fixes (return to S4034 for processing).

[0094] S4037: Export a machine-readable intermediate representation according to the ASD-IR Schema, including metadata, market and data definitions, strategy diagram, execution and costs, portfolio and risks, and a list of executability constraints. Then calculate the content hash; record the template version, rule version, and ontology version used; generate a code compiler-compatible signature. Next, audit logging: write the source, confidence level, and remediation plan (if any) for each slot into the audit trail. Finally, output ASD-IR (JSON); version and signature metadata.

[0095] S4038: Generate ASD-NL, first performing chapter-based rendering: outputting according to fixed chapters: Objectives and Assumptions, Signal Logic, Entry / Exit, Positions and Risk Management, Portfolio and Risk, Execution and Cost, Actionability Statement, and Source Notes. Then, consistency control is performed: all facts come from the nodes and attributes of ASD-IR; facts not appearing in IR are prohibited; key sentences are accompanied by source footnotes (from users, templates, best practices, or solution fixes). Finally, output ASD-NL (structured text).

[0096] S4039. Code compilation and backtesting configuration integration, including module mapping: node types in ASD-IR correspond one-to-one with compiler modules; spec field names match compiler parameter names. Then, configuration is generated: strategy parameter configuration, data source configuration, trading session and unit configuration, cost and risk parameter configuration, and report output configuration are directly generated from ASD-IR. Next, a final unit and session consistency check is performed before code generation; if it fails, generation is rejected and backtracking to S4036 is initiated. Finally, the strategy code skeleton and backtesting configuration file are output; a compiler compatibility signature is written to the output header.

[0097] In layman's terms, the above process involves taking the SSO (strategy idea and preliminary rules) generated through lengthy dialogues, transforming and cleaning it into a refined and professional strategy format, accurate to the type, precision, specific varieties, precision frequency, code format, backtesting, etc., and then compiling a strategy summary for user confirmation.

[0098] Financial anti-pattern participation in RAG ranking: Including domain "incorrect structures" as negative samples in retrieval / ranking to reduce illusions and improper assembly; Field-level Provenance and Confidence: Continuously carrying source / confidence / template version at the slot level and explicitly annotating it on the NL end; Pre-compilation constraint resolution: Formalizing risk and executability requirements into constraint sets and using a solver to statically resolve conflicts during the generation phase.

[0099] It should be noted that the Financial Logic Rule Base is a hard-coded, immutable rule base containing thousands of axioms and theorems derived from financial trading practices and risk management theories. Its existence is to limit the creativity of the LLM and prevent it from generating any code that violates fundamental trading principles or contains logical flaws.

[0100] The aforementioned financial logic rule base is divided into multiple levels:

[0101] 1. Logical layer rules, such as "closing a position cannot be performed when there are no open positions" and "the number of open positions cannot be negative or zero".

[0102] 2. Risk control rules, such as "any trading strategy must include stop-loss logic unless the user explicitly refuses" and "the maximum loss of a single trade cannot exceed a preset threshold (such as 2%) of the total account funds".

[0103] 3. Data layer rules, such as "before calculating the 20-day moving average, at least 20 historical data points must be available".

[0104] It's also worth noting that the strategy templates and best practice library cover a wide range of models, from classic trend following, mean reversion, and market-neutral arbitrage to more complex factor models and statistical arbitrage. During inference, based on the main intent in the structured semantic object (such as "Momentum_Strategy"), the library is prioritized to find the best-matching template as the strategy's skeleton.

[0105] Trend following can be achieved using two moving averages (MA) crossover: Signal = 1{MA_fast > MA_slow} − 1{MA_fast < MA_slow}. Typical examples include 10 / 50 and 20 / 100 days. Alternatively, channel / Turtle breakouts can be used: go long on a break above the past N-day high and go short on a break below the past N-day low; often combined with N / 2-day reverse stop-loss. Time-Series Momentum can also be used: Signal = sign(past 12 months' return, excluding the most recent month); very common in futures / forex. Finally, ATR trailing stop-loss can be used: after entry, a k×ATR trailing stop-loss is used to control drawdowns.

[0106] Mean reversion can be achieved using Bollinger Reversion: the price spread z = (P−MA) / σ, opening a position in the opposite direction when |z|>z*, and closing the position when the price reverts to the mean. Alternatively, it can utilize RSI / RSI2 extreme reversals: going long when RSI<30, and going short when RSI>70; RSI2 is often used with shorter timeframes (e.g., 2 days) to capture ultra-short-term reversals. Another approach is pair trading (OU model): finding two assets A and B, and calculating the price spread S = A − βB; if S approximates OU: dS=κ(μ−S)dt+σdW, opening a position in the opposite direction when z=(S−μ) / σ deviates from the threshold. Finally, it can employ Kalman filtering dynamic hedging ratio (Kalman Spread): using Kalman filtering to estimate β_t online, constructing S_t = A_t − β_t B_t, and performing mean reversion.

[0107] Market-neutral arbitrage can be achieved through: Stat Beta-Neutral: going long on a single stock while simultaneously shorting an index / sector ETF using the regression-derived beta, targeting a net beta of approximately 0. Alternatively, index arbitrage tracks the deviation between the theoretical basis F − Se^{rT} of futures and spot prices; reversing the position when the deviation exceeds a threshold. Convertible arbitrage (simplified version): going long on convertible bonds and shorting the corresponding underlying stock to neutralize Delta and profit from mismatch and volatility gains. Finally, cross-maturity volatility neutrality (Vol Neutral): employing Vega / Delta neutrality across a portfolio of options with different expiration / exercise dates to capture structural biases.

[0108] Factor models can be implemented using Fama-French 3 / 5 factors: returns are explained by MKT, SMB, HML (+RMW, CMA); stock selection can involve going long on high-scoring portfolios and shorting on low-scoring portfolios. Alternatively, Carhart four-factor models (including momentum MOM) can be used: adding a momentum factor to FF3; commonly used for "going long on strong stocks and shorting on weak stocks." Industry / style risk models (Barra series) can also be used: building a risk model using style (value, growth, volatility, etc.) + industry factors, going long on alpha and shorting the hedge basket to achieve neutrality. Finally, quality / profitability models can be used: a comprehensive score based on ROE, gross margin, asset turnover, etc., forms a long-short portfolio.

[0109] Statistical arbitrage can employ cointegration cluster trading (Cluster / Pairs via Cointegration): first cluster by industry / factor, then perform Johansen / EG cointegration tests within the clusters, and trade the error correction term of the cointegrated combination. Alternatively, PCA residual momentum / regression can be used: perform principal component decomposition / cross-sectional regression on returns, and trade residuals (e.g., shorting positive residuals, going long on negative residuals, or applying momentum / reversal to residuals). Microstructure / Order Flow Imbalance (OFI) can also be used: estimate OFI using the order book increment ΔDepth, with the signal = sign(OFI_{t−k:t}); commonly used for short-term market making / reversal. Finally, Avellaneda–Stoikov market making can be used: given risk aversion and inventory targets, dynamically set buy and sell quotes and inventory control to statistically profit from the spread.

[0110] S50: Use the framework code generator to compile the abstract strategy description into an executable strategy file.

[0111] Specifically, after the Abstract Strategy Description (ASD) file is generated, based on the tags and summary fields in the ASD structure, historical strategies with similar embedding are searched, and then relevant results of these historical strategies are filtered out from the database, including: strategy parameters, backtesting results of multiple varieties (arranged in ascending order according to Sharpe ratio), and backtesting results of different years for the corresponding varieties, forming a strategy table.

[0112] Next, based on the current ASD and strategy table, we analyze and obtain recommended backtesting varieties and recommended backtesting years, which are then presented to the user for selection.

[0113] Then, the ASD is parsed to determine the required data length and generate the configuration code self.am = ArrayManager(size=50).

[0114] Next, the framework code generator translates the logic in ASD line by line into Python code. For example, it translates `calculate: moving_average` into `self.moving_average = self.am.sma(self.ma_period, array=True)`, and the buy logic into a complete `if` statement block.

[0115] Next, the injector adds interpretable comments above the key logic lines. For example, above the `if` statement that determines a buy signal, the comment `#` will be automatically generated, corresponding to the user instruction: "Buy when a large bullish candle breaks through the previous high." Finally, code formatting tools such as Black are used to beautify the final code, ensuring it conforms to PEP 8 standards.

[0116] Finally, the compilation layer generates a complete .py file containing all necessary imports, class definitions, initialization methods, event handling methods, and helper functions. Users can directly load this file into the backtesting system and run it without any manual modifications.

[0117] The quantitative trading generation method described in the above embodiments identifies and supplements user needs through a multi-task language model, and then infers the trading strategy required by the user based on financial logic rules and a strategy template library. This revolutionizes the traditional development paradigm of quantitative trading strategies, realizing intelligent and automated management of the entire process from strategy conception to deployment, significantly improving efficiency, accuracy, and market adaptability. It not only greatly reduces the professional threshold of quantitative trading, enabling more financial professionals without programming backgrounds to participate in strategy development, but also helps professional investors maintain a competitive advantage in a rapidly changing market and achieve better investment returns through continuous optimization.

[0118] Reference Figure 3 This embodiment provides a quantitative trading strategy generation device, comprising:

[0119] The preprocessing unit 100 is used to receive user input requirements and preprocess the requirements. It should be noted that since the specific preprocessing methods and processes have been described in detail in step S10 of the above-mentioned quantitative trading strategy generation method, they will not be repeated here.

[0120] Extraction unit 200 is used to extract the preprocessed entities and intentions of the requirements using a multi-task language model. It should be noted that since the specific extraction method and process have been described in detail in step S20 of the above-mentioned quantitative trading strategy generation method, they will not be repeated here.

[0121] The generation unit 300 is used to generate a structured semantic object based on the entity and intent. It should be noted that since the specific generation method and process have been described in detail in step S30 of the above-mentioned generation method of a quantitative trading strategy, they will not be repeated here.

[0122] The reasoning unit 400 is used to reason about the structured semantic object to generate an abstract strategy description. It should be noted that since the specific reasoning method and process have been described in detail in step S40 of the above-mentioned method for generating a quantitative trading strategy, they will not be repeated here.

[0123] The compilation unit 500 is used to compile the abstract strategy description into an executable strategy file using the framework code generator. It should be noted that since the specific compilation method and process have been described in detail in step S50 of the above-mentioned method for generating a quantitative trading strategy, they will not be repeated here.

[0124] In addition, embodiments of the present invention also provide a computer-readable storage medium, wherein the computer-readable storage medium may store a program that, when executed, includes some or all of the steps of any quantitative trading generation method described in the above method embodiments.

[0125] Furthermore, the functional units in the various embodiments of the present invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.

[0126] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage device (CMD). Based on this understanding, the technical solution of this invention, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a memory and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of this invention. The aforementioned memory includes various media capable of storing program code, such as USB flash drives, read-only memory (ROM), random access memory (RAM), portable hard drives, magnetic disks, or optical disks.

[0127] Those skilled in the art will understand that all or part of the steps in the various methods of the above embodiments can be implemented by a program instructing related hardware. The program can be stored in a computer-readable storage device, which may include: a flash drive, a read-only memory (ROM), a random access memory (RAM), a magnetic disk, or an optical disk, etc.

[0128] The above description, with reference to the accompanying drawings, illustrates an exemplary flowchart of a method for generating a quantitative trading strategy according to an embodiment of the present invention. It should be noted that the numerous details included in the above description are merely illustrative of the invention and not intended to limit it. In other embodiments of the invention, the method may have more, fewer, or different steps, and the order, inclusion, function, and other relationships between the steps may differ from those described and illustrated.

Claims

1. A method for generating a quantitative trading strategy, characterized in that, include: Receive user input and preprocess the requirements; Utilize a multi-task language model to extract preprocessed entities and intents related to the requirements; Generate structured semantic objects based on the entities and intentions; The structured semantic object is used to generate an abstract strategy description through reasoning. The abstract strategy description is compiled using a framework code generator to generate an executable strategy file.

2. The generation method according to claim 1, characterized in that, The preprocessing includes: Remove invalid information from the requirements and standardize the format; Break down continuous text after standardization into basic semantic units that can be processed; Map the basic semantic units to numeric IDs; The numeric ID is processed sequentially to generate an attention mask.

3. The generation method according to claim 1, characterized in that, The multi-task language model includes: Multiple domain adapters are used for lightweight parameter training of the corresponding domains. During forward pass, the domain router decides which domain adapter to activate or with what weights to mix them. The intent classification head uses hierarchical multi-label classification to identify multi-level intents defined in the CTA strategy ontology; The entity extraction head uses a pointer generation hybrid mechanism to extract entities across a range, adaptively choosing between original text copying and terminology normalization. Market state perception calculates a state vector through external signals, which is then appended to the cue or hidden state as an additional condition during fine-tuning and inference, enabling the multi-task language model to adapt its understanding of cycles, thresholds, and risk control to market states.

4. The generation method according to claim 3, characterized in that: The gating and mixing in the multiple register adapters are determined by the following formula: (1) (2) Where K represents the number of register adapters, Indicates temperature. This represents the gating weight for the k-th register adapter, and exp(*) represents the logarithmic calculation. , This indicates the routing network's score for each domain. This represents the vector after register adaptation. This represents the vector before register adaptation. This represents the adapter for the k-th register, where k represents the adapter for the k-th register. The state vector is calculated using the following formula: (3) (4) (5) Where T represents the time window, t represents the current time, and r t Represents the profit sequence, v t Indicates transaction volume. Indicates quantile calculation, This indicates the trading volume indicator within the window. Indicates the energy intensity within the window. Indicates the strength of the trend. This indicates the calculation of the exponential moving average, where L(p) represents the long-term trend and S(p) represents the short-term trend. Represents a constant; The state vector and injection are determined by the following formula: (6) (7) (8) Where z represents the state vector and c represents the condition vector. Represents a state-mapping network. This represents the latent vector after the injected state. Let represent the implicit vector at the initial position.

5. The generation method according to claim 1, characterized in that, The abstract strategy description for reasoning and generating the structured semantic object includes: The structured semantic object is validated to determine if there are any logical contradictions; Determine whether the structured semantic object is complete; if incomplete, complete it. The system uses strategy templates and best practice libraries to reason about the structured semantic objects to generate abstract description strategies. The reasoning process is confined to the rules of a financial logic rule base, which contains multiple rules based on financial trading practices and risk management theories.

6. The generation method according to claim 5, characterized in that, The strategy utilizes policy templates and best practice libraries to reason about and generate abstract description strategies for the structured semantic objects being completed, including: Select and sort appropriate templates from the strategy templates and best practice library; Instantiate and populate the slot list of the highest score template or combined template to obtain the populated slot list; The final set of slots is obtained by performing conflict detection and constraint solving on the filled slot list; A strategy graph structure is generated based on the slot set; The strategy graph structure is validated and structured text is generated. The structured text is compiled to obtain an abstract description strategy.

7. The generation method according to claim 1, characterized in that, The abstract policy description is compiled into an executable policy file using a framework code generator, including: The abstract strategy description is parsed to generate configuration code; The framework code generator is used to translate the logic in the abstract strategy description line by line into executable code. Comment out the executable code and output an executable strategy file.

8. The generation method according to claim 7, characterized in that, The abstract strategy description is parsed to generate configuration code, including: Static analysis is performed on the abstract strategy description to obtain the tags and summary fields of the abstract strategy description; Using the aforementioned tags and summary fields, a search is performed to obtain logically similar historical strategies; Filter the database to retrieve results relevant to the historical strategy.

9. A device for generating a quantitative trading strategy, characterized in that, include: The preprocessing unit is used to receive user input requirements and preprocess those requirements. The extraction unit is used to extract the preprocessed entities and intents of the requirements using a multi-task language model; A generation unit is used to generate a structured semantic object based on the entity and the intent; The reasoning unit is used to reason about the structured semantic object to generate an abstract strategy description; The compilation unit is used to compile the abstract strategy description into an executable strategy file using the framework code generator.

10. A computer-readable storage medium comprising a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the steps of the method for generating a quantitative trading strategy as described in any one of claims 1 to 8.

Citation Information

Patent Citations

  • Method for laboratory examination and interpretation of physical examination report based on hybrid expert model

    CN118841155A

  • Intelligent programming auxiliary method and system based on multi-mode AI language model

    CN120315685A

  • Quantitative strategy natural language construction and interpretability auxiliary system based on multi-agent collaborative architecture

    CN120524938A

Cited By

  • Futures quantitative back-testing method and system based on large model

    CN121937218A