文章采用均值为SMA(close, time_period = 3日),利用(收盘价 - 三日均线)计算偏离程度。
如果大于阈值(首个收盘价的2%)则开仓买入(卖出)
如果收盘价穿过均线说明均值偏离情况消失平仓。
文章采用Tick高频数据、也可以切换日收盘价数据进行改写。
话不多说上代码:
导出必要包和数据
import pandas as pd
import numpy as np
import datetime
import talib as tl
import warnings
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from pyecharts.charts import Kline,Line, Bar, Grid,Scatter
warnings.filterwarnings("ignore")
data = pd.read_csv('你的数据路径')
使用Ta-Lib库计算SMA均线(本文采用Tick数据,如果换成日数据请注意修改参数)
查看一下偏离度与阈值的变化情况
data = x
data['month'] = data.index.map(lambda x: x.strftime('%Y.%m'))
data['time'] = data.index.map(lambda x: x.time())
# 选取 阈值
threshold = data.close[0]*0.02
data['SMA'] = tl.SMA(data.close, len(data[(data.index.date==data.index.date[0])])*3)
data['distance'] = data['close'] - data['SMA']
data['threshold'] = threshold
df = data[['threshold', 'distance']].resample('1D').last().round(2)
df = df.dropna()
L_ = (
Line(init_opts=opts.InitOpts(theme=ThemeType.MACARONS, width='900px', height='500px'))
.add_xaxis(df.index.tolist())
.add_yaxis("距离",df['distance'].tolist())
.add_yaxis("下轨",(df['threshold']*-1).tolist())
.a