### Example: Get Balance Sheet Data by Date Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_mini_Reference.md This example demonstrates how to retrieve balance sheet data for a specific stock on a given date. Ensure proper error handling for network issues. ```python get_fundamentals('600570.XSHG', 'balance_statement', date='2018-06-01') ``` -------------------------------- ### Example: Get Balance Sheet Data by Year Range Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_mini_Reference.md This example shows how to fetch balance sheet data for multiple stocks within a specified year range. Note that this returns a pandas.Panel. ```python get_fundamentals(['600000.SS', '600570.SS', '000002.SZ'], 'balance_statement', start_year='2016', end_year='2016') ``` -------------------------------- ### Python: Example Strategy with before_trading_start Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md An example demonstrating the use of initialize, set_universe, and before_trading_start functions within a trading strategy. The before_trading_start function logs a global variable. ```python def initialize(context): #g为全局变量 g.security = '600570.SS' set_universe(g.security) def before_trading_start(context, data): log.info(g.security) def handle_data(context, data): order('600570.SS',100) ``` -------------------------------- ### Install SimTradeLab and Optional Packages Source: https://github.com/kay-ou/simtradelab/blob/main/README.md Install the core SimTradeLab library. Optional packages for technical indicators and parameter optimization can be installed using package extras. ```bash pip install simtradelab # Optional: technical indicators (requires system ta-lib) pip install simtradelab[indicators] # Optional: parameter optimizer pip install simtradelab[optimizer] ``` -------------------------------- ### Install SimTradeLab with Server Support Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Install SimTradeLab with optional server dependencies to enable the FastAPI server. ```bash pip install simtradelab[server]==2.5.0 ``` -------------------------------- ### Start SimTradeLab API Server Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Run this command to start the SimTradeLab API server on the default port. ```bash simtradelab --port 8000 ``` -------------------------------- ### Install SimTradeLab with Optimizer Support Source: https://github.com/kay-ou/simtradelab/blob/main/docs/TOOLS.md Install the SimTradeLab library with the necessary dependencies for the optimizer module using pip or Poetry. This is the first step before writing any optimization scripts. ```bash pip install simtradelab[optimizer] ``` ```bash poetry install -E optimizer ``` -------------------------------- ### Example: Get Sector Ranking Data Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Demonstrates how to use the get_sort_msg function to fetch and log sector ranking data, and access the first item in the sorted list. Requires initialization and data handling context. ```python def initialize(context): g.security = '000001.SZ' set_universe(g.security) def handle_data(context, data): #获取XBHS.DY板块的涨幅排名信息 sort_data = get_sort_msg(sort_type_grp='XBHS.DY', sort_field_name='preclose_px', sort_type=1, data_count=100) log.info(sort_data) #获取sort_data排序第一条代码的数据 sort_data_first = sort_data[0] log.info(sort_data_first) ``` -------------------------------- ### Customizing Optimization Objective with Backtest Stats Source: https://github.com/kay-ou/simtradelab/blob/main/docs/TOOLS.md Customize the optimization objective by defining a custom metric based on backtest results. This example shows how to use various statistics like annual return, drawdown, and Sharpe ratio to guide the optimization. ```python def objective(trial): # ... 参数定义 ... # 运行回测 stats = optimizer.run_backtest_with_params( max_position=max_position, rotation_period=rotation_period ) # 自定义目标函数(使用卡玛比率:年化收益/最大回撤) annual_return = stats['annual_return'] max_drawdown = stats['max_drawdown'] sharpe_ratio = stats['sharpe_ratio'] sortino_ratio = stats['sortino_ratio'] calmar_ratio = stats['calmar_ratio'] # 示例:最大化索提诺比率(更关注下行风险控制) return sortino_ratio ``` -------------------------------- ### Install VS Code Pylance Extension Source: https://github.com/kay-ou/simtradelab/blob/main/docs/IDE_SETUP.md Install the Pylance extension for advanced type checking and language features in VS Code. ```bash code --install-extension ms-python.vscode-pylance ``` -------------------------------- ### Install VS Code Python Extension Source: https://github.com/kay-ou/simtradelab/blob/main/docs/IDE_SETUP.md Use the VS Code command-line interface to install the official Python extension. ```bash code --install-extension ms-python.python ``` -------------------------------- ### Setup Typeshed for VS Code Source: https://github.com/kay-ou/simtradelab/blob/main/docs/IDE_SETUP.md Run this script to set up typeshed for VS Code, which is necessary for accurate type hinting and definition jumping. ```bash bash scripts/setup_typeshed.sh ``` -------------------------------- ### Example: Optimizing Parameters for a 5-Moving Average Strategy Source: https://github.com/kay-ou/simtradelab/blob/main/docs/TOOLS.md A complete example demonstrating the optimization of parameters for a 5-moving average (5mv) trading strategy. It defines the strategy path, data range, and a custom objective function with specific parameters like max position, rotation period, minimum market cap, and filter for ST stocks. ```python from simtradelab.backtest.optimizer_framework import StrategyOptimizer optimizer = StrategyOptimizer( strategy_path='strategies/5mv', data_path='data', start_date='2020-01-01', end_date='2024-12-31' ) def objective(trial): # 定义参数空间 max_position = trial.suggest_int('max_position', 5, 30) rotation_period = trial.suggest_int('rotation_period', 10, 60) min_market_cap = trial.suggest_float('min_market_cap', 50, 200) # 亿 filter_st = trial.suggest_categorical('filter_st', [True, False]) # 运行回测 return optimizer.evaluate( trial, max_position=max_position, rotation_period=rotation_period, min_market_cap=min_market_cap, filter_st=filter_st ) # 运行优化 best_params = optimizer.optimize(objective, n_trials=200) print(f""" 最优参数: - 最大持仓数: {best_params['max_position']} - 轮动周期: {best_params['rotation_period']}天 - 最小市值: {best_params['min_market_cap']}亿 - 过滤ST: {best_params['filter_st']} """) ``` -------------------------------- ### ETF Information Return Example Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_mini_Reference.md Illustrates the structure of the dictionary returned by get_etf_info for a specific ETF. ```python {'510020.SS': {'nav_percu': 206601.39, 'redeem_max': 0.0, 'nav_pre': 0.207, 'report_unit': 1000000, 'max_cash_ratio': 0.4, 'cash_balance': -813.75, 'etf_redemption_code': '510021', 'pre_cash_component': 598.39, 'allot_max': 0.0, 'publish': 1}} ``` -------------------------------- ### Initialize and Get Stock Exrights Info Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Initializes the security and retrieves stock exrights information within the handle_data function. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): stock_exrights = get_stock_exrights(g.security) log.info('the stock exrights info of security %s:\n%s' % (g.security, stock_exrights)) ``` -------------------------------- ### Upgrade Simtradelab Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md To upgrade to version 2.11.0, use the pip install command. This command fetches and installs the specified version of the Simtradelab package. ```bash pip install --upgrade simtradelab==2.11.0 ``` -------------------------------- ### Install VS Code Jupyter Extension Source: https://github.com/kay-ou/simtradelab/blob/main/docs/IDE_SETUP.md Install the Jupyter extension to enable support for Jupyter Notebooks directly within VS Code. ```bash code --install-extension ms-toolsai.jupyter ``` -------------------------------- ### Get and Log Position Information Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_mini_Reference.md Demonstrates placing an order and then retrieving and logging the position information for a specific security using get_position. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) ``` ```python def handle_data(context, data): order(g.security,1000) position = get_position(g.security) log.info(position) ``` -------------------------------- ### Example of Invalid and Correct Lifecycle Transitions Source: https://github.com/kay-ou/simtradelab/blob/main/docs/ARCHITECTURE.md Illustrates incorrect and correct phase transitions within the lifecycle control. The incorrect example shows a forbidden jump, while the correct one follows the defined sequence. ```python # ❌ 错误:跳过 before_trading_start 直接到 after_trading_end initialize → after_trading_end # 抛出异常 # ✅ 正确:按顺序转换 initialize → before_trading_start → handle_data → after_trading_end ``` -------------------------------- ### Example Usage of on_trade_response Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Demonstrates a practical implementation of the on_trade_response function within a trading strategy. It shows how to place an order based on the trade response and log information. ```python def initialize(context): g.security = ['600570.SS','002416.SZ'] set_universe(g.security) g.flag = 0 def on_trade_response(context, trade_list): log.info(trade_list) if(g.flag==0): order('600570.SS', 100) g.flag = 1 else: log.info("end") def handle_data(context, data): order('600570.SS', 100) ``` -------------------------------- ### Initialize Strategy Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_mini_Reference.md The initialize function is required for strategy execution in backtesting and trading environments. It runs once at the start to set up global variables and initial configurations. ```python def initialize(context): #g为全局对象 g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): order('600570.SS',100) ``` -------------------------------- ### Initialize Trading Context and Set Universe Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_mini_Reference.md Initializes the trading context by setting the security and defining the trading universe. This function is typically called at the start of a trading session. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) ``` -------------------------------- ### Example: Fetch ETF Details Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Shows how to call get_etf_info with a single ETF code and a list of ETF codes, then logs the retrieved information. Ensure the context is set up for stock trading. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): #ETF信息 etf_info = get_etf_info('510020.SS') log.info(etf_info) etfs_info = get_etf_info(['510020.SS','510050.SS']) log.info(etfs_info) ``` -------------------------------- ### Run a Backtest with Configuration Source: https://github.com/kay-ou/simtradelab/blob/main/README.md Configure and execute a backtest using SimTradeLab's BacktestRunner and BacktestConfig. This example covers essential parameters like strategy name, dates, capital, market, and data paths. ```python from simtradelab.backtest.runner import BacktestRunner from simtradelab.backtest.config import BacktestConfig config = BacktestConfig( # --- Required --- strategy_name='my_strategy', # Strategy folder name under strategies/ start_date='2024-01-01', # Backtest start date end_date='2024-12-31', # Backtest end date # --- Capital & Market --- initial_capital=100000.0, # Starting capital (must be > 0) market='CN', # Market: 'CN' (A-shares) | 'US' broker_profile='auto', # Broker API profile: 'auto' | 'guosheng' | 'dongguan' | 'shanxi' t_plus_1=None, # T+1 override: None=market default (CN=True, US=False) benchmark_code='', # Benchmark code, empty=market default # --- Frequency --- frequency='1d', # Bar frequency: '1d' (daily) | '1m' (minute) # --- Paths --- data_path='~/.simtradelab/data', # Market data directory strategies_path='./strategies', # Strategies root directory # --- Performance --- enable_multiprocessing=True, # Enable parallel data loading num_workers=None, # Worker count (None=auto, must be >= 1) use_data_server=True, # Use in-memory data server (singleton) # --- Output --- enable_charts=True, # Generate PNG chart enable_logging=True, # Write log file enable_export=False, # Export trade details to CSV # --- i18n --- locale='auto', # Log language: 'zh' | 'en' | 'de' (auto: CN market→zh, else system locale) optimization_mode=False, # Optimization mode: skip validation/logging (managed by optimizer) # --- Entry file --- strategy_file='backtest.py', # Entry file: 'backtest.py' | 'live.py' ) runner = BacktestRunner() report = runner.run(config=config) ``` -------------------------------- ### Get Single Security Historical Data (Open Price) Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Example of retrieving the 'open' price for a single security ('600570.SS') for the last 5 days (daily frequency). The return type is a pandas DataFrame with datetime index and 'open' as the column. ```python get_history(5, '1d', 'open', '600570.SS', fq=None, include=False) ``` -------------------------------- ### Get Multiple Securities Historical Data (Open Price) Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Example of retrieving the 'open' price for multiple securities (['600570.SS', '600571.SS']) for the last 5 days (daily frequency). The return type is a pandas DataFrame with datetime index and security codes as columns. ```python get_history(5, '1d', 'open', ['600570.SS','600571.SS'], fq=None, include=False) ``` -------------------------------- ### Basic Strategy Initialization and Execution Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Example demonstrating the basic structure of a PTrade strategy, including initialization, data handling, and order placement. This snippet shows how to set a security, subscribe to it, and place an order. ```python def initialize(context): #g为全局变量 g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): order('600570.SS',100) def after_trading_end(context, data): log.info(g.security) ``` -------------------------------- ### Standard Release Steps Source: https://github.com/kay-ou/simtradelab/blob/main/script/RELEASE.md Execute the release script to prepare the version and push the main branch. The CI will handle tagging and publishing. ```bash # 1) Execute version preparation (defaults to running tests first) python script/release.py --version 2.10.2 # 2) Push the main branch git push origin main ``` -------------------------------- ### Get Multiple Securities Historical Data (Open and Close Prices) Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Example of retrieving both 'open' and 'close' prices for multiple securities (['600570.SS', '600571.SS']) for the last 2 days (daily frequency). The return type is a pandas Panel, where each item is a DataFrame indexed by datetime and security code. ```python get_history(2, frequency='1d', field=['open','close'], security_list=['600570.SS', '600571.SS'], fq=None, include=False) ``` -------------------------------- ### Python Example: Fetching and Processing Historical Market Data Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Demonstrates how to initialize a trading context, set a security universe, and retrieve historical data for industries and individual stocks using `get_history`. It shows how to access specific data points, calculate means, and retrieve data with different frequencies and复权 (ex-rights) options. ```python def initialize(context): g.security = ['600570.SS', '000001.SZ'] set_universe(g.security) def before_trading_start(context, data): # 获取农业版块过去10天的每日收盘价 industry_info = get_history(10, frequency="1d", field="close", security_list="A01000.XBHS") log.info(industry_info) def handle_data(context, data): # 股票池中全部股票过去5天的每日收盘价 his = get_history(5, '1d', 'close', security_list=g.security) log.info('股票池中全部股票过去5天的每日收盘价') log.info(his) # 获取600570(恒生电子)过去5天的每天收盘价, # 一个pd.Series对象, index是datatime log.info('获取600570(恒生电子)过去5天的每天收盘价') log.info(his['600570.SS']) # 获取600570(恒生电子)昨天(数组最后一项)的收盘价 log.info('获取600570(恒生电子)昨天的收盘价') log.info(his['600570.SS'][-1]) # 获取股票池中全部股票昨天的收盘价 log.info('获取股票池中全部股票昨天的收盘价') log.info(his.iloc[-1]) # 获取600570(恒生电子)昨天(数组最后一项)的收盘价 log.info('获取600570(恒生电子)昨天的收盘价') log.info(his.iloc[-1]['600570.SS']) # 取得每一列的平均值 log.info('取得每一列的平均值') log.info(his.mean()) # 获取股票池中全部股票的过去10分钟的成交量 his1 = get_history(10, '1m', 'volume') log.info('获取股票池中全部股票的过去10分钟的成交量') log.info(his1) # 获取恒生电子的过去5天的每天的收盘价 his2 = get_history(5, '1d', 'close', security_list='600570.SS') log.info('获取恒生电子的过去5天的每天的收盘价') log.info(his2) # 获取恒生电子的过去5天的每天的后复权收盘价 his3 = get_history(5, '1d', 'close', security_list='600570.SS', fq='post') log.info('获取恒生电子的过去5天的每天的后复权收盘价') log.info(his3) # 获取恒生电子的过去5周的每周的收盘价 his4 = get_history(5, '1w', 'close', security_list='600570.SS') log.info('获取恒生电子的过去5天的每天的收盘价') log.info(his4) # 获取多只股票的开盘价和收盘价数据 panel_info = get_history(2, frequency='1d', field=['open','close'], security_list=g.security) open_df = panel_info['open'] log.info('获所有股票的取开盘价数据') log.info(open_df) df = open_df['600570.SS'] log.info('仅获取恒生电子的开盘价数据') log.info(df) # panel索引中的对象进行转换 panel_info2 = panel_info.swapaxes("minor_axis", "items") df = panel_info2['600570.SS'] log.info('仅获取恒生电子的开盘价和收盘价数据') log.info(df) open_df = df['open'] log.info('获取恒生电子的开盘价数据') log.info(open_df) ``` -------------------------------- ### Initialize and Handle Data in Simtradelab Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Example of initializing global variables and handling data for a trading strategy. This snippet demonstrates setting a security and placing an order within the Simtradelab framework. ```python def initialize(context): #g为全局变量 g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): order('600570.SS',100) ``` -------------------------------- ### Install VS Code GitLens Extension Source: https://github.com/kay-ou/simtradelab/blob/main/docs/IDE_SETUP.md Install the GitLens extension to enhance Git capabilities, such as viewing code history and authorship, within VS Code. ```bash code --install-extension eamodio.gitlens ``` -------------------------------- ### Get Individual Transaction Data Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Retrieves real-time individual transaction data for stocks. Requires Level 2 market data. Use this to get details on executed trades. ```python get_individual_transaction(stocks=None, data_count=50, start_pos=0, search_direction=1) ``` ```python def initialize(context): g.security = "000001.SZ" set_universe(g.security) def handle_data(context, data): # 获取当前股票池逐笔成交数据 transaction = get_individual_transaction() log.info(transaction) # 获取指定股票列表逐笔成交数据 transaction = get_individual_transaction(["000002.SZ", "000032.SZ"]) log.info(transaction) # 获取成交量 if transaction is not None: business_amount = transaction["000002.SZ"]["business_amount"] log.info("逐笔数据的成交量为:%s" % business_amount) ``` -------------------------------- ### Get Individual Entrust Data Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Retrieves real-time individual entrust data for stocks. Requires Level 2 market data. Use this to get detailed buy/sell order information. ```python get_individual_entrust(stocks=None, data_count=50, start_pos=0, search_direction=1) ``` ```python def initialize(context): g.security = "000001.SZ" set_universe(g.security) def handle_data(context, data): # 获取当前股票池逐笔委托数据 entrust = get_individual_entrust() log.info(entrust) # 获取指定股票列表逐笔委托数据 entrust = get_individual_entrust(["000002.SZ", "000032.SZ"]) log.info(entrust) # 获取委托量 if entrust is not None: business_amount = entrust["000002.SZ"]["business_amount"] log.info("逐笔数据的委托量为:%s" % business_amount) ``` -------------------------------- ### Example of API Call Restrictions in 'initialize' Phase Source: https://github.com/kay-ou/simtradelab/blob/main/docs/ARCHITECTURE.md Demonstrates incorrect and correct API usage within the 'initialize' phase. Shows that trading operations like 'order' are forbidden, while configuration calls like 'set_benchmark' are allowed. ```python def initialize(context): # ❌ 错误:initialize 阶段不能交易 order('600519.SS', 100) # 抛出:API 'order' cannot be called in phase 'initialize' # Allowed phases: ['handle_data', 'tick_data'] # ✅ 正确:initialize 只能配置 set_benchmark('000300.SS') ``` -------------------------------- ### 创建新分支 Source: https://github.com/kay-ou/simtradelab/blob/main/docs/CONTRIBUTING.md 从 main 分支创建一个新分支以开始您的功能开发。 ```bash git checkout -b feature/your-new-feature ``` -------------------------------- ### Get Tick Direction Data Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Retrieves intraday transaction data (tick data) for stocks. Requires Level 2 market data. Use this to get time-stamped trade details within a day. ```python get_tick_direction(symbols=None, query_date=0, start_pos=0, search_direction=1, data_count=50) ``` ```python def initialize(context): g.security = '000001.SZ' set_universe(g.security) def handle_data(context, data): #获取000001.SZ的分时成交数据 direction_data = get_tick_direction(g.security) log.info(direction_data) #获取指定股票列表分时成交数据 direction_data = get_tick_direction(['000002.SZ','000032.SZ']) log.info(direction_data) #获取成交量 business_amount = direction_data['000002.SZ']['business_amount'] log.info('分时成交的成交量为:%s' % business_amount) ``` -------------------------------- ### Place Order by Quantity (Python) Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Executes a buy or sell order for a specified quantity of a security. Supports reverse repurchase agreements. Ensure correct amount for reverse repos (>=1000 yuan). Backtesting has minimum order quantity checks (100 shares/10 lots). Trading module relies on counterparty data. ```python def initialize(context): g.security = ['600570.SS', '000001.SZ'] set_universe(g.security) def handle_data(context, data): #以系统最新价委托 order('600570.SS', 100) # 逆回购1000元 order('131810.SZ', -10) #以39块价格下一个限价单 order('600570.SS', 100, limit_price=39) ``` -------------------------------- ### Upgrade SimTradeLab to 2.5.0 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your SimTradeLab installation to version 2.5.0. ```bash pip install --upgrade simtradelab==2.5.0 ``` -------------------------------- ### open_prepared Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md Opens a prepared option position. ```APIDOC ## open_prepared ### Description Opens a prepared option position. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage for opening a prepared option position # open_prepared(prepared_order_id) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Upgrade SimTradeLab to 2.6.0 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your SimTradeLab installation to version 2.6.0. ```bash pip install --upgrade simtradelab==2.6.0 ``` -------------------------------- ### Upgrade SimTradeLab to 2.6.1 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your SimTradeLab installation to version 2.6.1. ```bash pip install --upgrade simtradelab==2.6.1 ``` -------------------------------- ### Upgrade SimTradeLab to 2.9.0 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your SimTradeLab installation to version 2.9.0. ```bash pip install --upgrade simtradelab==2.9.0 ``` -------------------------------- ### Initialize Trading Context and Set Universe Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_mini_Reference.md Initializes the trading context by setting a list of securities and defining the trading universe. This is typically the first step in a trading strategy. ```python def initialize(context): g.security = ['600570.SS', '000001.SZ'] set_universe(g.security) ``` -------------------------------- ### Upgrade SimTradeLab to 2.10.0 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your SimTradeLab installation to version 2.10.0. ```bash pip install --upgrade simtradelab==2.10.0 ``` -------------------------------- ### Upgrade SimTradeLab to 2.10.1 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your SimTradeLab installation to version 2.10.1. ```bash pip install --upgrade simtradelab==2.10.1 ``` -------------------------------- ### Python: before_trading_start Function Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md This function is called once before the trading session begins each day. It's used for daily initialization tasks. Available in backtesting and trading modules. ```python def before_trading_start(context, data): pass ``` -------------------------------- ### open_prepared Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_mini_Reference.md Opens a prepared position. Used in options trading. ```APIDOC ## open_prepared ### Description Opens a prepared position. Used in options trading. ### Method Not specified (assumed to be a function call within a Python environment) ### Endpoint Not applicable (SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage to open a prepared position # open_prepared('prepared_position_id') pass ``` ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Python: Initialize and Process Tick Data Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_Complete_Reference.md This snippet shows how to initialize a security, set the trading universe, and process incoming tick data to retrieve bid prices and place orders based on price conditions. It includes commented-out examples for accessing other tick data fields and transaction details. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def tick_data(context,data): # 获取买一价 security = g.security current_price = eval(data[security]['tick']['bid_grp'][0])[1][0] log.info(current_price) # 获取买二价 # current_price = eval(data[security]['tick']['bid_grp'][0])[2][0] # 获取买三量 # current_amount = eval(data[security]['tick']['bid_grp'][0])[3][1] # 获取tick最高价 # current_high_price = data[security]['tick']['high_px'][0] # 最近一笔逐笔成交的成交量 # transaction = data[security]["transcation"] # business_amount = list(transaction["business_amount"]) # if len(business_amount) > 0: # log.info("最近一笔逐笔成交的成交量:%s" % business_amount[0]) # 最近一笔逐笔委托的委托类别 # order = data[security]["order"] # trans_kind = list(order["trans_kind"]) # if len(trans_kind) > 0: # log.info("最近一笔逐笔委托的委托类别:%s" % trans_kind[0]) if current_price > 38.19: # 按买一档价格下单 order_tick(security, 100, 1) def handle_data(context, data): pass ``` -------------------------------- ### Upgrade Simtradelab to Version 2.7.0 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your Simtradelab installation to version 2.7.0. ```bash pip install --upgrade simtradelab==2.7.0 ``` -------------------------------- ### Upgrade Simtradelab to Version 2.8.0 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your Simtradelab installation to version 2.8.0. ```bash pip install --upgrade simtradelab==2.8.0 ``` -------------------------------- ### SimTradeLab Documentation Navigation Source: https://github.com/kay-ou/simtradelab/blob/main/src/simtradelab/AGENTS.md This table provides a quick reference for locating specific functionalities within the SimTradeLab project, mapping tasks to their respective file paths and offering brief notes. ```markdown | Task | Location | Notes | |------|----------|-------| | PTrade API | `ptrade/api.py` | Main PtradeAPI class implementation | | Strategy validation | `ptrade/strategy_validator.py` | Lifecycle + Python 3.5 checks | | Backtesting core | `backtest/engine.py` | Local simulation engine | | Python 3.5 checker | `utils/py35_compat_checker.py` | Compatibility validation | | Performance tools | `utils/perf.py` | Timing and optimization utilities | ``` -------------------------------- ### Upgrade Simtradelab to Version 2.10.2 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your Simtradelab installation to version 2.10.2. ```bash pip install --upgrade simtradelab==2.10.2 ``` -------------------------------- ### Initialize Global Variables with g Source: https://github.com/kay-ou/simtradelab/blob/main/docs/PTrade_API_mini_Reference.md Demonstrates initializing global variables using the 'g' object in the initialize function. These variables can be accessed by other functions. ```python def initialize(context): g.security = None #股票池 ``` ```python def initialize(context): g.security = "600570.SS" g.count = 1 g.flag = 0 set_universe(g.security) ``` -------------------------------- ### Basic Strategy Optimization Script Source: https://github.com/kay-ou/simtradelab/blob/main/docs/TOOLS.md Create a Python script to define and run parameter optimization for a trading strategy. This involves initializing the StrategyOptimizer, defining an objective function, and running the optimization process. ```python from simtradelab.backtest.optimizer_framework import StrategyOptimizer # 创建优化器 optimizer = StrategyOptimizer( strategy_path='strategies/my_strategy', data_path='data', start_date='2020-01-01', end_date='2024-12-31' ) # 定义参数空间 def objective(trial): # 定义要优化的参数 max_position = trial.suggest_int('max_position', 5, 30) rotation_period = trial.suggest_int('rotation_period', 10, 60) stop_loss = trial.suggest_float('stop_loss', 0.05, 0.20) # 运行回测并返回目标值(年化收益率) return optimizer.evaluate(trial, max_position, rotation_period, stop_loss) # 运行优化(200次trial) best_params = optimizer.optimize(objective, n_trials=200) print(f"最优参数: {best_params}") ``` -------------------------------- ### Upgrade Simtradelab to Version 2.8.1 Source: https://github.com/kay-ou/simtradelab/blob/main/CHANGELOG.md Use this command to upgrade your Simtradelab installation to the latest version 2.8.1. ```bash pip install --upgrade simtradelab==2.8.1 ```