%matplotlib inline
import matplotlib.pyplot as plt
import seaborn
import matplotlib as mpl
mpl.rcParams['font.family'] = 'serif'
import warnings; warnings.simplefilter('ignore') #忽略警告信息;
import numpy as np
import pandas as pd
import tushare as ts
策略思想
均值回归策略应用了股市投资中经典的高抛低吸思想,该类型策略一般在震荡市中表现优异; 但是在单边趋势行情中一般表现糟糕,往往会大幅跑输市场;
data = ts.get_k_data('hs300', start = '2010-01-01', end='2016-06-30')[['date','close']]
data.rename(columns={'close': 'price'}, inplace=True)
data.set_index('date', inplace = True)
data['price'].plot(figsize = (10,8))
2. 策略开发思路
data['returns'] = np.log(data['price'] / data['price'].shift(1))
SMA = 50
data['SMA'] = data['price'].rolling(SMA).mean()
threshold = 250 #阈值;
data['distance'] = data['price'] - data['SMA']
data['distance'].dropna().plot(figsize=(10, 6), legend=True)
plt.axhline(threshold, color='r')
plt.axhline(-threshold, color='r')
plt.axhline(0, color='r')
data['position'] = np.where(data['distance'] > threshold, -1, np.nan) #核心精髓;
data['position'] = np.where(data['distance'] < -threshold, 1, data['position'])
data['position'] = np.where(data['distance'] *
data['distance'].shift(1) < 0, 0, data['position'])
data['position'] = data['position'].ffill().fillna(0)
data['position'].ix[SMA:].plot(ylim=[-1.1, 1.1], figsize=(10, 6))
3. 计算策略年化收益并可视化
data['strategy'] = data['position'].shift(1) * data['returns']
data[['returns', 'strategy']].dropna().cumsum().apply(np.exp).plot(figsize=(10, 6))
网友评论