每日调仓
并且融合以下三个策略的优点:
1,将基准回报率碾压成直线的小市值股票策略
小市值公司股票带来超高收益,但它们往往涨幅大跌幅也大,所以在此基础进行优化。
2,将动量带入价值投资的考虑动量的价值投资策略
将该策略中的动量因素加入本策略,经过对比回测显示,该思路进一步强化了小市值股票的收益率。
3,经典的Dual Thrust策略
考虑大盘走势选择性空仓是这个策略的要点之一,把大盘的空仓判定加入到小盘股策略中来,即前一日市场跌幅若大于3%,第二日空仓。
欢迎各种调整!应该还有不少提升空间。
源代码
import pandas as pd
import numpy as np
def init(context):
context.s1 = '000001.XSHG'
context.max_num_stocks = 40
context.days = 0
context.period_days = 1
context.relative_strength_6m = {}
def period_passed(context):
return context.days % context.period_days == 0
def before_trading(context):
context.days += 1
if not period_passed(context):
return
dofilter(context)
update_universe(context.fundamental_df.columns.values)
def dofilter(context):
fundamental_df = get_fundamentals(
query(fundamentals.eod_derivative_indicator.market_cap)
.order_by(fundamentals.eod_derivative_indicator.market_cap.asc())
.limit(context.max_num_stocks)
)
#Update context
context.stocks = [stock for stock in fundamental_df]
context.fundamental_df = fundamental_df
def rebalance(context, bar_dict):
for stock in context.portfolio.positions:
if stock not in context.fundamental_df:
order_target_percent(stock, 0)
context.stocks = [stock for stock in context.stocks
if stock in bar_dict and bar_dict[stock].is_trading and context.relative_strength_6m[stock] <-0.5]
if len(context.stocks) == 0:
return
weight = 1.0/len(context.stocks)
for stock in context.stocks:
order_target_percent(stock, weight)
def handle_bar(context, bar_dict):
his = history(10, '1d', 'close')['000001.XSHG']
if period_passed(context):
if his[9]/his[8]< 0.97:
if len(context.portfolio.positions)>0:
for stock in context.portfolio.positions.keys():
order_target_percent(stock, 0)
return
if not period_passed(context):
return
compute_relative_strength(context,bar_dict)
rebalance(context, bar_dict)
def compute_relative_strength(context,bar_dict):
prices = history (150, '1d', 'close')
#过去六个月的价格变化率
pct_change = (prices.ix[149] - prices.ix[19]) / prices.ix[19]
#print(prices.ix[19])
#print(pct_change)
priceofbase = history (150, '1d', 'close')[context.s1]
pct_changeforbase = (priceofbase.ix[149] - priceofbase.ix[19]) / priceofbase.ix[19]
pct_change = pct_change - pct_changeforbase
print(pct_change.index)
print(bar_dict)
if pct_changeforbase != 0:
pct_change = pct_change / abs(pct_changeforbase)
context.relative_strength_6m = pct_change