一、策略思路
在股票池里选取过去60个交易日累积收益率最高的一只股票买入,同时清仓一只已买入的股票,换仓频率为60天一次。
二、策略代码
import pandas as pd
start = '2020-01-01' # 回测开始时间
end = '2020-09-14' # 回测结束时间
benchmark = 'HS300' # 策略参考标准为沪深300
universe = ['000425.XSHE', '603881.XSHG'] # 证券池,
# capital_base = 100000
freq = 'd'
refresh_rate = 60 # 策略运行频率
max_history_window = 60
accounts = {
'fantasy_account':AccountConfig(account_type='security', capital_base = 100000) # 账户,初始模拟资金
}
def initialize(context):
pass
def handle_data(context): # 核心策略逻辑
account = context.get_account('fantasy_account')
hist = context.history(universe, 'closePrice', 60)
momentum = {'symbol': [], 'c_ret': []}
for stk in hist.keys():
momentum['symbol'].append(stk)
momentum['c_ret'].append(hist[stk]['closePrice'][-1]/hist[stk]['closePrice'][0])
momentum = pd.DataFrame(momentum).sort(columns='c_ret', ascending=False).reset_index()
momentum = momentum[0:1] # 获取累计收益率最高的一只股票
buylist = momentum['symbol'].tolist()
# print(buylist)
for stk in account.get_positions():
if stk not in buylist:
account.order_to(stk, 0) # 清仓
portfolio_value = account.portfolio_value
for stk in buylist:
account.order_pct_to(stk, 1.0/len(buylist)) # 买入
print(portfolio_value)
三、策略效果
四、策略总结
年化收益率126.4%,效果还行,主要还是取决于股票池股票的质量,股票池不同的股票,年化收益率相差比较大。
😁