Strategy Learning Notes _ single Factor Strategy _ small Market capitalization Strategy
Single-factor strategy description: benchmark: based on Shanghai and Shenzhen 300 stocks as the benchmark Jiancang standard: select Shanghai and Shenzhen 300 stocks with the smallest market value N stocks buy and sell standard: position stocks are not in the list of the smallest N stocks to sell position stocks buy standard: belong to the smallest market value N stocks and unheld stocks buy adjustment cycle: the first working day of each month adjustment Time range of backtest: 2012-01-01
Code:
# Import function library from jqdata import * # initialize function Set benchmark, etc. Def initialize (context): # set Shanghai and Shenzhen 300 as benchmark set_benchmark ('000300.XSHG') # enable dynamic restoration mode (real price) set_option (' use_real_price' True) # output to log log.info () log.info ('initial function starts to run and only runs once globally') # filter out log # log.set_level ('order',' error') generated by order series API which is lower than error level # Stock related settings # the handling fee for each transaction in the stock class is: 3/10000 commission at the time of purchase The commission at the time of sale is 3/10000 plus 1/1000 stamp duty, and the minimum commission per transaction is 5 yuan set_order_cost (OrderCost (close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) Type='stock') # user definition # get_index_stocks get constituent stocks g.security = get_index_stocks ('000300.XSHG') # CSI 300 market capitalization data query statement g.Q = query (valuation) .filter (valuation.code.in_ (g.security)) # screen the smallest N stocks g.N = 10 run_monthly (handle) 1) # buy N stocks with the smallest market capitalization def handle (context): df = get_fundamentals (g.Q) df = df.sort_values ('market_cap') df = df [: G.N] tohold = df [' code'] .values for stock in context.portfolio.positions: if stock not in tohold: # sell order_target (stock 0) tobuy = [stock for stock in tohold if stock not in context.portfolio.positions] cash = context.portfolio.available_cash n = len (tobuy) # Buy for stock in tobuy: order_value (stock, int (cash/n))
Back test result