### Stock and General Trading Setup Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Covers initialization, setting benchmarks, options, order costs, and subscribing to stock data. ```APIDOC ## Initialize Trading Environment ### Description Initializes the trading environment by setting the benchmark, trading options, and order costs. ### Method `initialize(context)` ### Parameters * **context** (object) - Required - The execution context. ### Code Example ```python def initialize(context): set_benchmark('000300.XSHG') set_option('use_real_price', True) set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') ``` --- ## Before Trading Start ### Description Sets up subscriptions before the trading day begins. ### Method `before_trading_start(context)` ### Parameters * **context** (object) - Required - The execution context. ### Code Example ```python def before_trading_start(context): subscribe('000001.XSHE','tick') ``` --- ## Handle Tick Data (Stock) ### Description Logs received tick data for stocks. ### Method `handle_tick(context, tick)` ### Parameters * **context** (object) - Required - The execution context. * **tick** (object) - Required - The tick data object. ### Code Example ```python def handle_tick(context, tick): log.info(tick) ``` --- ## After Trading End ### Description Cleans up subscriptions after the trading day concludes. ### Method `after_trading_end(context)` ### Parameters * **context** (object) - Required - The execution context. ### Code Example ```python def after_trading_end(context): unsubscribe_all() ``` ``` -------------------------------- ### Tick-Level Strategy Initialization Example Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Example of initializing a tick-level trading strategy, including setting up sub-portfolios for futures and scheduling daily market open/close functions. ```python def initialize(context): init_cash = context.portfolio.starting_cash set_subportfolios([SubPortfolioConfig(cash=init_cash, type='futures')]) g.code1 = 'RB1909.XSGE' run_daily(before_market_open, time='08:30', reference_security='RB9999.XSGE') run_daily(after_market_open, time='15:30', reference_security='RB9999.XSGE') ``` -------------------------------- ### Moving Average Crossover Strategy Example Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Provides a Python code example for a simple moving average crossover strategy. ```APIDOC ## Moving Average Crossover Strategy Example ### Description Implements a basic trading strategy that buys when the price is 5% above the 5-day moving average and sells when it's 5% below. ### Method `initialize(context)` and `handle_data(context, data)` ### Code Example ```python # Import the JoinQuant library import jqdata # Initialization function: Define target stock, benchmark, etc. def initialize(context): # Define the global variable for the target stock # 000001 (Stock: Ping An Bank) g.security = '000001.XSHE' # Set CSI 300 as the benchmark set_benchmark('000300.XSHG') # Enable dynamic复权 mode (real prices) set_option('use_real_price', True) # Function called at each time step (day or minute) def handle_data(context, data): security = g.security # Strategy logic: Buy if price > 1.05 * 5-day MA # Sell if price < 0.95 * 5-day MA pass ``` ``` -------------------------------- ### Run Daily Strategy at Specific Times (JoinQuant) Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Shows how to schedule a function to run daily at specific times within a JoinQuant strategy. This includes running at the start of the trading day, at a fixed time during the day, and after the market closes. ```python # Run at 09:00 daily run_daily(func, time='09:00') # Run at 14:50 daily run_daily(func, time='14:50') # Run at 15:30 daily run_daily(func, time='15:30') ``` -------------------------------- ### Get Open Orders Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Retrieves all outstanding (unfulfilled) orders. The 'get_open_orders' function is used for this. ```python get_open_orders() ``` -------------------------------- ### Simple Strategy Initialization and Execution (Python) Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Demonstrates a basic strategy structure in JoinQuant, including initializing a security and scheduling a daily market open function. This serves as a foundation for more complex strategies. ```python def initialize(context): # Define a global variable to store the stock to operate on g.security = '000001.XSHE' # Run the market_open function daily run_daily(market_open, time='every_bar') def market_open(context): if g.security not in context.portfolio.positions: order(g.security, 1000) else: order(g.security, -800) ``` -------------------------------- ### Strategy Initialization and State Management Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Information on initializing strategies, handling context objects, and the limitations of serialization for objects like database connections, open files, and network connections. ```APIDOC ## Strategy Initialization and State Management ### Description This section covers the `process_initialize` function, the serialization of context objects using `pickle`, and the restrictions on state size (30MB limit, with warnings at 20MB) to prevent malicious attacks. It also explains the recovery process, including code loading, restoring global variables, and the execution of `after_code_changed` if the strategy code has been modified. ### State Serialization Limitations Objects that involve I/O operations cannot be serialized: - Database connections (e.g., `query(valuation)`) - Open files (e.g., `open("some/path")`) - Network connections (e.g., `requests.get('')`) ### State Size Limit - **Maximum state size:** 30MB. Exceeding this limit will cause the save state operation to fail. - **Warning threshold:** 20MB. Logs will display a warning when the state size reaches this limit. ### Recovery Process 1. Load strategy code. 2. Restore `g`, `context`, and global variables defined outside functions from the saved state. 3. If the strategy code has changed and an `after_code_changed` function is defined, execute `after_code_changed(context)`. 4. Execute `process_initialize(context)`. ### `initialize` Function Behavior - The `initialize` function is executed only once during the entire backtesting/simulation lifecycle. - It is not executed on restart or after changing the backtest configuration. - To modify values from the previous `initialize` run after a code change, use the `after_code_changed` function. ### Simulation Start Time - If a simulation is created today and the start date is also today, it runs from the current time. - Functions scheduled to run before the current time will not execute. ### Failed Simulation Restart - If a simulation fails at time A and is restarted at time B, functions scheduled to run between A and B will not be executed. ### Simulation Resource Limits Simulations may be temporarily paused if: - The simulation owner has not accessed the JoinQuant website in the last month. - Accessing the website reactivates the simulation, which will then run the missed trading days the next day. ### General Resource Restrictions 1. Serialized state size: Maximum 30MB. 2. Function execution time: Maximum 1800 seconds per function. 3. Process memory usage: Maximum 3GB. Optimize strategies if these limits are exceeded, refer to common bug and warning solutions. ### Real Price Usage It is strongly recommended to use real prices for simulated trading by calling `set_option('use_real_price', True)`. ``` -------------------------------- ### Futures Account Initialization Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Details how to configure accounts for futures trading. ```APIDOC ## Initialize Futures Account ### Description Configures subportfolios to enable futures trading by setting the account type to 'futures'. Default accounts only allow stock and fund trading. ### Method `set_subportfolios(subportfolio_configs)` ### Parameters * **subportfolio_configs** (list of SubPortfolioConfig) - Required - A list containing SubPortfolioConfig objects. ### SubPortfolioConfig Object * **cash** (float) - Required - The initial cash for the subportfolio. * **type** (string) - Required - The type of the subportfolio, e.g., 'stock', 'futures'. ### Code Example (Single Futures Account) ```python def initialize(context): # Get initial cash init_cash = context.portfolio.starting_cash # Set the account for futures trading set_subportfolios([SubPortfolioConfig(cash=init_cash, type='futures')]) ``` --- ## Run Daily Futures Trading Logic ### Description Schedules a function to run daily, typically at the start of each trading bar, for futures strategies. Allows setting a reference security. ### Method `run_daily(func, time='every_bar', reference_security=None)` ### Parameters * **func** (function) - Required - The function to execute daily. * **time** (string) - Optional - The timing for execution, e.g., 'every_bar'. Defaults to 'every_bar'. * **reference_security** (string) - Optional - The reference security for the strategy (e.g., 'CU9999.XSGE'). Defaults to '000300.XSHG'. ### Code Example ```python # Define a custom function for market open def market_open(context): # Trading logic here pass # Schedule the function to run daily run_daily(market_open, time='every_bar', reference_security='CU9999.XSGE') ``` ``` -------------------------------- ### Get Current Time in Simulation Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Prints the current actual time within the simulation environment. This is useful for debugging and understanding execution timing. ```python print(datetime.datetime.now()) ``` -------------------------------- ### Python: Initialize Strategy Context Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Initializes the trading strategy context by setting up a query for valuation data. It also highlights limitations regarding the serialization of I/O objects like database connections and open files. ```python def process_initialize(context): g.__query = query(valuation) ``` -------------------------------- ### Margin Trading Account Initialization Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Explains how to initialize and configure accounts for margin trading (financing and securities lending). ```APIDOC ## Initialize Margin Trading Account ### Description Configures subportfolios to enable margin trading by setting the account type to 'stock_margin'. Initial stock accounts only allow basic stock and fund trading. ### Method `set_subportfolios(subportfolio_configs)` ### Parameters * **subportfolio_configs** (list of SubPortfolioConfig) - Required - A list containing SubPortfolioConfig objects. ### SubPortfolioConfig Object * **cash** (float) - Required - The initial cash for the subportfolio. * **type** (string) - Required - The type of the subportfolio, e.g., 'stock', 'futures', 'stock_margin'. ### Code Example (Single Margin Account) ```python def initialize(context): # Get initial cash init_cash = context.portfolio.starting_cash # Set the account for margin trading set_subportfolios([SubPortfolioConfig(cash=init_cash, type='stock_margin')]) ``` ### Code Example (Multiple Accounts) ```python def initialize(context): # Get initial cash and divide it init_cash = context.portfolio.starting_cash / 3 # Set subportfolios for stock, futures, and margin trading set_subportfolios([ SubPortfolioConfig(cash=init_cash, type='stock'), SubPortfolioConfig(cash=init_cash, type='index_futures'), SubPortfolioConfig(cash=init_cash, type='stock_margin') ]) ``` --- ## Get Margin Securities ### Description Retrieves a list of securities available for margin trading. Note: Data for the current incomplete trading day may not be available. ### Method `get_marginsec_stocks()` ### Response List of securities available for margin trading. ``` -------------------------------- ### Python: Configure Trading Environment and Costs Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Sets up the trading environment in Python, including setting a benchmark, enabling real prices, and defining stock transaction costs. This ensures accurate backtesting and simulation. ```python set_benchmark('000300.XSHG') set_option('use_real_price', True) set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') ``` -------------------------------- ### Portfolio Optimization API Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Documentation for using the portfolio optimizer, including supported optimization models and how to configure constraints for portfolio construction. ```APIDOC ## Portfolio Optimization API ### Description This section details the portfolio optimization feature, which allows users to construct and optimize investment portfolios based on various models and constraints. It covers supported optimization models and provides an example of how to use the optimizer in a trading strategy. ### Supported Optimization Models - **MinVariance**: Portfolio risk minimization (Mean-Variance Optimization). - **MaxProfit**: Portfolio return maximization. - **MaxSharpeRatio**: Portfolio Sharpe Ratio maximization. - **MinTrackingError**: Tracking Error minimization. - **RiskParity**: Risk Parity. - **MaxScore**: Portfolio asset scoring maximization. - **MinScore**: Portfolio asset scoring minimization. - **MaxFactorValue**: Factor value maximization. - **MinFactorValue**: Factor value minimization. - **Custom Constraints**: Optimization models with user-defined constraints. ### Example Usage ```python # Import necessary libraries import pandas as pd from jqdata import * from jqfactor import Factor from jqlib.optimizer import * # Initialize function def initialize(context): # Set benchmark set_benchmark('000300.XSHG') # Enable real price mode set_option('use_real_price', True) # Set stock order costs set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') # Optimizer settings g.optimizer = 2 # Set the optimization model to use optimize_model = { 1: "Model 1: Equal weight allocation", 2: "Model 2: Portfolio risk parity; Total stock weight limit 0-90%, ETF total weight limit 0-10%; Each asset weight limit not exceeding 10%", 3: "Model 3: Portfolio risk minimization (minimize portfolio variance); Total portfolio weight limit 90%-100%; Portfolio annualized return target lower limit 10%", 4: "Model 4: Maximize 'Popularity Index 5-day Moving Average'; Portfolio annualized return target lower limit 10%; Each asset weight limit not exceeding 20%", 5: "Model 5: Portfolio Sharpe Ratio maximization; Each asset weight limit not exceeding 10%" } print(f"Optimizing using: {optimize_model[g.optimizer]}") # Schedule functions to run # Before market open run_monthly(before_market_open, monthday=1, time='9:00', reference_security='000300.XSHG') # At market open run_monthly(market_open, monthday=1, time='9:30', reference_security='000300.XSHG') ## Function to run before market opens def before_market_open(context): print(f'Rebalancing date: {context.current_dt.date()}') # Select a portion of CSI 300 index components and a selected ETF to form a stock pool etf = [ '159902.XSHE', '159903.XSHE', '510050.XSHG', '510880.XSHG', '510440.XSHG', ] g.buy_list = list(get_index_stocks('000016.XSHG')[-15:]) + etf ## Function to run at market open def market_open(context): # Sell stocks not in the stock pool sell_list = set(context.portfolio.positions.keys()) - set(g.buy_list) for stock in sell_list: order_target_value(stock, 0) # Portfolio optimization model if g.optimizer == 1: # Model 1: Equal weight allocation optimized_weight = pd.Series(data=[1.0/len(g.buy_list)]*len(g.buy_list), index=g.buy_list) elif g.optimizer == 2: # Model 2: Portfolio risk parity with constraints... pass # Placeholder for actual implementation # ... other models ``` ``` -------------------------------- ### Python: Initialize Portfolio Optimizer Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Initializes the portfolio optimizer in Python by setting the desired optimization model. The `optimize_model` dictionary maps integer keys to descriptions of different optimization strategies. ```python g.optimizer = 2 optimize_model = { 1:"模型1:等权重配置", 2:"模型2:组合风险平价;股票的总权重限制为0到90%,ETF的总权重限制为0到10%;每只标的权重不超过10%", 3:"模型3:组合风险最小化(最小化组合方差);组合总权重限制为90%到100%;组合年化收益率目标下限为10%", 4:"模型4:'人气指标5日均值'最大化;组合年化收益率目标下限为10%;每只标的权重不超过20%", 5:"模型5:组合夏普比率最大化;每只标的权重不超过10%" } print("优化%s"%(optimize_model[g.optimizer])) ``` -------------------------------- ### Core Strategy Functions Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Functions for initializing and running trading strategies, including event callbacks and lifecycle management. ```APIDOC ## initialize ### Description Initialization function for a trading strategy. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def initialize(context): pass ``` ### Response None ``` ```APIDIDOC ## run_daily ### Description Runs a strategy daily. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def run_daily(context, data): pass ``` ### Response None ``` ```APIDOC ## run_weekly ### Description Runs a strategy weekly. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def run_weekly(context, data): pass ``` ### Response None ``` ```APIDOC ## run_monthly ### Description Runs a strategy monthly. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def run_monthly(context, data): pass ``` ### Response None ``` ```APIDOC ## handle_data ### Description Handles trading strategy execution based on market data. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def handle_data(context, data): pass ``` ### Response None ``` ```APIDOC ## on_event ### Description Callback for specific events during strategy execution. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def on_event(context, event): pass ``` ### Response None ``` ```APIDOC ## before_trading_start ### Description Function executed before the trading day starts. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def before_trading_start(context, data): pass ``` ### Response None ``` ```APIDOC ## after_trading_end ### Description Function executed after the trading day ends. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def after_trading_end(context, data): pass ``` ### Response None ``` ```APIDOC ## on_strategy_end ### Description Function called when the strategy execution finishes. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def on_strategy_end(context): pass ``` ### Response None ``` ```APIDOC ## process_initialize ### Description Function that runs when the program starts each time. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def process_initialize(context): pass ``` ### Response None ``` ```APIDOC ## after_code_changed ### Description Function executed after the strategy code is changed during simulation. ### Method Optional ### Endpoint N/A ### Parameters None ### Request Example ```python def after_code_changed(context): pass ``` ### Response None ``` -------------------------------- ### Strategy Configuration Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Functions to configure strategy parameters, including benchmark, order costs, slippage, and data modes. ```APIDOC ## set_benchmark ### Description Sets the benchmark for performance comparison. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python set_benchmark('0000001.XSHE') ``` ### Response None ``` ```APIDOC ## set_order_cost ### Description Sets commission and stamp duty for orders. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python set_order_cost(OrderCost(commission=0.001, stock_tax=0.001)) ``` ### Response None ``` ```APIDOC ## set_slippage ### Description Sets the slippage for orders. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python set_slippage(FixedSlippage(0.0001)) ``` ### Response None ``` ```APIDOC ## use_real_price ### Description Enables real price (dynamic adjustment) mode for backtesting. Recommended to enable. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python use_real_price(True) ``` ### Response None ``` ```APIDOC ## order_volume_ratio ### Description Sets the trading volume ratio for orders. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python order_volume_ratio(0.1) ``` ### Response None ``` ```APIDOC ## match_with_order_book ### Description Enables order book matching mode. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python match_with_order_book(True) ``` ### Response None ``` ```APIDOC ## set_universe ### Description Sets the universe of securities for backtesting (history specific). ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python set_universe(['0000001.XSHE', '0000002.XSHE']) ``` ### Response None ``` ```APIDOC ## set_commission ### Description Sets the commission rate (deprecated). ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python set_commission(commission=0.001) ``` ### Response None ``` ```APIDOC ## disable_cache ### Description Disables the cache. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python disable_cache() ``` ### Response None ``` ```APIDOC ## avoid_future_data ### Description Sets whether to enable the avoid future data mode. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python avoid_future_data(True) ``` ### Response None ``` -------------------------------- ### Initialize Margin Trading Account (Single) Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Initializes a margin trading account by setting the SubPortfolioConfig type to 'stock_margin'. This allows for direct margin trading operations. ```python def initialize(context): ## 设置单个账户 # 获取初始资金 init_cash = context.portfolio.starting_cash # 设定账户为融资融券账户,初始资金为 init_cash 变量代表的数值(如不使用设置多账户,默认只有subportfolios[0]一个账户,Portfolio 指向该账户。) set_subportfolios([SubPortfolioConfig(cash=init_cash, type='stock_margin')]) ``` -------------------------------- ### Factor Models and Customization Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Functions for applying factor models, performing neutralization, and data transformation. ```APIDOC ## alpha101 ### Description Applies Alpha 101 factors. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python alpha101(context, data, security='0000001.XSHE') ``` ### Response Alpha 101 factor value. ``` ```APIDOC ## alpha191 ### Description Applies Alpha 191 factors. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python alpha191(context, data, security='0000001.XSHE') ``` ### Response Alpha 191 factor value. ``` ```APIDOC ## technical_analysis ### Description Applies technical analysis indicators. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python technical_analysis('SMA', context, data, security='0000001.XSHE', period=20) ``` ### Response Technical indicator value. ``` ```APIDOC ## neutralize ### Description Performs neutralization on factor exposures. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python neutralize(factor_exposures, benchmark_exposures) ``` ### Response Neutralized factor exposures. ``` ```APIDOC ## winsorize ### Description Applies Winsorization (trimming extreme values) to data. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python winsorize(data, limits=(0.05, 0.95)) ``` ### Response Winsorized data. ``` ```APIDOC ## winsorize_med ### Description Applies Winsorization using the median. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python winsorize_med(data, limits=(0.05, 0.95)) ``` ### Response Median-Winsorized data. ``` ```APIDOC ## standardlize ### Description Applies standardization (z-score normalization) to data. ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python standardlize(data) ``` ### Response Standardized data. ``` -------------------------------- ### Initialize Margin Trading Accounts (Multiple) Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Initializes multiple subportfolios, including a margin trading account, by dividing the initial cash among them. Each subportfolio is configured with a specific type. ```python def initialize(context): # 获取初始资金,并等分为三份 init_cash = context.portfolio.starting_cash/3 # 设定subportfolios[0]为 股票和基金仓位,初始资金为 init_cash 变量代表的数值 # 设定subportfolios[1]为 金融期货仓位,初始资金为 init_cash 变量代表的数值 # 设定subportfolios[2]为 融资融券账户,初始资金为 init_cash 变量代表的数值 set_subportfolios([SubPortfolioConfig(cash=init_cash, type='stock'), SubPortfolioConfig(cash=init_cash, type='index_futures'), SubPortfolioConfig(cash=init_cash, type='stock_margin')]) ``` -------------------------------- ### 万圣节效应策略 Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view 实现万圣节效应策略,在10月15日后买入中国蓝筹股,并在次年5月15日后卖出。策略基于日期判断执行买卖操作,每次买入固定金额的股票。 ```python import jqdata def initialize(context): set_option('use_real_price', True) g.stocks = ['000001.XSHE','600000.XSHG','600019.XSHG','600028.XSHG','600030.XSHG','600036.XSHG','600519.XSHG','601398.XSHG','601857.XSHG','601988.XSHG'] def handle_data(context, data): cash = context.portfolio.available_cash / len(g.stocks) hist = history(1,'1d','close',g.stocks) for security in g.stocks: today = context.current_dt current_price = hist[security][0] if today.month == 10 and today.day > 15 and cash > current_price and context.portfolio.positions[security].closeable_amount == 0: order_value(security, cash) log.info("Buying %s" % (security)) elif today.month == 5 and today.day > 15 and context.portfolio.positions[security].closeable_amount > 0: order_target(security, 0) ``` -------------------------------- ### Portfolio Optimization Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Functions for defining optimization objectives, constraints, and bounds for portfolio construction. ```APIDOC ## target ### Description Defines the optimization objective function (only one can be selected). ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python target(SharpeRatio.target) ``` ### Response Optimization objective function. ``` ```APIDOC ## constraints ### Description Defines constraints for the total portfolio weights (one or more can be set). ### Method Any ### Endpoint N/A ### Parameters None ### Request Example ```python constraints(sum(weights) == 1) ``` ### Response Portfolio constraints. ``` ```APIDOC ## bounds ### Description Defines bounds for individual security weights in the portfolio (one or more can ``` -------------------------------- ### 获取股票收盘价并执行交易 Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view 获取指定股票过去五天的收盘价,计算五日平均价格,并根据当前价格与平均价格的对比执行买入或卖出操作。当当前价格高于五日均价的105%时买入,低于95%时卖出。 ```python close_data = attribute_history(security, 5, '1d', ['close']) MA5 = close_data['close'].mean() current_price = close_data['close'][-1] cash = context.portfolio.available_cash if (current_price > 1.05*MA5) and (cash>0): order_value(security, cash) log.info("Buying %s" % (security)) elif current_price < 0.95*MA5 and context.portfolio.positions[security].closeable_amount > 0: order_target(security, 0) log.info("Selling %s" % (security)) record(stock_price=current_price) ``` -------------------------------- ### Initialize Futures Trading Account Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Initializes a futures trading account by setting the SubPortfolioConfig type to 'futures'. This enables direct trading of futures contracts. ```python def initialize(context): ## 设置单个账户 # 获取初始资金 init_cash = context.portfolio.starting_cash # 设定账户为金融账户,初始资金为 init_cash 变量代表的数值(如不使用设置多账户,默认只有subportfolios[0]一个账户,Portfolio 指向该账户。) set_subportfolios([SubPortfolioConfig(cash=init_cash, type='futures')]) ``` -------------------------------- ### Futures Subscription and Tick Handling Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view This section details how to subscribe to futures for trading and how to handle tick data events. ```APIDOC ## Subscribe to Futures ### Description Subscribes to futures contracts to receive real-time tick data. ### Method `subscribe(security, frequency)` ### Parameters * **security** (string) - Required - The futures contract code (e.g., g.code1). * **frequency** (string) - Required - The data frequency, typically 'tick'. ### Response No explicit response, operation is performed. --- ## Handle Tick Data ### Description Defines the function to be called when new tick data is available for subscribed futures. ### Method `handle_tick(context, tick)` ### Parameters * **context** (object) - Required - The execution context. * **tick** (object) - Required - The tick data object. ### Code Example ```python def handle_tick(context, tick): # Get the latest tick data tick_data = get_current_tick(g.code1) print(tick_data) ``` --- ## Unsubscribe All Futures ### Description Unsubscribes from all currently subscribed futures contracts. ### Method `unsubscribe_all()` ### Response No explicit response, operation is performed. ``` -------------------------------- ### Moving Average Strategy Implementation Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Implements a moving average strategy that buys when the price is 5% above the 5-day moving average and sells when it's 5% below. It sets up the security to trade and the benchmark. ```python # 导入聚宽函数库 import jqdata # 初始化函数,设定要操作的股票、基准等等 def initialize(context): # 定义一个全局变量, 保存要操作的股票 # 000001(股票:平安银行) g.security = '000001.XSHE' # 设定沪深300作为基准 set_benchmark('000300.XSHG') # 开启动态复权模式(真实价格) set_option('use_real_price', True) # 每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次 def handle_data(context, data): security = g.security ``` -------------------------------- ### Performance Analysis Metrics Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Details various metrics for analyzing strategy performance, including returns, risk, and holdings. ```APIDOC ## Performance Analysis Metrics ### Description Provides a comprehensive set of metrics for evaluating trading strategy performance. ### Net Value Analysis * **Cumulative Return**: Total return over the backtest period. * **Log Cumulative Return**: Cumulative return plotted on a logarithmic scale. * **Daily Return**: Time series plot of daily returns. * **Cumulative Return Affected by Slippage**: Cumulative return calculated using daily returns adjusted for slippage. * **Annualized Return**: Final value of cumulative returns calculated annually. * **Monthly Return Time Series**: Final value of cumulative returns calculated monthly. * **Monthly Return Heatmap**: Visual representation of monthly returns. * **Monthly Return Frequency Distribution**: Distribution of monthly returns. ### Risk Indicators * **Rolling Beta (6-month and 12-month)**: Beta calculated over rolling 6-month and 12-month periods. * **Rolling Sharpe Ratio (6-month)**: Sharpe ratio calculated over a rolling 6-month window. * **Top 5 Drawdown Intervals**: Identifies the five largest drawdown periods. ### Holdings Analysis * **Top 10 Holdings**: Displays the top 10 securities held. * **Holding Returns**: Shows the returns for each holding, including Internal Rate of Return (IRR). * **Daily Trading Volume**: Sum of absolute daily trading volumes. * **Daily Turnover Rate**: (Sum of absolute daily trading value / 2) / Total daily market value. ``` -------------------------------- ### Run Daily Futures Function Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Schedules a function to run daily for futures trading, specifying the time and a reference security. The 'market_open' function needs to be implemented separately. ```python # 设置运行函数的参考(market_open为自定义函数,需要自己实现;参考标的默认为沪深300,需要根据策略自己设置,下面只是举例) run_daily(market_open, time='every_bar', reference_security='CU9999.XSGE') ``` -------------------------------- ### Python: Execute Portfolio Rebalancing Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Implements portfolio rebalancing logic in Python. It first sells stocks that are no longer in the `buy_list` and then applies different optimization models for portfolio allocation. ```python def market_open(context): sell_list = set(context.portfolio.positions.keys()) - set(g.buy_list) for stock in sell_list: order_target_value(stock, 0) if g.optimizer == 1: optimized_weight = pd.Series(data=[1.0/len(g.buy_list)]*len(g.buy_list), index=g.buy_list) ``` -------------------------------- ### 多股票交易策略 Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view 实现一个多股票交易策略,根据股票价格与三天平均价的比较来决定买入或卖出。当价格低于三天平均价的99.5%且持有股票时卖出,高于100.5%且有现金时买入。 ```python import jqdata def initialize(context): g.stocks = ['000001.XSHE','000002.XSHE','000004.XSHE','000005.XSHE'] set_benchmark('000300.XSHG') set_option('use_real_price', True) def handle_data(context, data): for security in g.stocks: vwap = data[security].vwap(3) price = data[security].close cash = context.portfolio.available_cash if price < vwap * 0.995 and context.portfolio.positions[security].closeable_amount > 0: order(security,-100) log.info("Selling %s" % (security)) elif price > vwap * 1.005 and cash > 0: order(security,100) log.info("Buying %s" % (security)) ``` -------------------------------- ### Multiple Scheduled Runs in JoinQuant Strategy Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Illustrates how to configure a JoinQuant strategy to execute functions at multiple different times throughout the day, including running on every bar and at specific fixed times. ```python # Run every minute run_daily(func1, time='every_bar') # Run at 11:00 daily run_daily(func2, time='11:00') # Run at 14:00 daily run_daily(func3, time='14:00') ``` -------------------------------- ### Python: Select Stocks and ETFs for Portfolio Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Selects a list of stocks and ETFs to form a trading portfolio in Python. It retrieves stocks from the '000016.XSHG' index and combines them with specified ETF tickers. ```python etf = [ '159902.XSHE', '159903.XSHE', '510050.XSHG', '510880.XSHG', '510440.XSHG', ] g.buy_list = list(get_index_stocks('000016.XSHG')[-15:]) + etf ``` -------------------------------- ### portfolio_optimizer - Portfolio Optimization Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view The portfolio_optimizer function calculates optimal portfolio weights given a specific date, a list of securities, a target objective function, and various constraints and bounds. ```APIDOC ## portfolio_optimizer - Portfolio Optimization ### Description Optimizes investment portfolios by calculating the best weights for a given set of securities based on specified objectives and constraints. ### Method `portfolio_optimizer(date, securities, target, constraints, bounds, default_port_weight_range, ftol, return_none_if_fail)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **date** (date) - Required - The date for which the optimization is performed. Be mindful of lookahead bias. - **securities** (list of strings) - Required - A list of security identifiers (e.g., stock tickers). - **target** (object) - Required - The optimization objective function. Must be one of the predefined target functions (e.g., `RiskParity`, `MinVariance`, `MaxFactorValue`, `MaxSharpeRatio`). - **constraints** (list of objects) - Optional - A list of constraint functions to limit the overall portfolio weights. Can include multiple constraints of the same or different types (e.g., `MarketConstraint`, `WeightConstraint`, `AnnualProfitConstraint`). - **bounds** (list of objects) - Optional - A list of bound functions to limit the weight of individual securities within the portfolio. If multiple bounds are provided, the minimum lower bound and maximum upper bound across all bounds will be applied. Defaults to `[Bound(0.0, 1.0)]`. - **default_port_weight_range** (list of floats) - Optional - A list of two floats defining the default range for the sum of portfolio weights. Defaults to `[0.0, 1.0]`. If no `WeightConstraint` or `WeightEqualConstraint` is present in `constraints`, a `WeightConstraint` with this range will be added. - **ftol** (float) - Optional - The function value tolerance for the optimization algorithm. Defaults to `1e-9`. Adjusting this value can affect the precision and runtime of the optimization. - **return_none_if_fail** (boolean) - Optional - If set to `True` (default), returns `None` if the optimization fails. If set to `False`, returns a portfolio with all weights set to 0 upon failure. ### Request Example ```json { "date": "2023-10-27", "securities": ["000001.XSHE", "600000.XSHG"], "target": "RiskParity(count=250)", "constraints": ["MarketConstraint('stock', low=0.0, high=0.9)"], "bounds": ["Bound(0, 0.1)"] } ``` ### Response #### Success Response (200) Returns a dictionary where keys are security identifiers and values are their optimal weights. - **{security_id: weight}** (dict) - A dictionary containing the optimized weights for each security. #### Response Example ```json { "000001.XSHE": 0.5, "600000.XSHG": 0.5 } ``` #### Error Response (e.g., if optimization fails and return_none_if_fail is True) ```json null ``` ``` -------------------------------- ### Portfolio Optimization: Risk Parity Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Optimizes a portfolio using the Risk Parity model, capping stock and ETF weights, and individual security weights. It returns optimized weights or None if optimization fails. ```python optimized_weight = portfolio_optimizer(date=context.previous_date, securities = g.buy_list, target = RiskParity(count=250, risk_budget=None), constraints = [MarketConstraint('stock', low=0.0, high=0.9), MarketConstraint('etf', low=0.0, high=0.1)], bounds=[Bound(0, 0.1)], default_port_weight_range=[0., 1.0], ftol=1e-09, return_none_if_fail=True) ``` -------------------------------- ### Schedule Daily Function Execution Source: https://www.joinquant.com/help/api/help/file/d/1S23wggXYfdm9wMual2Fq3zN0_pKjOYP5/view Schedules a function to run daily at a specific time. The 'run_daily' function takes a function and a time string as arguments. ```python run_daily(func2, time='14:50') ```