# 导入函数库 from jqdata import * # 初始化函数,设定基准等等 def initialize(context): # 设定沪深300作为基准 set_benchmark('000300.XSHG') # 开启动态复权模式(真实价格) set_option('use_real_price', True) # 输出内容到日志 log.info() log.info('初始函数开始运行且全局只运行一次') # 过滤掉order系列API产生的比error级别低的log # log.set_level('order', 'error') ### 股票相关设定 ### # 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱 set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') g.security = get_index_stocks('000300.XSHG') g.q = query(valuation).filter(valuation.code.in_(g.security)) g.N = 10 run_monthly(handle,1) def handle(context): df = get_fundamentals(g.q) df = df.sort(columns='market_cap') df = df[:g.N] tohold = df['code'].values print(tohold) for stock in context.portfolio.positions: if stock not in tohold: #卖出 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) #买入 for stock in tobuy: order_value(stock,int(cash/n))