羊驼交易法则
起始时随机买入N只股票,每天卖掉收益最差的M支,再随机买入剩余股票池的M支。
随机选股,周期调仓
改进策略:
买入历史收益率最低的N只股票,调仓日留下反转程度大的股票,卖掉表现最差的M只股票
再买入收益率最低的M只股票
from jqdata import * 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') g.security = get_index_stocks('000300.XSHG') g.period = 30 # 选取30天来计算收益率 g.N = 10 # 总共持有10支股票 g.change = 1 # 每次调仓1只股票 g.init = True # 只运行一次 run_monthly(handle, 1) # 获取所有按收益增长率排序之后的沪深300股票 def get_sorted_stocks(context, stocks): df = history(g.period, field='close',security_list=stocks).T df['ret'] = (df.iloc[:,len(df.columns)-1] - df.iloc[:,0]) / df.iloc[:,0] df = df.sort_values('ret', ascending=False) return df.index.values def handle(context): if g.init: # 初始化,买入收益增长率最小的N支 stocks = get_sorted_stocks(context,g.security)[:g.N] cash = context.portfolio.available_cash / len(stocks) for stock in stocks: order_value(stock, cash) g.init = False return # 调仓卖掉原有股票中反转最小的股票 stocks = get_sorted_stocks(context, context.portfolio.positions.keys()) for stock in stocks[-g.change:0]: order_target(stock, 0) # 调仓买入新的收益增长率最低的 stocks = get_sorted_stocks(context, g.security) for stock in stocks: if len(context.portfolio.positions) >= g.N: break if stock not in context.portfolio.positions: order_value(stock, context.portfolio.available_cash)