1.当我们形成了一个想法或者一个量化投资的策略的时候,我们会首先在历史的数据上检验我们的策略是否有效,即回测。在做回测的时候我们需要注意的是,在涨停的时候,虽然可能有一个成交价,但是实际情况下我们几乎不可能在这一个价格上买到股票;同理,在跌停的时候,我们也无法在历史数据中的成交价上卖出股票。因此,在回测的时候我们通常假定不能以涨停价格买入股票;不能以跌停价格卖出股票。
2.动量策略
start = '2012-01-01' #起始时间
end = '2015-06-01' #结束时间
benchmark = 'HS300' #策略参考标准,上指30
universe = set_universe('HS300') #设置股票池
capital_base = 10000000 #起始资金
refresh_rate = 10 #调仓频率
def initialize(account):
pass
def handle_data(account):
window = 20 #回望周期
history = account.get_attribute_history('closePrice',window+1) #多取一天收盘价,为了计算window个收益率
history = pd.DataFrame(history)
sharpe ={'symbol':[],'ratio':[]} #设置一个字典
for stk in account.universe:
sharpe['symbol'].append(stk) #字典中的symbol段,存储股票代码
ret = history[stk].pct_change() #之前讲history转化成DataFrame结构,方便计算```
基于sharpe_momentum的策略
import numpy as np
import pandas as pd
start = ‘2012-01-01’ #起始时间
end = ‘2015-06-01’ #结束时间
benchmark = ‘HS300’ #策略参考标准,上指30
universe = set_universe(‘HS300’) #设置股票池
capital_base = 10000000 #起始资金
refresh_rate = 10 #调仓频率,执行handle_Data时间
def initialize(account):
pass
def handle_data(account):
window = 20 #回望表现周期
history = account.get_attribute_history(‘closePrice’,window+1) #多取一天收盘价,为了计算window个收益率
history = pd.DataFrame(history)
sharpe ={‘symbol’:[],‘ratio’:[]} #设置一个字典
for stk in account.universe:
sharpe[‘symbol’].append(stk)
ret = history[stk].pct_change() #这个函数用来计算同colnums两个相邻的数字之间的变化率。
ratio = ret.mean()/ret.std() #夏普率简化为平均收益/收益波动,也不年化了,反正排序后效果是一致的
sharpe[‘ratio’].append(ratio)
#按照过去window日收益率排序,并选择前10%的股票作为买入候选
sharpe = pd.DataFrame(sharpe).sort(columns='ratio').reset_idnex()
sharpe =sharpe[len(sharpe)*4/5:len(sharpe)]
buylist = sharpe['symbol'].tolist()
for stk in account.valid_secpos:
if stk not in buylist:
order_to(stk,0)
#等权重买入所选股票
portfolio_value = account.referncePortfolioValue
filteredBuylist = []
for stk in buylist:
if not np.isnan(account.referencePrice[stk]):
filteredBuylist.append(stk)
for stk in filteredBuylist:
if stk not in account.valid_secpos:
orer_to(stk,int(portfolio_value/account.referencePrice[stk]/100.0/len(buylist))*100)