### Running Strategy with research_trade and TradeAPI - Python Source: https://github.com/fisher188/supermcode/blob/main/模拟仿真.md This example demonstrates how to initialize a TradeAPI object with a specific account and order policy, and then use it to run a strategy via the `research_trade` function in simulation/live trading mode (`signal_mode=False`) with minute frequency and recovery from today's start. ```Python from tick_trade_api import TradeAPI #初始化TradeAPI时需要指定下单策略,MarketPolicy为市价下单;LimitPolicy为限价下单 trade_api=TradeAPI('69271711',order_policy=MarketPolicy) source_code=""" # 股票策略模版 def init(context): pass # 盘前执行 def before_trading(context): pass # 开盘时运行函数 def handle_bar(context, bar_dict): order_id = order('000001.SZ', 100) print(get_orders()) try: cancel_order(order_id) except: print('撤单失败') print(get_open_orders()) print(get_tradelogs()) print(context.portfolio.stock_account) print(context.portfolio.positions) """ rtrade = research_trade( '研究环境策略', source_code, frequency='MINUTE', trade_api=trade_api, signal_mode=False, recover_dt='today' ) ``` -------------------------------- ### Example Usage of research_strategy - Python Source: https://github.com/fisher188/supermcode/blob/main/研究环境_实盘.md Provides a practical example demonstrating how to use the `research_strategy` function. It shows how to define a simple strategy within a multi-line string and pass it along with specific backtesting parameters like start/end dates, capital base, and frequency. ```python source_code=r""" # 股票策略模版 def init(context): pass ## 开盘时运行函数 def handle_bar(context, bar_dict): order('000001.SZ', 100) """ btest = research_strategy(source_code, start_date='20210601', end_date='20210815', capital_base=float(10000000), frequency='DAILY', stock_market='STOCK', benchmark=None) ``` -------------------------------- ### Setting Initial Holdings - Supermcode Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Sets the initial stock positions for the backtesting account. This allows starting a backtest with a predefined portfolio without reducing the initial cash balance. Holdings are valued at the closing price of the day before the backtest start date. Must be called within `init(context)`. ```Python def init(context): #设置策略初始持仓 set_holding_stocks({'000001.SZ': 200,'300033.SZ': 500,'600519.SH': 700}) ``` -------------------------------- ### Example Usage of research_trade with TradeAPI - Python Source: https://github.com/fisher188/supermcode/blob/main/研究环境_实盘.md Illustrates how to use the `research_trade` function for simulation, specifically demonstrating integration with a `TradeAPI` object. It shows the initialization of `TradeAPI` with an order policy and the call to `research_trade` with a multi-line strategy code string that includes `init`, `before_trading`, and `handle_bar` functions, along with parameters for frequency, trade API, signal mode, and recovery date. ```python from tick_trade_api import TradeAPI #初始化TradeAPI时需要指定下单策略,MarketPolicy为最新价下单;LimitPolicy为限价下单 trade_api=TradeAPI('69271711', order_policy=LimitPolicy) source_code=""" # 股票策略模版 def init(context): pass # 盘前执行 def before_trading(context): pass # 开盘时运行函数 def handle_bar(context, bar_dict): order_id = order('000001.SZ', 100) print(get_orders()) try: cancel_order(order_id) except: print('撤单失败') print(get_open_orders()) print(get_tradelogs()) print(context.portfolio.stock_account) print(context.portfolio.positions) """ rtrade = research_trade( '研究环境策略', source_code, frequency='MINUTE', trade_api=trade_api, signal_mode=False, recover_dt='today' ) ``` -------------------------------- ### Calculating Holding Days Using positions_days (Issue Example) Source: https://github.com/fisher188/supermcode/blob/main/模拟仿真.md This Python snippet demonstrates a strategy attempting to sell positions after holding them for 5 trading days. It relies on `context.portfolio.positions[k].positions_days` to calculate the holding period. However, this field is often unavailable or zero in real/simulated trading environments, causing the holding period logic to fail. ```Python from datetime import timedelta as td def init(context): g.symbols = ['000001.SZ','600519.SH'] g.status = True def handle_bar(context): if g.status: for symbol in g.symbols: order(symbol,100) g.status = False else: for k,v in context.portfolio.positions: trade_days = get_datetime() - td(v.positions_days) tdays = len(get_trade_days( trade_days.strftime('%Y%m%d'), get_datetime().strftime('%Y%m%d') )) if tdays>5: order_target(k,0) ``` -------------------------------- ### Setting OTC Fund Subscription Discount Rate - set_discount_rate - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md This example sets the discount rate for subscribing to over-the-counter (OTC) funds to 10% (0.1) during strategy initialization. This function must be called within the `init(context)` function. ```Python def init(context): # 初始化策略时设置折扣率10% set_discount_rate(0.1) ``` -------------------------------- ### Initialize Stock and Futures Accounts - Python Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md This Python snippet demonstrates how to initialize both stock and futures sub-accounts simultaneously in the `init` function. It allocates 500,000 cash to both account types using `set_subportfolios`, enabling trading in both markets within the same strategy. This setup is required if your strategy involves trading both asset classes. ```Python def init(context): #设置子账户,股票账户50万,期货账户50万. set_subportfolios([{'cash':500000,'type':'stock'},{'cash':500000,'type':'future'}]) ``` -------------------------------- ### Portfolio Optimizer Application Example (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md A Python script demonstrating a portfolio optimization strategy. It selects 50 random stocks from CSI 500, sets up benchmark, trading costs (commission, slippage), volume limits, and defines a weekly rebalancing function. The `optmize` function constructs an `OptimizePort` instance, adds stock weight and tracking error constraints, solves for optimal weights, and executes trades. ```python # 从中证500中随机选取50股票,模拟中证500走势,周频调仓 # Stratified Sampling 方法优点: #1.当指数标的过多时,完全复制的资金量要求较高 #2.指数标的中很多股票的成交量过小,交易成本较高,甚至无法完全复制中证500标的成分股权重 import random def init(context): # 设置基准收益:中证500指数 set_benchmark('000905.SH') # 打印日志 log.info('策略开始运行,初始化函数全局只运行一次') # 设置股票每笔交易的手续费为万分之二(手续费在买卖成交后扣除,不包括税费,税费在卖出成交后扣除) set_commission(PerShare(type='stock',cost=0.0002)) # 设置股票交易滑点0.5%,表示买入价为实际价格乘1.005,卖出价为实际价格乘0.995 set_slippage(PriceSlippage(0.002)) # 设置日级最大成交比例25%,分钟级最大成交比例50% # 日频运行时,下单数量超过当天真实成交量25%,则全部不成交 # 分钟频运行时,下单数量超过当前分钟真实成交量50%,则全部不成交 set_volume_limit(0.25,0.5) # 从中证500中随机选取50股票 stocks=random.sample(list(get_index_stocks('000905.SH','2017-12-21')), 50) #构建股票列表,形式为dict,以便后续使用组合优化器 context.security={ia:0 for ia in stocks} #构建初始股票权重 context.hold={ia:0 for ia in stocks} #股票权重限制 context.weight={ia :[0.0,100.0] for ia in stocks} #周频调仓 run_weekly(func=optmize, date_rule=1, reference_security='000001.SZ') def optmize(context, bar_dict): time=get_datetime().strftime('%Y%m%d') #构造组合优化器,优化目标设置为最大化效用,使用历史收益率作为预期收益率 opt=OptimizePort(context.security, '2017-12-21', True, opt_focus='UI', benchmark='000905.SH', period='w', holds=context.hold, long_short='long-only') opt.add_constraint('stock_weight',context.weight) #添加跟踪误差约束 opt.add_constraint('tracking_error',(-0.02,0.02)) # opt.add_constraint('industry','industry_neutralize') #使用组合优化器进行求解 stock_weight = opt.optimized_weight() #根据组合优化器结果进行权重调整 for ia in stock_weight.keys(): order_target_percent(ia, stock_weight[ia]/100) ``` -------------------------------- ### Running a Strategy for Simulation/Live Trading using research_trade and TradeAPI (Python) Source: https://github.com/fisher188/supermcode/blob/main/研究环境_实盘.md This snippet demonstrates how to execute a trading strategy directly within the SuperMind research environment for simulation or live trading. It initializes the TradeAPI with a specific account and order policy, defines the strategy logic as a multi-line string, and then uses the research_trade function to run the strategy with specified parameters like frequency and the initialized trade_api instance. The strategy code includes examples of placing orders, querying orders, cancelling orders, and accessing portfolio information. ```Python from tick_trade_api import TradeAPI #初始化TradeAPI时需要指定下单策略,MarketPolicy为最新价下单;LimitPolicy为限价下单 trade_api=TradeAPI('69271711',order_policy=LimitPolicy) source_code=""" # 股票策略模版 def init(context): pass # 盘前执行 def before_trading(context): pass # 开盘时运行函数 def handle_bar(context, bar_dict): order_id = order('000001.SZ', 100) print(get_orders()) try: cancel_order(order_id) except: print('撤单失败') print(get_open_orders()) print(get_tradelogs()) print(context.portfolio.stock_account) print(context.portfolio.positions) """ rtrade = research_trade( '研究环境策略', source_code, frequency='MINUTE', trade_api=trade_api, signal_mode=False, recover_dt='today' ) ``` -------------------------------- ### Initialize Futures Account - Python Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md This Python snippet shows how to initialize sub-accounts within the `init` function for futures trading. It sets up a stock account with 0 cash and a futures account with 500,000 cash using the `set_subportfolios` function. This is necessary for trading futures instruments and is typically done once at the start of the strategy. ```Python def init(context): #设置子账户,股票账户0万,期货账户50万. set_subportfolios([{'cash':0,'type':'stock'},{'cash':500000,'type':'future'}]) ``` -------------------------------- ### Real-time Stock Selection with query_iwencai (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Provides an example of using query_iwencai with a natural language query to select stocks based on criteria like recent capital flow, market cap, and daily turnover. This function is intended for research environments and real-time selection. ```Python query_iwencai("近10日的区间主力资金流向>5000万元,市值>1000亿,日成交额>30亿") ``` -------------------------------- ### Setting OTC Fund Dividend Mode - set_dividend_mode - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md This example sets the dividend handling mode for over-the-counter (OTC) funds to 'invest' (reinvest dividends) during strategy initialization. This function must be called within the `init(context)` function. ```Python def init(context): #初始化策略时设置分红模式为红利再投资 set_dividend_mode(invest) ``` -------------------------------- ### Getting Futures Info - supermcode - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves information related to a specific futures or options variety. Requires the futures variety symbol and an optional query date. ```python #查询螺纹钢期货的2023年8月1日的品种信息 data = get_futures_info('RB','20230801') print(data) ``` -------------------------------- ### Setting Option Commission - set_option_commission - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md This example shows how to set the commission fee per option contract to 10 yuan. This function must be called within the `init(context)` function to be effective. ```Python # 设置期权手续费为10元/张 def init(context): set_option_commission(10) ``` -------------------------------- ### Implement MA Crossover Strategy with Logging - SuperMind - Python Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md This Python code snippet enhances the basic moving average crossover strategy by adding logging and data recording features for the SuperMind backtesting engine. It calculates the moving averages and places orders based on crossovers, similar to the previous example, but also uses `log.info` to print the trade signal and `record` to output the signal for visualization purposes. ```Python #初始化账户 def init(context): g.index='600519.SH' def handle_bar(context,bar_dict): close = history(g.index, ['close'], 20, '1d', False, fq = 'pre', is_panel=0) MA5 = close['close'].values[-5:].mean() #计算二十日均线价格 MA20 = close['close'].values.mean() #设置交易信号 trade_signal=0 #如果五日均线大于二十日均线 if MA5 > MA20: #使用所有现金买入证券 order_target_percent(g.index,1) #记录本次买入 log.info("全仓买入{0}".format(g.index)) #记录买入信号 trade_signal=1 #如果五日均线小于二十日均线 if MA5 < MA20 : #卖出所有证券 order_target_percent(g.index,0) #记录本次卖出 log.info("全仓卖出{0}".format(g.index)) #记录卖出信号 trade_signal=-1 log.info(trade_signal) record(trade_signal=trade_signal) ​ ``` -------------------------------- ### Getting Tradable Option Contracts - supermcode - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves a list of all tradable ETF option contracts on the Shanghai and Shenzhen exchanges for a given date. Requires an optional query date. ```python #查询2023年8月1日可交易的螺纹钢期货合约 options_all = get_option_code('20230801') print(options_all) ``` -------------------------------- ### Subscribing to Symbols - subscribe - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md This example demonstrates subscribing to the main Rebar futures contract ('RB9999') during strategy initialization. Subscribing adds the symbol to the contract pool and influences strategy execution times. ```Python def init(context): #订阅螺纹主力合约 subscribe('RB9999') ``` -------------------------------- ### Setting Option Trading Slippage - set_option_slippage - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md This example sets the option trading slippage rate to 0.004, representing a total slippage of 0.002 for each side of a round trip. This function must be called within the `init(context)` function. ```Python # 设置期权交易滑点为双边0.004(单边0.002) def init(context): set_option_slippage(0.004) ``` -------------------------------- ### Getting Single Security Info - supermcode - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves basic information for a single security using its Tonghuashun code. Requires the security symbol as a string. Note that the returned abbreviation cannot be used to determine if a stock is ST in backtesting. ```python data = get_security_info('000001.SZ') print(data) ``` -------------------------------- ### Setting Margin Rate for Symbol - set_margin_rate - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md This example demonstrates setting the margin rate for the 'RB' symbol (Rebar futures) to 9% (0.09) for both long and short positions. This function must be called within the `init(context)` function. ```Python # 设置螺纹钢的保证金比例为9% def init(context): set_margin_rate('RB',0.09,0.09) ``` -------------------------------- ### Getting All Securities Info - supermcode - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves basic information for all securities or a specified type of security on a given date. Allows filtering by security type (`ty`) and specifying the query date. Note that the returned abbreviation cannot be used to determine if a stock is ST in backtesting. ```python #查询2023年8月1日处于上市状态的沪京深股票信息 data = get_all_securities('stock','20230801') print(data) ``` -------------------------------- ### Getting Resistance and Support Levels (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves price resistance and support level data for multiple securities. Parameters include a list of symbols, start/end dates (or bar count), frequency step ('1d', '30m', '5m'), desired fields ('resistance_line', 'support_line'), bar count (cannot be used with start_date), and output format (is_panel). Panel format data can be converted to a multi-index DataFrame using to_frame(). ```Python # 000001.SZ在2023年8月1日至2023年8月10日阻力线的日数据,字典形式输出 data = get_resistance_support( symbol_list='000001.SZ', start_date='20230801', end_date='20230810', fre_step='1d', fields=['resistance_line'], bar_count=None, is_panel=0 ) print(data) ``` -------------------------------- ### Getting Margin Trading and Securities Lending Data (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves historical margin trading and securities lending data for stocks. Parameters include a list of security codes, start/end dates (or count), desired fields ('fin_value', 'sec_value', etc.), count (cannot be used with start_date), and output format (is_panel). Data is only available at a daily frequency. Panel format data can be converted to a multi-index DataFrame using to_frame(). ```Python #获取平安银行2023年8月1日过去20天的融资余额与融券余额数据 data =get_mtss(['000001.SZ'], None, '20230801', ['fin_value', 'sec_value'], 20, is_panel=0) print(data) ``` -------------------------------- ### Getting Current Bar Time - get_datetime - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md This example shows how to get the current bar's time using `get_datetime()` within the `handle_bar` function. It also demonstrates calculating and formatting the previous day's date using `timedelta`. ```Python from datetime import timedelta as td def init(context): pass def handle_bar(context,bar_dict): # 获取当前bar的时间 time = get_datetime() log.info(time) # 获取回测前一天日期 yesterday_time = get_datetime()-td(days=1) yesterday_date = yesterday_time.strftime("%Y%m%d") log.info(yesterday_date) ``` -------------------------------- ### Initialize Futures Account and Subscribe - Python Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md This Python snippet shows the necessary steps in the `init` function to prepare for futures trading. It initializes a futures account with 200,000 cash using `set_subportfolios`, sets the instrument code, and subscribes to the specified futures contract ('RB9999') using the `subscribe` function to receive market data. Subscription is crucial for accessing historical and real-time data for the instrument. ```Python def init(context): #设立商品期货账户 set_subportfolios([{"cash": 0, "type": 'stock'},{"cash": 200000, "type": "future"}]) #订阅需要交易的期货品种 context.ins = 'RB9999' subscribe(context.ins) ``` -------------------------------- ### Getting Previous Bar Time - get_last_datetime - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md This example demonstrates how to retrieve the time of the previous bar using `get_last_datetime()` within the `handle_bar` function. This is useful for analyzing time series data. ```Python def init(context): pass def handle_bar(context,bar_dict): # 获取上一个bar的时间 last_datetime = get_last_datetime() log.info('回测前一个handle_bar调用时间:'+str(last_datetime)) ``` -------------------------------- ### Get Trading Days by Date Range (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves a list of trading days for the Shanghai, Shenzhen, and Beijing exchanges within a specified start and end date range, or a specified count of days. ```Python #查询2023年1月1日至2023年8月1日之间的交易日 tdays_list = get_trade_days('20230101','20230801') print(tdays_list) ``` -------------------------------- ### Initializing Portfolio Optimizer (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Provides the signature and parameters for initializing the OptimizePort class. It shows how to create an optimizer instance with various configuration options like expected returns, optimization date, focus, benchmark, risk aversion, cost, period, current holdings, and long/short strategy. ```Python OptimizePort(stock_return, trade_date, return_expect, opt_focus='UI', benchmark='000905.SH', loss_aversion=0.5, cost=0.003, period='d', holds=0, long_short='long-only') ``` -------------------------------- ### Getting Historical Tick Data (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves historical market tick snapshot data for multiple securities over a specified date range. Supports fetching intraday tick data. Requires security codes (string or list), start and end dates/times, and a list of fields. Note that fetching data for the current day may time out if the response exceeds six seconds. ```Python # 获取平安银行的2023年8月1日9点23分至9点30分的成交价 data = get_tick('000001.SZ','20230801 09:23','20230801 09:30',['current']) print(data) ``` -------------------------------- ### 前端申购费用计算公式 Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md 前端收费指的是你在购买开放式基金时就支付申购费的付费方式。 申购(认购)费用——前后端收费 申购(认购)就是在基金成立后的存续期间(认购则是在基金发行时的募集期间),投资者向基金公司购买基金份额的交易行为。在交易过程中,投资者都需要向基金公司支付一定的手续费。这种手续费,称为申购(认购)费用。 申购(认购)费用分为前端收费和后端收费两种模式。 前端收费指的是你在购买开放式基金时就支付申购费的付费方式。后端收费指的则是你在购买开放式基金时并不支付申购费,等到卖出时才支付的付费方式。后端收费的设计目的是为了鼓励你能够长期持有基金,因此,后端收费的费率一般会随着你持有基金时间的增长而递减。某些基金甚至规定如果你能在持有基金超过一定期限后才卖出,后端收费可以完全免除。 通过不同平台购买基金,折扣率会不同,回测中默认值为0.1,也可以通过函数set_discount_rate()函数来自定义设置申购折扣率。 注意:当前所有平台只对前端申购费用进行打折,其他费用不应用折扣率这一参数。 ```Formula 申购费用=净申购金额×申购费率×折扣率 净申购金额=申购金额−申购费用 根据公式1和2得到:净申购金额=申购金额÷(1+申购费率×折扣率) 申购费用=申购金额×申购费率×折扣率÷(1+申购费率×折扣率) ``` -------------------------------- ### Initializing Trading API - Simulation Counter - Python Source: https://github.com/fisher188/supermcode/blob/main/模拟仿真.md This Python snippet demonstrates how to initialize the trading API within the research environment for use with the Simulation Counter. It imports the necessary class and creates an instance using a logged-in account ID. ```Python from tick_trade_api.api import TradeAPI trade_api = TradeAPI(account_id='84728199') #填入已登录的资金账号 ``` -------------------------------- ### Get All Trading Days (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves a list of all historical trading days for the Shanghai, Shenzhen, and Beijing exchanges. This function requires no parameters. ```Python #查询所有交易日 tdays_list = get_all_trade_days() print(tdays_list) ``` -------------------------------- ### Initialize Factor Analysis Class with Parameters Source: https://github.com/fisher188/supermcode/blob/main/研究环境_实盘.md Defines the `FactorAnalyse` class and sets core parameters for the analysis, including start/end dates, benchmark, stock pool, factor grouping, rebalancing period, and frequency. ```python import alphalens import pandas as pd import numpy as np import time import statsmodels.api as sm import scipy as sp class FactorAnalyse(object): #==========================================因子检测参数设置============================================================== start_date = '2021-05-22' #回测开始时间 end_date = '2021-06-21' #回测结束时间 benchindex = '000300.SH' #基准指数设置 stockpool = '000905.SH' #股票池设置 quantiles=3 #因子分组数量 periods=1 #调仓周期 frequency='daily' #调仓频率'daily','weekly','monthly'一周按5个交易日计算,一月按21个交易日计算 ``` -------------------------------- ### Get Concept Classification Info (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves information for all TongHuaShun concepts, including classification details and corresponding index codes, for a specified date. ```Python #查询2023年8月1日所有同花顺概念信息 concept_info = get_concept_relate(date = '20230801') print(concept_info) ``` -------------------------------- ### Get Stock Industry Classification (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves the industry classification information for a specific stock code on a given date. Supports multiple industry classification systems. ```Python #查询300033.SZ(同花顺)在2023年8月1日的行业分类信息 industry_info = get_symbol_industry('300033.SZ',date='20230801') print(industry_info) ``` -------------------------------- ### Get Industry Constituent Stocks (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves the list of stock codes that are constituents of a specified industry index on a given date. Requires the industry index symbol and an optional date. ```Python #查询2023年8月1日中信二级行业-一般零售的成分股列表 index_list = get_industry_stocks('CI311000','20230801') print(index_list) ``` -------------------------------- ### Demonstrating Order Execution Delay Issue - Python Source: https://github.com/fisher188/supermcode/blob/main/模拟仿真.md This snippet illustrates a potential problem in live trading where orders do not execute instantly. It attempts to record position information immediately after placing an order and then access it after a short delay, which can lead to errors if the order has not yet been filled and updated the portfolio data. ```Python import time def init(context): g.information = {} g.symbols = ['000001.SZ','600519.SH'] def handle_bar(context): for symbol in g.symbols: order(symbol,100) for symbol in list(context.portfolio.positions): g.information[symbol] = 1 time.sleep(3) for symbol in list(context.portfolio.positions): print(g.infomation[symbol]) ``` -------------------------------- ### Getting Index List by Suffix - supermcode - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Queries for a list of indices based on their code suffix on a specific date. Requires the index code suffix and an optional query date. ```python #查询2023年8月1日后缀为'TI'的指数列表(同花顺指数) index_list = get_index_list('TI','20230801') print(index_list) ``` -------------------------------- ### 基金管理费计算公式 Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md 基金管理费是基金公司,也就是基金管理人的管理报酬,是基金公司的主要收入方式。 基金管理费是按日计提,月底由基金托管人(在我国是托管银行)从基金总资产中一次性支付给基金管理人,不另外向投资人收取。 同样,基金托管费,销售服务费也是这样收取的。直接从基金总资产中扣除,每日公布的基金净值是已经扣除了管理费、托管费和销售服务费的。因此,在回测中不在额外对这三项费用进行扣除。 ```Formula 每日应付的基金管理费=前一日的基金资产净值X年管理费率/当年天数 ``` -------------------------------- ### Implement Stock-Future Mixed Strategy - Python Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md Sets up separate sub-accounts for stocks and futures, configures trading parameters like slippage and volume limits, and defines the main trading logic in `handle_bar` which calls separate functions for stock and future trading based on moving averages. Includes an `after_trading` function for logging. ```python def init(context): #设立商品期货子账户,其中stock为30000,future为700000 set_subportfolios([{"cash": 300000, "type": 'stock'},{"cash": 700000, "type": "future"}]) set_volume_limit(0.25,0.5) set_slippage(PriceSlippage(0.1),'stock') set_slippage(FixedSlippage(0),'future') #设置需要交易的标的,螺纹钢 context.ins='RB9999' set_margin_rate('RB',0.09,0.09) def handle_bar(context, bar_dict): stock(context, bar_dict) future(context, bar_dict) def after_trading(context): #收盘查看账户基本合约持仓情况 log.info(context) pass def stock(context, bar_dict): price = history(['000001.SZ'], ['close'] , 20, '1d', False, 'pre', is_panel=1)['close'] ma20 = price.mean().values ma5 = price.iloc[-5:].mean().values if ma20ma5 and context.portfolio.stock_account.positions['000001.SZ'].available_amount>0: log.info('卖出平安银行') order_target('000001.SZ',0) def future(context, bar_dict): #获取螺纹钢的合约代码 g.con = get_futures_dominate('RB') #获取合约行情数据 hist1 = history_future(g.con,['close'], 250,'1m',False,'pre', is_panel=1)['close'] #计算250日,20日均线 ma250 = hist1.mean().values ma20 = hist1.iloc[-20:].mean().values p = hist1.iloc[-1].values #获取当前账户的多空单数量 short_amount = context.portfolio.future_account.positions[context.ins].short_amount long_amount = context.portfolio.future_account.positions[context.ins].long_amount #判断条件,如果价格突破250日线,且账户存在空单,则平空 if p > ma250 and short_amount > 0: order_future(context.ins, 15, 'close', 'short', None) #判断条件,如果20日均线突破250日线,且账户没有多单,则开多 elif ma20 > ma250 and long_amount == 0: order_future(context.ins, 15, 'open', 'long', None) #判断条件,如果价格突破跌破250日线,且账户存在多单,则平多 elif p <= ma250 and long_amount > 0: order_future(context.ins, 15, 'open', 'short', None) #判断条件,如果20日均线跌破250日线,且账户没有空单,则开空15手,即平多头的15手 elif ma20 <= ma250 and short_amount == 0: order_future(context.ins, 15, 'close', 'long', None) ​ ``` -------------------------------- ### Unsubscribing from Symbols - unsubscribe - Python Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md This example shows how to subscribe to the main Rebar futures contract ('RB9999') in the `init` function and then unsubscribe from it in the `after_trading` function. Unsubscribing removes the symbol from the contract pool. ```Python def init(context): #订阅螺纹主力合约 subscribe('RB9999') def after_trading(context): #取消订阅螺纹主力合约 unsubscribe('RB9999') ``` -------------------------------- ### Get Stock Factor Data (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves processed factor data (e.g., technical or financial indicators) for a list of stocks over a specified date range. Data is processed (winsorized, standardized). ```Python #获取300033.SZ(同花顺)和600519.SH(贵州茅台)2023年8月1日到2023年8月5日的macd因子数据 start_date = '20230801' end_date = '20230805' stocks=['600519.SH','300033.SZ'] factor_input = ['macd'] factor_info = get_sfactor_data(start_date, end_date, stocks, factor_input) ``` -------------------------------- ### Implement MA Crossover Strategy - SuperMind - Python Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md This Python code snippet demonstrates a basic moving average crossover strategy within the SuperMind backtesting engine. It initializes the strategy for a specific stock (600519.SH), calculates the 5-day and 20-day simple moving averages, and uses `order_target_percent` to buy or sell based on the crossover signals. ```Python #初始化账户 def init(context): g.index='600519.SH' def handle_bar(context,bar_dict): close = history(g.index, ['close'], 20, '1d', False, fq = 'pre', is\_panel=0) MA5 = close['close'].values[-5:].mean() #计算二十日均线价格 MA20 = close['close'].values.mean() #如果五日均线大于二十日均线 if MA5 > MA20: #使用所有现金买入证券 order_target_percent(g.index,1) #记录本次买入 log.info("全仓买入{0}".format(g.index)) #如果五日均线小于二十日均线 if MA5 < MA20 : #卖出所有证券 order_target_percent(g.index,0) #记录本次卖出 log.info("全仓卖出{0}".format(g.index)) ​ ``` -------------------------------- ### Get Concept Constituent Stocks (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves the list of stock codes that are constituents of a specified concept or concept index on a given date. Requires the concept code or concept index symbol. ```Python #查询2023年8月1日ChatGPT概念的成分股 stock_list = get_concept_stocks('886031.TI',date='20230801') print(stock_list) ``` -------------------------------- ### Get Industry Classification Info (Python) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md Retrieves A-share industry classification information, including industry names and codes, for a specified date and classification type. Supports various classification systems. ```Python #查询2023年8月1日中信二级行业分类信息 industry_info = get_industry_relate(date='20230801',types='ci_industryid2') print(industry_info) ``` -------------------------------- ### Futures MA Crossover Strategy Implementation - Python Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md Implements a futures trading strategy on the SuperMind platform. The `init` function sets up the account and subscribes to the instrument. The `handle_bar` function calculates 5-day and 20-day moving averages and executes trades based on MA crossovers and price relative to the 20-day MA. The `after_trading` function logs portfolio details. ```python def init(context): #设立商品期货账户 set_subportfolios([{"cash": 0, "type": 'stock'},{"cash": 200000, "type": "future"}]) #设置需要交易的标的,螺纹钢 context.ins = 'RB9999' #订阅需要交易的期货品种 subscribe('RB9999') def handle_bar(context, bar_dict): #获取螺纹钢的合约代码 g.con = get_futures_dominate('RB') #获取合约行情数据 date = get_datetime().strftime('%Y%m%d %H%M') if date[-1] == '0' or date[-1] == '5': hist1 = get_price_future(g.con,None,date,'1d',['close'],bar_count = 20) #计算5日,20日均线 ma20 = hist1.mean().values ma5 = hist1.iloc[-5:].mean().values p = hist1.iloc[-1].values #获取当前账户的多空单数量 short_amount = context.portfolio.future_account.positions[context.ins].short_amount long_amount = context.portfolio.future_account.positions[context.ins].long_amount #判断条件,如果价格突破20日线,且账户存在空单,则平空 if p > ma20 and short_amount > 0: order_future(context.ins, short_amount, 'close', 'short', None) #判断条件,如果5日均线突破20日线,且账户没有多单,则开多 elif ma5 > ma20 and long_amount == 0: order_future(context.ins, 15, 'open', 'long', None) #判断条件,如果价格突破跌破20日线,且账户存在多单,则平多 elif p <= ma20 and long_amount > 0: order_future(context.ins, long_amount, 'close', 'long', None) #判断条件,如果5日均线跌破20日线,且账户没有空单,则开空 elif ma5 <= ma20 and short_amount == 0: order_future(context.ins, 15, 'open', 'short', None) def after_trading(context): #收盘查看账户基本合约持仓情况 log.info('收盘查看账户基本合约持仓情况') log.info(context) ``` -------------------------------- ### 后端申购费用计算公式 Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md 后端收费指的则是你在购买开放式基金时并不支付申购费,等到卖出时才支付的付费方式。后端收费的设计目的是为了鼓励你能够长期持有基金,因此,后端收费的费率一般会随着你持有基金时间的增长而递减。某些基金甚至规定如果你能在持有基金超过一定期限后才卖出,后端收费可以完全免除。 由于赎回费用会根据持有期的长短进行调整,所以赎回的不同持有期的基金份额使用不同赎回费率,从申购/认购确认日开始计算到当前日(获取净值的日期)的自然日天数。遵循先进先出原则。 例如:3月1日申购了100份,4月1日申购了500份,5月1日赎回200份,则其中100份的持有期从3月1日算为61天,另外100份从4月1日起算为30天。同样,后端申购费率也采用这种机制。 ```Formula 后端申购÷认购费用=赎回份额×基金净值×对应份额后端申购(认购)费率 ``` -------------------------------- ### Initializing Strategy (init) Source: https://github.com/fisher188/supermcode/blob/main/API 文档 (2025_5_10).md The initialization function, executed once at the beginning of backtesting or simulated trading. It is mandatory for every strategy and is used to set up account information, backtesting parameters, global variables, benchmark, transaction fees, slippage, contract pool, etc. ```Python def init(context): #设置要交易的标的(平安银行) ,命名的时候注意不要覆盖系统变量 context.stock = '000001.SZ' ``` -------------------------------- ### 赎回费用计算公式 Source: https://github.com/fisher188/supermcode/blob/main/回测引擎.md 赎回就是投资者将持有的基金份额卖给基金公司的交易行为。在交易过程中,投资者需要向基金公司支付一定的手续费,这种手续费,称为赎回费用。 由于赎回费用会根据持有期的长短进行调整,所以赎回的不同持有期的基金份额使用不同赎回费率,从申购/认购确认日开始计算到当前日(获取净值的日期)的自然日天数。遵循先进先出原则。 例如:3月1日申购了100份,4月1日申购了500份,5月1日赎回200份,则其中100份的持有期从3月1日算为61天,另外100份从4月1日起算为30天。同样,后端申购费率也采用这种机制。 ```Formula 赎回费用=赎回份额X基金净值X赎回费率 ```