文章来源: 量化小课堂
#!/usr/bin/env python
#coding:utf-8
import pandas as pd
index_data = pd.read_csv('./all_trading_data/stock data/sh000001.csv', parse_dates=['date'])
index_data = index_data[['date', 'high', 'low', 'close', 'change']]
index_data.sort_values('date', inplace=True)
N1 = 20
N@ = 10
index_data['最近N1个交易日的最高点'] = pd.rolling_max(index_data['high'], N1)
index_data['最近N1个交易日的最高点'].fillna(value=pd.expanding_max(index_data['high']), inplace=True)
index_data['最近N2个交易日的最低点'] = pd.rolling_min(index_data['low'], N1)
index_data['最近N2个交易日的最低点'].fillna(value=pd.expanding_min(index_data['low']), inplace=True)
buy_index = index_data[index_data['close'] > index_data['最近N1个交易日的最高点'].shift(1)].index
index_data.loc[buy_index, '收盘发出的信号'] = 1
sell_index = index_data[index_data['close'] < index_data['最近N2个交易日的最低点'].shift(1)].index
index_data.loc[sell_index, '收盘发出的信号'] = 0
index_data['当天的仓位'] = index_data['收盘发出的信号'].shift(1)
index_data['当天的仓位'].fillna(method='ffill', inplace=True)
index_data['资金指数'] = (index_data['change'] * index_data['当天的仓位'] + 1.0).cumprod()
initial_idx = index_data.iloc[0]['close'] / (1 + index_data.iloc[0]['change'])
index_data['资金指数'] *= initial_idx
index_data[['date', 'high', 'low', 'close', 'change', '最近N1个交易日的最高点',
'最近N2个交易日的最低点', '当天的仓位', '资金指数']].to_csv('turtle.csv', index=False, encoding='gbk')
index_data['海龟法则每日涨跌幅'] = index_data['change'] * index_data['当天的仓位']
year_rtn = index_data.set_index('date')[['change', '海龟法则每日涨跌幅']] \
.resample('A', how=lambda x:(x+1.0).prod() - 1.0) *100
print year_rtn
网友评论