A method and apparatus for generating financial strategy codes based on a large language model
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-31
- Publication Date
- 2026-08-14
AI Technical Summary
[0003]有鉴于此,本申请提供一种基于大语言模型的金融策略代码生成方法及装置,主要目的在于解决现有基于大语言模型的金融策略代码生成有效性差的问题
本申请提供了一种基于大语言模型的金融策略代码生成方法及装置,与现有技术相比,本申请实施例通过获取金融策略文本,并基于大语言模型对所述金融策略文本进行实体解析,得到策略事件标准化表示,所述策略事件标准化表示由策略因子、计算规则与筛选条件组成;基于金融领域知识库查询与所述策略事件标准化表示匹配的多个策略改进方案文本,多个所述策略改进方案文本之间具有相同的意图;基于所述策略改进方案文本、所述策略事件标准化表示以及方案约束信息生成策略代码,所述方案约束包括代码编译的语义约束、语法约束以及规范约束中至少一项,大大提升金融策略代码的生成效率,避免人为编译错误的发生,同时,结合大语言模型生成的策略代码更加兼具创新性和可解释性。
Smart Images

Figure CN122044534B_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of computer development technology, and in particular to a method and apparatus for generating financial strategy codes based on a large language model. Background Technology
[0002] In the financial field, the core of quantitative investment lies in the generation, implementation, and continuous iteration of trading strategies. A complete, backtestable trading strategy not only includes core financial factors (such as the alpha factor) but also encompasses a series of logical processes, including signal generation mechanisms, portfolio construction, position management, and risk control. Currently, investment ideas can be described in natural language or informally and transformed into rigorously structured, backtestable, and live-trading strategy code files (such as complete Python backtesting scripts) to execute trading strategies. Existing trading strategy code files rely on manual coding by researchers or development engineers, or on automated factor mining using the Genetic Programming (GP) paradigm. However, manual coding is inefficient, time-consuming, highly dependent on personal experience, and suffers from significant variations in code quality and style. It also incurs high costs for strategy iteration and maintenance and is prone to discrepancies between the implemented logic and the intended design. Furthermore, the GP paradigm, which involves the combination and optimization of mathematical expressions, struggles to construct complete strategies with complex logic. The generated results often lack clear economic meaning, have weak interpretability, poor out-of-sample stability, and significant overfitting risk. Therefore, a financial strategy code generation method based on a large language model is urgently needed to address these issues. Summary of the Invention
[0003] In view of this, this application provides a method and apparatus for generating financial strategy codes based on a large language model, the main purpose of which is to solve the problem of poor effectiveness of existing financial strategy code generation based on large language models.
[0004] According to one aspect of this application, a method for generating financial strategy codes based on a large language model is provided, comprising: The financial strategy text is obtained, and entity parsing is performed on the financial strategy text based on a large language model to obtain a standardized representation of the strategy event. The standardized representation of the strategy event consists of strategy factors, calculation rules and screening conditions. Based on a financial knowledge base query, multiple strategy improvement scheme texts are matched with the standardized representation of the strategy event, and these multiple strategy improvement scheme texts have the same intent; Based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information, strategy code is generated. The scheme constraints include at least one of the semantic constraints, syntax constraints, and specification constraints of code compilation.
[0005] Furthermore, the entity parsing of the financial strategy text based on a large language model to obtain a standardized representation of the strategy event includes: The financial strategy text is used as the input parameter of the large language model for semantic parsing to obtain financial entities, operators, and logical relationships. The strategy factors, calculation rules, and screening conditions are determined based on the financial entity, the operator, and the logical relationship. The standardized representation of the strategy event is constructed based on the strategy factors, the calculation rules, and the screening conditions. The standardized representation of the strategy event is in standardized JSON format data.
[0006] Furthermore, before querying the text of multiple strategy improvement schemes based on the financial domain knowledge base and matching it with the standardized representation of the strategy event, the method further includes: A knowledge base for the financial field is built based on factor templates, historical performance data, and risk indicators of different financial strategies. The text of the multiple strategy improvement schemes based on matching financial domain knowledge base queries with the standardized representation of the strategy events includes: The query intent is determined according to the strategy factors, calculation rules and filtering conditions in the standardized representation of the strategy event, and the query intent is matched with the factor templates, historical performance data and risk indicators in the financial domain knowledge base to determine multiple strategy improvement scheme texts.
[0007] Furthermore, before generating strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information, the method further includes: Output the text of the proposed strategy improvement plan in the user interface; After receiving a confirmation command through the user interface, obtain the constraint information of the strategy improvement scheme text.
[0008] Furthermore, the generation of strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information includes: The code generator is invoked, and the code generator is used to determine the text of the strategy improvement scheme and the list of strategy operation parameters in the standardized representation of the strategy event; The strategy template that matches the strategy operation parameter list is determined from the template index, and the strategy operation parameter list is mapped to the strategy template to obtain the initial code; Obtain a code sample, and adjust the initial code by combining the code sample and the scheme constraint information through a hint constraint model to obtain intermediate code; Add auxiliary code to the intermediate code to obtain the strategy code.
[0009] Furthermore, the method also includes: Retrieve historical simulation samples and run the strategy code based on the historical simulation samples to obtain strategy indicators; If the strategy indicator matches the preset indicator condition, then the strategy code is output; If the strategy indicator does not match the preset indicator conditions, a code adjustment strategy is obtained, and the strategy code is adjusted based on the code adjustment strategy.
[0010] Furthermore, the acquisition of the financial strategy text includes: Receive financial strategy text entered by the user through the user interface; The financial strategy text is cleaned to obtain the financial strategy text to be parsed by entity parsing. The text cleaning includes identifier blacklist cleaning and text blacklist cleaning.
[0011] According to another aspect of this application, a financial strategy code generation apparatus based on a large language model is provided, comprising: The acquisition module is used to acquire financial strategy text and perform entity parsing on the financial strategy text based on a large language model to obtain a standardized representation of strategy events. The standardized representation of strategy events consists of strategy factors, calculation rules and screening conditions. The query module is used to query multiple strategy improvement scheme texts that match the standardized representation of the strategy event based on a financial domain knowledge base, and the multiple strategy improvement scheme texts have the same intent; The generation module is used to generate strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information. The scheme constraints include at least one of the semantic constraints, syntax constraints, and specification constraints of code compilation.
[0012] Furthermore, The acquisition module is specifically used to take the financial strategy text as the input parameter of the large language model, perform semantic parsing, and obtain financial entities, operators, and logical relationships; determine the composition of strategy factors, calculation rules, and screening conditions based on the financial entities, operators, and logical relationships, and construct the standardized representation of the strategy event based on the strategy factors, calculation rules, and screening conditions, wherein the standardized representation of the strategy event is standardized JSON format data.
[0013] Furthermore, the device also includes: a construction module, The construction module is used to build a knowledge base in the financial field based on factor templates of different financial strategies, historical performance data and risk indicators; The query module is specifically used to determine the query intent according to the strategy factors, calculation rules and filtering conditions in the standardized representation of the strategy event, and to match the query intent with the factor templates, historical performance data and risk indicators in the financial domain knowledge base to determine multiple strategy improvement scheme texts.
[0014] Furthermore, The acquisition module is also used to output the strategy improvement scheme text in the user interaction interface; and after receiving a confirmation instruction through the user interaction interface, to acquire the scheme constraint information of the strategy improvement scheme text.
[0015] Furthermore, The generation strategy specifically involves invoking a code generator and using the code generator to determine the strategy improvement scheme text and the strategy operation parameter list in the standardized representation of the strategy event; determining a strategy template adapted to the strategy operation parameter list from the template index, and mapping the strategy operation parameter list to the strategy template to obtain initial code; obtaining a code sample, and adjusting the initial code using a hint constraint model combined with the code sample and the scheme constraint information to obtain intermediate code; and adding auxiliary code to the intermediate code to obtain strategy code.
[0016] Furthermore, the device also includes: The execution module is used to retrieve historical simulation samples and run the strategy code based on the historical simulation samples to obtain strategy indicators; if the strategy indicators match preset indicator conditions, the strategy code is output; if the strategy indicators do not match preset indicator conditions, a code adjustment strategy is obtained and the strategy code is adjusted based on the code adjustment strategy.
[0017] Furthermore, The acquisition module is specifically used to receive financial strategy text entered by the user through the user interaction interface; perform text cleaning on the financial strategy text to obtain financial strategy text to be parsed by entity, wherein the text cleaning includes identifier blacklist cleaning and text blacklist cleaning.
[0018] According to another aspect of this application, a storage medium is provided, wherein at least one executable instruction is stored therein, the executable instruction causing a processor to perform operations corresponding to the above-described method for generating financial strategy code based on a large language model.
[0019] According to another aspect of this application, a terminal is provided, comprising: a processor, a memory, a communication interface, and a communication bus, wherein the processor, the memory, and the communication interface communicate with each other through the communication bus; The memory is used to store at least one executable instruction, which causes the processor to perform the operation corresponding to the above-described financial strategy code generation method based on a large language model.
[0020] By employing the above technical solutions, the technical solutions provided in the embodiments of this application have at least the following advantages: This application provides a method and apparatus for generating financial strategy code based on a large language model. Compared with the prior art, the embodiments of this application obtain financial strategy text and perform entity parsing on the financial strategy text based on a large language model to obtain a standardized representation of strategy events. The standardized representation of strategy events consists of strategy factors, calculation rules, and screening conditions. Based on a financial domain knowledge base, multiple strategy improvement scheme texts that match the standardized representation of strategy events are queried, and the multiple strategy improvement scheme texts have the same intent. Based on the strategy improvement scheme texts, the standardized representation of strategy events, and scheme constraint information, strategy code is generated. The scheme constraints include at least one of semantic constraints, syntactic constraints, and normative constraints for code compilation. This greatly improves the generation efficiency of financial strategy code, avoids human compilation errors, and the strategy code generated by combining the large language model is more innovative and interpretable.
[0021] The above description is only an overview of the technical solution of this application. In order to better understand the technical means of this application and to implement it in accordance with the contents of the specification, and to make the above and other objects, features and advantages of this application more obvious and understandable, the following are specific embodiments of this application. Attached Figure Description
[0022] Various other advantages and benefits will become apparent to those skilled in the art upon reading the following detailed description of preferred embodiments. The accompanying drawings are for illustrative purposes only and are not intended to limit the scope of this application. Furthermore, the same reference numerals denote the same parts throughout the drawings. In the drawings: Figure 1 The flowchart illustrates a financial strategy code generation method based on a large language model provided in an embodiment of this application. Figure 2 This illustration shows a block diagram of a financial strategy code generation device based on a large language model, as provided in an embodiment of this application. Figure 3 A schematic diagram of the structure of a terminal provided in an embodiment of this application is shown. Detailed Implementation
[0023] Exemplary embodiments of the present disclosure will now be described in more detail with reference to the accompanying drawings. While exemplary embodiments of the present disclosure are shown in the drawings, it should be understood that the present disclosure may be implemented in various forms and should not be limited to the embodiments set forth herein. Rather, these embodiments are provided so that this disclosure will be thorough and complete, and will fully convey the scope of the disclosure to those skilled in the art.
[0024] It should be noted that the terms "first," "second," etc., in the specification, claims, and accompanying drawings of this application are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments of this application described herein can be implemented in orders other than those illustrated or described herein. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion; for example, a process, method, system, product, or apparatus that comprises a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.
[0025] The embodiments of this invention can acquire and process relevant data based on artificial intelligence technology. Artificial intelligence (AI) refers to the theories, methods, technologies, and application systems that use digital computers or machines controlled by digital computers to simulate, extend, and expand human intelligence, perceive the environment, acquire knowledge, and use that knowledge to obtain optimal results.
[0026] Foundational technologies for artificial intelligence generally include sensors, dedicated AI chips, cloud computing, distributed storage, big data processing, operating / interactive systems, and mechatronics. AI software technologies mainly encompass computer vision, robotics, biometrics, speech processing, natural language processing, and machine learning / deep learning.
[0027] Based on this, in one embodiment, the present invention provides a method for generating financial strategy code based on a large language model. Taking the application of this method to computer devices such as servers as an example, the server can be an independent server or a cloud server that provides basic cloud computing services such as cloud services, cloud databases, cloud computing, cloud functions, cloud storage, network services, cloud communication, middleware services, domain name services, security services, content delivery networks (CDN), and big data and artificial intelligence platforms, such as intelligent financial systems and digital financial platforms.
[0028] This application provides a method for generating financial strategy codes based on a large language model, such as... Figure 1 As shown, the method includes: 101. Obtain the financial strategy text and perform entity parsing on the financial strategy text based on the large language model to obtain a standardized representation of the strategy event.
[0029] In this embodiment, the current execution end serves as the execution entity for generating financial strategy code. The current execution end can be a code server, a code processing terminal, or an application system embedded in different financial platforms. This embodiment does not impose specific limitations. The financial strategy text is used to characterize the natural language text describing the generated financial strategy, for example, "screening stocks whose volatility is lower than the industry average and whose revenue growth rate ranks in the top 10% over the past 20 trading days." Furthermore, to identify the strategic intent of the financial strategy text, the current execution end can parse the financial strategy text based on a large language model. That is, the financial strategy text is used as model input, fed into the large language model for querying, to output a standardized representation of the strategy event. This standardized representation of the strategy event consists of strategy factors, calculation rules, and screening conditions. The strategy factors characterize the strategy parameters for generating the code, including but not limited to time parameters, amount parameters, and percentage parameters. The calculation rules characterize the calculation logic for generating the code, including but not limited to addition, multiplication, and percentage calculations. The screening conditions characterize the conditions for filtering the content in the financial text when converting it into code, including but not limited to past, future, and increase conditions. This embodiment does not impose specific limitations.
[0030] 102. Text of multiple strategy improvement schemes that match the standardized representation of the strategy event based on a knowledge base query in the financial field.
[0031] In this embodiment, the financial domain knowledge base is constructed based on knowledge information across the entire financial domain, primarily consisting of templates, historical data, and risk information. This allows for the querying of multiple strategy improvement scheme texts that match the standardized representation of strategy events. These multiple strategy improvement scheme texts share the same intent; in this case, intent refers to the desired outcome of converting a financial strategy into code. For example, multiple strategy improvement schemes achieving the same intent can be found. Each scheme's intent includes key quantitative evaluation indicators, such as expected return, maximum drawdown, and estimated computational cost. This embodiment does not impose specific limitations on these indicators. Furthermore, to facilitate user verification or filtering, at least three strategy improvement scheme texts are preferably selected.
[0032] 103. Generate strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information.
[0033] In this embodiment of the application, when generating strategy code, the current execution end uses the scheme strategy as a constraint for automatically generating code. At this time, the scheme constraint includes at least one of the semantic constraints, syntax constraints, and specification constraints of code compilation. Semantic constraints are used to characterize the constraints that the generated code semantics have computer language logic, such as "revenue growth rate" being correctly mapped to a financial data field. Syntax constraints are used to characterize the constraints that generate complete code, such as code that conforms to Python syntax. Specification constraints are used to characterize the constraints that apply to the code, such as on a specific platform. This embodiment of the application does not make specific limitations.
[0034] It should be noted that when generating strategy code, the current execution end can call a pre-configured code generator to generate high-quality, compileable and executable strategy code.
[0035] In another embodiment of this application, for further definition and explanation, the step of performing entity parsing on the financial strategy text based on a large language model to obtain a standardized representation of the strategy event includes: The financial strategy text is used as the input parameter of the large language model for semantic parsing to obtain financial entities, operators, and logical relationships. The strategy factors, calculation rules, and screening conditions are determined based on the financial entity, the operator, and the logical relationship, and a standardized representation of the strategy event is constructed based on the strategy factors, the calculation rules, and the screening conditions.
[0036] To accurately identify the strategic intent within financial strategy texts for standardized description, the current execution end first uses the financial strategy text as input parameters for a large language model during entity parsing. This semantic parsing yields financial entities, operators, and logical relationships. The large language model (LLM) is a deep learning-based natural language processing model trained on massive amounts of financial text. It possesses the ability to understand, generate, and reason about text. The large model is obtained through a multi-stage training process (pre-training, fine-tuning, RLHF) on a Transformer architecture (which relies on self-attention mechanisms to process long text sequences) with a massive number of parameters (typically billions to hundreds of billions). This model serves as the intent parser for deep semantic parsing, yielding financial entities, operators, and logical relationships. Financial entities refer to specific financial indicators or entry features, such as "volatility" or "revenue growth rate." Operators are comparative strategy operation symbols, such as "below" or "top 10%." Logical relationships are linguistic or word relationships representing the strategy logic, such as "filter" or "query." This embodiment does not impose specific limitations on these relationships. Furthermore, the strategy factors, calculation rules, and screening conditions are determined based on the financial entity, the operator, and the logical relationship. This can be determined based on a pre-trained large language model or a pre-established mapping relationship; this embodiment does not impose specific limitations. Finally, the obtained strategy factors, calculation rules, and screening conditions are used to construct a standardized representation of the strategy event.
[0037] It should be noted that the policy events constructed by the current execution end are represented in a standardized JSON format. The JSON object clearly defines the policy factors, calculation rules, and filtering conditions involved in the policy, so as to provide a machine-readable semantic foundation for subsequent automated processing.
[0038] In another embodiment of this application, for further definition and explanation, before the step of querying multiple strategy improvement scheme texts that match the standardized representation of the strategy event based on a financial domain knowledge base, the method further includes: A knowledge base for the financial field is built based on factor templates for different financial strategies, historical performance data, and risk indicators.
[0039] To determine strategy improvement proposals using knowledge across the entire financial sector, the current execution end pre-constructs a financial sector knowledge base based on factor templates for different financial strategies, historical performance data, and risk indicators. The factor templates are templates for improving different strategy factors, the historical performance data represents the historical performance of the financial strategies, and the risk indicators represent the financial risks of different strategy factors during execution. The constructed financial sector knowledge base can be in tabular or network diagram form; this embodiment does not impose specific limitations.
[0040] Correspondingly, the steps involve querying a financial knowledge base to find multiple strategy improvement schemes that match the standardized representation of the strategy event, including: The query intent is determined according to the strategy factors, calculation rules and filtering conditions in the standardized representation of the strategy event, and the query intent is matched with the factor templates, historical performance data and risk indicators in the financial domain knowledge base to determine multiple strategy improvement scheme texts.
[0041] To accurately determine the strategy improvement proposal text, after obtaining the strategy factors, calculation rules, and screening conditions, the current execution end first determines the query intent. At this point, the query can be performed based on Coze's large model workflow platform. Coze's large model can be pre-trained based on intent samples. After obtaining multiple query intents, the current execution end matches the query intents with factor templates, historical performance data, and risk indicators in the financial domain knowledge base to determine multiple strategy improvement proposal texts. During the matching process, matching and identification can still be performed based on Coze's large model workflow platform to obtain multiple strategy improvement proposal texts, such as improvement proposal texts for expected returns, maximum drawdown, and estimated calculation costs, so that users can make preliminary comparisons and decisions.
[0042] It should be noted that in some embodiments, the strategy improvement schemes for the same intent are used as a basis, and the strategy scheme suggestion nodes in the Coze workflow are generated autonomously by the Doubao 1.5 Pro large model.
[0043] In another embodiment of this application, for further definition and explanation, before the step of generating strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information, the method further includes: Output the text of the proposed strategy improvement plan in the user interface; After receiving a confirmation command through the user interface, obtain the constraint information of the strategy improvement scheme text.
[0044] To ensure the effectiveness of the strategy improvement plan text, the current execution end outputs the strategy improvement plan text through the user interface so that the user can make a decision. At this time, it can be displayed in the form of a visual card. This application embodiment does not make specific limitations.
[0045] In some embodiments, users can "adopt," "discard," or trigger "refine" operations to complete a decision on the strategy improvement proposal text. In one specific embodiment, after receiving a confirmation instruction through the user interface, the current execution terminal obtains the proposal constraint information of the strategy improvement proposal text. For example, if the user selects "refine," a dialog window will be activated to receive the proposal constraint information entered by the user in natural language as additional constraints, such as "restrict execution to the end of the trading day" or "add dynamic stop-loss based on 2.5 times ATR," to ensure the controllability and flexibility of the strategy generation process.
[0046] In one specific embodiment, the financial strategy text is "Select stocks with the top 10% revenue growth rate over the past 60 trading days," and the user-added scheme constraint information is "Execute the trade only at the end of the trading day (14:55) and set 2.5 times ATR (Average True Range) as the dynamic stop-loss condition." The intent obtained after parsing by the large language model is to integrate the core logic and additional constraints into a complete, executable strategy description. The scheme constraint information includes rule constraints, semantic constraints, and syntactic constraints. The rule constraints determine the target platform as "BigQuant," thereby locking down the libraries that need to be imported and the functions that must be implemented (such as handle_data). The semantic constraints ensure that "revenue growth rate" is correctly mapped to financial data fields (such as income_statement.operating_revenue), "top 10%" is correctly converted into ranking and percentage calculations, "end of the trading day" corresponds to a specific trading time judgment, and "ATR dynamic stop-loss" correctly implements its financial calculation logic. The syntactic constraints generate structurally complete code that conforms to Python syntax so that strategy code can be generated based on the code generator.
[0047] In another embodiment of this application, for further definition and explanation, the step of generating strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information includes: The code generator is invoked, and the code generator is used to determine the text of the strategy improvement scheme and the list of strategy operation parameters in the standardized representation of the strategy event; The strategy template that matches the strategy operation parameter list is determined from the template index, and the strategy operation parameter list is mapped to the strategy template to obtain the initial code; Obtain a code sample, and adjust the initial code by combining the code sample and the scheme constraint information through a hint constraint model to obtain intermediate code; Add auxiliary code to the intermediate code to obtain the strategy code.
[0048] To automatically and accurately generate strategy code, the current execution end first invokes the code generator when generating strategy code. The code generator then determines the strategy improvement proposal text and the list of strategy operation parameters in the standardized representation of strategy events. The strategy operation parameter list records "strategy-operation-parameter". Simultaneously, a strategy template adapted to the strategy operation parameter list is determined through a template index. This template index can be determined based on a financial knowledge base search. The template index is used to retrieve templates including, but not limited to, double moving averages, momentum, and arbitrage, to map the corresponding "strategy-operation-parameter" to the strategy template, obtaining the initial code. This involves mapping list elements one-to-one to placeholders in the template, forming the first version of the code.
[0049] Furthermore, the current execution end can obtain code examples from the "backtesting platform code snippets" set in the financial knowledge base, for example, obtaining the top 5 similar examples. Then, the current execution end uses a prompt constraint model to adjust the initial code in conjunction with the code examples and the scheme constraint information to obtain intermediate code. Here, the prompt constraint model can be RAG (Rapid Advice Constraint Model), a technique that enhances the output of a large model by introducing retrieved external knowledge during the generation process. It can guide the model to generate more accurate answers by using prompts to combine search results. In some embodiments, the code generator can concatenate the strategy template with user-supplemented scheme constraint information into a query, input the code example and query together into the RAG prompt constraint model, and output a code segment that conforms to the platform syntax and is consistent with the example style, completing the strategy script completion; this is the intermediate code.
[0050] Finally, to obtain complete and usable strategy code, auxiliary code is added to the intermediate code to obtain the strategy code. This involves automatically appending header comments, exception handling, and other auxiliary code. In some embodiments, code based on Python header files, header comments, and exception handling can also be generated.
[0051] In a specific implementation example, taking high-frequency trading every minute as an example, the strategy template can be: {import talib # Talib usage example code def initialize(context): Initialization parameters; context._short_lag = 5# Short period order; context._long_lag = 10# Long period length; context._stock_pool_list = ['000001.SZ', '000002.SZ'...] ; # Initialize the static list of stocks to be traded, context._stock_pool_list. If the stock pool is fixed for a long time, determine it in the initialize function; if it changes dynamically over time, determine it in before_trading. return def before_trading(context, data): Daily Pre-Market Analysis current_datetime = data.trading_day_dt # Get the current date in datetime format (year, month, day, hour, minute, second) ifcontext.rebalance_period.is_signal_date(current_datetime): # Determine if the stock list is updated regularly over a long period, such as weekly or quarterly. context._stock_pool_list =context._current_data['instrument'].tolist() # Define the daily changing trading object code sequence context._stock_pool_list, obtained from context._current_data['instrument']. # Fixed statement, daily subscription to the required securities list and minute-by-minute market data, from The data is obtained from context.subscribe_bar(context._stock_pool_list, '1m'). # Daily pre-market initialization of the number of minute-level candlesticks already passed for the day context._ix = 0 def handle_data(context, data): "Minute-based event trigger operation" # Check if context._current_data exists # Fixed syntax: Use data.history to retrieve all historical minute-level closing price sequences since the opening of the current day, and use data.current to retrieve data for the current backtesting period. market_data_current = data.current('000001.SZ',[ ... ]) market_data_his = data.history('000001.SZ',[ ... ], context._ix, '1m') Add one minute-frequency candlestick count record context._ix += 1 # Check if there is historical data if len(market_data_his) == 0: return # Get the current closing price close_current = market_data_current['close'] # Convert to pandas sequences and floating-point numbers (necessary floating-point conversion before using the talib library) close = market_data['close'].values.astype('float64') volume = market_data['volume'].values.astype('float64') # Calculate a simple moving average using talib ma5 = talib.SMA(close, timeperiod=context._short_lag) # Data length validation if len(ma5)<2: print("Insufficient data length, skipping") return # Obtain specific technical indicator values current_ma5 = ma5[-1] # Get the latest closing price MA5 previous_ma5 = ma5[-2] # Get the closing price of the previous period's MA5 avg_volume_10=talib.SMA(volume,timeperiod=context._long_lag)[-1]# Get the latest MA10 of the trading volume # Check if the value required by talib is empty; if empty, return the function. if np.isnan(current_ma5) or np.isnan(previous_ma5) or np.isnan(avg_volume_10) or np.isnan(close_current): return # Subsequent processing logic..... return # Note that the talib.STOCH method requires at least three parameters: high, low, and close, and only returns the k and d values; the J value needs to be calculated manually. # k, d = talib.STOCH( #high,# highest price sequence #low,# Lowest price sequence #close,# Closing price sequence #fastk_period=5, # The calculation period for the K value (default 5) #slowk_period=3, # The smoothing period for the K value (default 3, which is the calculation period for the D value). #slowk_matype=0, # The type of moving average for the K value (0 = simple moving average) #slowd_period=3, # The smoothing period for the D value (default 3) #slowd_matype=0# The type of moving average for the D value (0 = simple moving average) # ) # j = 3k - 2d }
[0052] In another embodiment of this application, for further definition and explanation, the steps also include: Retrieve historical simulation samples and run the strategy code based on the historical simulation samples to obtain strategy indicators; If the strategy indicator matches the preset indicator condition, then the strategy code is output; If the strategy indicator does not match the preset indicator conditions, a code adjustment strategy is obtained, and the strategy code is adjusted based on the code adjustment strategy.
[0053] To improve the effectiveness of the strategy code, enhance its adaptability and evolutionary capabilities, and significantly lower the barrier to entry for quantitative investment, the obtained strategy code can also undergo backtesting verification. This involves directly sending the strategy code to a backtesting interface for performance validation and other backtesting tests. Specifically, the execution end first retrieves historical simulation samples and runs the strategy code through the backtesting interface, generating strategy metrics and outputting a detailed report containing multiple performance indicators such as Sharpe ratio, annualized return, and maximum drawdown, serving as the backtesting result. The execution end can also perform multi-dimensional analysis of the backtesting results and generate optimization suggestions based on preset rules. Furthermore, users can manually adjust the description of the financial strategy text or the scheme constraint information based on the backtesting results and system prompts, allowing them to restart a new round of optimization iterations from step 101. This forms an efficient, minute-level closed-loop workflow of "AI recommendation—human decision-making—code generation—backtesting verification," continuously improving strategy performance. In addition, after obtaining the strategy indicators, the current execution end is compared with the preset indicator conditions to determine the validity of the strategy code. At this time, the preset indicator conditions can be a pre-set indicator threshold or a specific range of indicators, which can be configured based on indicator requirements or backtesting requirements. This application embodiment does not make specific limitations.
[0054] If the strategy indicator matches the preset indicator condition, then the strategy code is output; If the strategy indicator does not match the preset indicator conditions, a code adjustment strategy is obtained, and the strategy code is adjusted based on the code adjustment strategy.
[0055] In another embodiment of this application, for further definition and explanation, the step of obtaining the financial strategy text includes: Receive financial strategy text entered by the user through the user interface; The financial strategy text is cleaned to obtain the financial strategy text to be parsed for entity analysis.
[0056] To ensure the validity of the financial strategy text, the current execution terminal first receives the financial strategy text entered by the user through the user interaction interface. At this time, since there may be some typos or sensitive words in the financial strategy text, the financial strategy text can be cleaned to obtain the financial strategy text to be parsed by entity. The text cleaning includes identifier blacklist cleaning and text blacklist cleaning. Typos can be cleaned based on the identifier blacklist, and sensitive words can be cleaned based on the text blacklist. This application embodiment does not make specific limitations.
[0057] This application provides a method for generating financial strategy code based on a large language model. Compared with existing technologies, this application obtains financial strategy text and performs entity parsing on the text based on a large language model to obtain a standardized representation of strategy events. The standardized representation of strategy events consists of strategy factors, calculation rules, and screening conditions. Multiple strategy improvement scheme texts matching the standardized representation of strategy events are queried from a financial domain knowledge base. These multiple strategy improvement scheme texts share the same intent. Strategy code is generated based on the strategy improvement scheme texts, the standardized representation of strategy events, and scheme constraint information. The scheme constraints include at least one of semantic constraints, syntactic constraints, and normative constraints for code compilation. This significantly improves the generation efficiency of financial strategy code, avoids human compilation errors, and, in conjunction with the large language model, the generated strategy code is more innovative and interpretable.
[0058] Furthermore, as a response to the above Figure 1 The implementation of the method shown in this application provides a financial strategy code generation device based on a large language model, such as... Figure 2 As shown, the device includes: The acquisition module 21 is used to acquire financial strategy text and perform entity parsing on the financial strategy text based on a large language model to obtain a standardized representation of strategy events. The standardized representation of strategy events consists of strategy factors, calculation rules and screening conditions. Query module 22 is used to query multiple strategy improvement scheme texts that match the standardized representation of the strategy event based on a financial domain knowledge base, wherein the multiple strategy improvement scheme texts have the same intent; The generation module 23 is used to generate strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information. The scheme constraints include at least one of the semantic constraints, syntax constraints, and specification constraints of code compilation.
[0059] Furthermore, The acquisition module is specifically used to take the financial strategy text as the input parameter of the large language model, perform semantic parsing, and obtain financial entities, operators, and logical relationships; determine the composition of strategy factors, calculation rules, and screening conditions based on the financial entities, operators, and logical relationships, and construct the standardized representation of the strategy event based on the strategy factors, calculation rules, and screening conditions, wherein the standardized representation of the strategy event is standardized JSON format data.
[0060] Furthermore, the device also includes: a construction module, The construction module is used to build a knowledge base in the financial field based on factor templates of different financial strategies, historical performance data and risk indicators; The query module is specifically used to determine the query intent according to the strategy factors, calculation rules and filtering conditions in the standardized representation of the strategy event, and to match the query intent with the factor templates, historical performance data and risk indicators in the financial domain knowledge base to determine multiple strategy improvement scheme texts.
[0061] Furthermore, The acquisition module is also used to output the strategy improvement scheme text in the user interaction interface; and after receiving a confirmation instruction through the user interaction interface, to acquire the scheme constraint information of the strategy improvement scheme text.
[0062] Furthermore, The generation strategy specifically involves invoking a code generator and using the code generator to determine the strategy improvement scheme text and the strategy operation parameter list in the standardized representation of the strategy event; determining a strategy template adapted to the strategy operation parameter list from the template index, and mapping the strategy operation parameter list to the strategy template to obtain initial code; obtaining a code sample, and adjusting the initial code using a hint constraint model combined with the code sample and the scheme constraint information to obtain intermediate code; and adding auxiliary code to the intermediate code to obtain strategy code.
[0063] Furthermore, the device also includes: The execution module is used to retrieve historical simulation samples and run the strategy code based on the historical simulation samples to obtain strategy indicators; if the strategy indicators match preset indicator conditions, the strategy code is output; if the strategy indicators do not match preset indicator conditions, a code adjustment strategy is obtained and the strategy code is adjusted based on the code adjustment strategy.
[0064] Furthermore, The acquisition module is specifically used to receive financial strategy text entered by the user through the user interaction interface; perform text cleaning on the financial strategy text to obtain financial strategy text to be parsed by entity, wherein the text cleaning includes identifier blacklist cleaning and text blacklist cleaning.
[0065] This application provides a financial strategy code generation device based on a large language model. Compared with the prior art, this application obtains financial strategy text and performs entity parsing on the financial strategy text based on a large language model to obtain a standardized representation of strategy events. The standardized representation of strategy events consists of strategy factors, calculation rules, and screening conditions. Multiple strategy improvement scheme texts matching the standardized representation of strategy events are queried based on a financial domain knowledge base. These multiple strategy improvement scheme texts share the same intent. Strategy code is generated based on the strategy improvement scheme texts, the standardized representation of strategy events, and scheme constraint information. The scheme constraints include at least one of semantic constraints, syntactic constraints, and normative constraints for code compilation. This greatly improves the generation efficiency of financial strategy code, avoids human compilation errors, and, in conjunction with the large language model, the generated strategy code is more innovative and interpretable.
[0066] According to one embodiment of this application, a storage medium is provided, the storage medium storing at least one executable instruction, which can execute the financial strategy code generation method based on a large language model in any of the above method embodiments.
[0067] Figure 3 The diagram shows a structural schematic of a terminal according to one embodiment of the present application. The specific embodiments of the present application do not limit the specific implementation of the terminal.
[0068] like Figure 3 As shown, the terminal may include: a processor 302, a communications interface 304, a memory 306, and a communications bus 308.
[0069] The processor 302, communication interface 304, and memory 306 communicate with each other via communication bus 308.
[0070] Communication interface 304 is used to communicate with other network elements such as clients or other servers.
[0071] The processor 302 is used to execute program 310, specifically to execute the relevant steps in the above embodiment of the financial strategy code generation method based on a large language model.
[0072] Specifically, program 310 may include program code that includes computer operation instructions.
[0073] Processor 302 may be a central processing unit (CPU), an application-specific integrated circuit (ASIC), or one or more integrated circuits configured to implement the embodiments of this application. The terminal includes one or more processors, which may be processors of the same type, such as one or more CPUs; or they may be processors of different types, such as one or more CPUs and one or more ASICs.
[0074] Memory 306 is used to store program 310. Memory 306 may include high-speed RAM memory, and may also include non-volatile memory, such as at least one disk storage device.
[0075] Specifically, program 310 can be used to cause processor 302 to perform the following operations: The financial strategy text is obtained, and entity parsing is performed on the financial strategy text based on a large language model to obtain a standardized representation of the strategy event. The standardized representation of the strategy event consists of strategy factors, calculation rules and screening conditions. Based on a financial knowledge base query, multiple strategy improvement scheme texts are matched with the standardized representation of the strategy event, and these multiple strategy improvement scheme texts have the same intent; Based on the policy improvement scheme text, the standardized representation of the policy event, and the scheme constraint information, policy code is generated. The scheme constraints include at least one of semantic constraints, syntactic constraints, and specification constraints for code compilation. Obviously, those skilled in the art should understand that the modules or steps of this application described above can be implemented using general-purpose computing devices. They can be centralized on a single computing device or distributed across a network of multiple computing devices. Optionally, they can be implemented using computer-executable program code, thereby storing them in a storage device for execution by a computing device. Furthermore, in some cases, the steps shown or described can be performed in a different order than presented here, or they can be fabricated as separate integrated circuit modules, or multiple modules or steps can be fabricated as a single integrated circuit module. Thus, this application is not limited to any particular hardware and software combination.
[0076] The above description is merely a preferred embodiment of this application and is not intended to limit this application. Various modifications and variations can be made to this application by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of this application should be included within the scope of protection of this application.
Claims
1. A method for generating financial strategy codes based on a large language model, characterized in that, include: The financial strategy text is obtained, and entity parsing is performed on the financial strategy text based on a large language model to obtain a standardized representation of the strategy event. The standardized representation of the strategy event consists of strategy factors, calculation rules and screening conditions. Based on a financial knowledge base query, multiple strategy improvement scheme texts are matched with the standardized representation of the strategy event, and these multiple strategy improvement scheme texts have the same intent; Based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information, strategy code is generated. The scheme constraints include at least one of the semantic constraints, syntax constraints, and specification constraints of code compilation. The entity parsing of the financial strategy text based on a large language model to obtain a standardized representation of the strategy event includes: The financial strategy text is used as the input parameter of the large language model for semantic parsing to obtain financial entities, operators, and logical relationships. Based on the financial entity, the operator, and the logical relationship, the strategy factor, calculation rule, and screening condition are determined, and the standardized representation of the strategy event is constructed based on the strategy factor, the calculation rule, and the screening condition. The standardized representation of the strategy event is standardized JSON format data. Before querying the text of multiple strategy improvement schemes based on a financial domain knowledge base and matching it with the standardized representation of the strategy event, the method further includes: A knowledge base for the financial field is built based on factor templates, historical performance data, and risk indicators of different financial strategies. The text of the multiple strategy improvement schemes based on matching financial domain knowledge base queries with the standardized representation of the strategy events includes: The query intent is determined according to the strategy factors, calculation rules and filtering conditions in the standardized representation of the strategy event, and the query intent is matched with the factor templates, historical performance data and risk indicators in the financial knowledge base to determine multiple strategy improvement scheme texts; The generation of strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information includes: The code generator is invoked, and the code generator is used to determine the text of the strategy improvement scheme and the list of strategy operation parameters in the standardized representation of the strategy event; The strategy template that matches the strategy operation parameter list is determined from the template index, and the strategy operation parameter list is mapped to the strategy template to obtain the initial code; Obtain a code sample, and adjust the initial code by combining the code sample and the scheme constraint information through a hint constraint model to obtain intermediate code; Add auxiliary code to the intermediate code to obtain the strategy code.
2. The method according to claim 1, characterized in that, Before generating strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information, the method further includes: Output the text of the proposed strategy improvement plan in the user interface; After receiving a confirmation command through the user interface, obtain the constraint information of the strategy improvement scheme text.
3. The method according to claim 1, characterized in that, The method further includes: Retrieve historical simulation samples and run the strategy code based on the historical simulation samples to obtain strategy indicators; If the strategy indicator matches the preset indicator condition, then the strategy code is output; If the strategy indicator does not match the preset indicator conditions, a code adjustment strategy is obtained, and the strategy code is adjusted based on the code adjustment strategy.
4. The method according to any one of claims 1-3, characterized in that, The obtained financial strategy text includes: Receive financial strategy text entered by the user through the user interface; The financial strategy text is cleaned to obtain the financial strategy text to be parsed by entity parsing. The text cleaning includes identifier blacklist cleaning and text blacklist cleaning.
5. A financial strategy code generation device based on a large language model, characterized in that, include: The acquisition module is used to acquire financial strategy text and perform entity parsing on the financial strategy text based on a large language model to obtain a standardized representation of strategy events. The standardized representation of strategy events consists of strategy factors, calculation rules and screening conditions. The query module is used to query multiple strategy improvement scheme texts that match the standardized representation of the strategy event based on a financial domain knowledge base, and the multiple strategy improvement scheme texts have the same intent; The generation module is used to generate strategy code based on the strategy improvement scheme text, the standardized representation of the strategy event, and the scheme constraint information. The scheme constraints include at least one of the semantic constraints, syntax constraints, and specification constraints of code compilation. Furthermore, The acquisition module is specifically used to take the financial strategy text as the input parameter of the large language model, perform semantic parsing, and obtain financial entities, operators, and logical relationships; determine strategy factors, calculation rules, and screening conditions based on the financial entities, operators, and logical relationships, and construct a standardized representation of the strategy event based on the strategy factors, calculation rules, and screening conditions, wherein the standardized representation of the strategy event is standardized JSON format data; The device further includes: a construction module, The construction module is used to build a knowledge base in the financial field based on factor templates of different financial strategies, historical performance data and risk indicators; The query module is specifically used to determine the query intent according to the strategy factors, calculation rules and filtering conditions in the standardized representation of the strategy event, and to match the query intent with the factor templates, historical performance data and risk indicators in the financial knowledge base to determine multiple strategy improvement scheme texts; The generation strategy specifically involves invoking a code generator and using the code generator to determine the strategy improvement scheme text and the strategy operation parameter list in the standardized representation of the strategy event; determining a strategy template adapted to the strategy operation parameter list from the template index, and mapping the strategy operation parameter list to the strategy template to obtain initial code; obtaining a code sample, and adjusting the initial code using a hint constraint model combined with the code sample and the scheme constraint information to obtain intermediate code; and adding auxiliary code to the intermediate code to obtain strategy code.
6. A computer-readable storage medium having a computer program / instructions stored thereon, characterized in that, When the computer program / instructions are executed by the processor, they implement the steps of the method of claim 1.
7. A computer device, comprising a memory, a processor, and a computer program stored in the memory, characterized in that, The processor executes the computer program to implement the steps of the method of claim 1.
Citation Information
Patent Citations
Workflow code automatic generation method driven by large model
CN120872310A
Method and system for automatically executing network security policy based on artificial intelligence large model
CN121056220A