本文在上一篇文章(05dma_03rollingGridParamV2)面临问题
对于双均线,最终采用参数为(20,22),(30,35)这样的参数组合,显然不合理,有对行情进行拟合的嫌疑。
较合理的参数组合方式是,采用快线以及慢线相对快线的倍率。大致认为剔除二者相关性了(正交性)。
此时就无法借助run_combs创建组合计算指标了,需基于vbt创建新技术指标DualMA。
勘误:此篇文章部分截图可能有误,此文章的后继文章“DMA之六滑窗网格参数优选”修复此问题。请查阅后文。
01,基础配置信息
#conda envs:vectorbt_envimport warningsimport vectorbt as vbtimport numpy as npimport pandas as pdfrom datetime import datetime, timedeltaimport pytzfrom dateutil.parser import parseimport ipywidgets as widgetsfrom copy import deepcopyfrom tqdm import tqdmimport imageiofrom IPython import displayimport plotly.graph_objects as goimport itertoolsimport dateparserimport gcimport mathfrom tools import dbtools
warnings.filterwarnings("ignore")
pd.set_option('display.max_rows',500)pd.set_option('display.max_columns',500)pd.set_option('display.width',1000)02,行情获取和可视化
a,时间交易参数配置
# Enter your parameters hereseed = 42symbol = '002594.XSHE'metric = 'total_return'
start_date = datetime(2020, 1, 1, tzinfo=pytz.utc) # time period for analysis, must be timezone-awareend_date = datetime(2023,1,1, tzinfo=pytz.utc)time_buffer = timedelta(days=100) # buffer before to pre-calculate SMA/EMA, best to set to max windowfreq = '1D'
vbt.settings.portfolio['init_cash'] = 10000. # 100$vbt.settings.portfolio['fees'] = 0.0025 # 0.25%vbt.settings.portfolio['slippage'] = 0.0025 # 0.25%b,获取行情和行情mask
# Download data with time buffercols = ['Open', 'High', 'Low', 'Close', 'Volume']# ohlcv_wbuf = vbt.YFData.download(symbol, start=start_date-time_buffer, end=end_date).get(cols)
ohlcv_wbuf=dbtools.MySQLData.download(symbol).get() # 自带工具类查询assert(~ohlcv_wbuf.empty)ohlcv_wbuf = ohlcv_wbuf.astype(np.float64)
print("ohlcv_wbuf.shape:",ohlcv_wbuf.shape)print("ohlcv_wbuf.columns:",ohlcv_wbuf.columns)
# Create a copy of data without time bufferwobuf_mask = (ohlcv_wbuf.index >= start_date) & (ohlcv_wbuf.index <= end_date) # mask without buffer
ohlcv = ohlcv_wbuf.loc[wobuf_mask, :]
print("ohlcv.shape:",ohlcv.shape)
# Plot the OHLC dataohlcv.vbt.ohlcv.plot().show_svg() # 绘制蜡烛图# remove show_svg() to display interactive chart!ohlcv_wbuf.shape: (978, 5)ohlcv_wbuf.columns: Index(['Open', 'High', 'Low', 'Close', 'Volume'], dtype='object')ohlcv.shape: (728, 5)
20,网格参数-指标计算和可视化
仅可视化第一列
fast_windows = np.arange(10, 50,5)slow_multis = np.arange(1.5, 5.5, 0.5)print("fast_windows:",fast_windows)print("slow_multis:",slow_multis)
price=ohlcv_wbuf['Close']dualma = vbt.DualMA.run(price, fast_window=fast_windows,slow_multi=slow_multis,param_product=True)dualma = dualma[wobuf_mask]# there should be no nans after removing time bufferassert(~dualma.fast_ma.isnull().any().any())assert(~dualma.slow_ma.isnull().any().any())
print()print('dualma.fast_ma.head(3)')print(dualma.fast_ma.head(3))print('dualma.slow_ma.head(3)')print(dualma.slow_ma.head(3))
print()fig = ohlcv['Close'].vbt.plot(trace_kwargs=dict(name='Price'))fig = dualma.fast_ma.iloc[:,0].vbt.plot(trace_kwargs=dict(name="Fast MA col %s"%str(dualma.fast_ma.iloc[:,0].name)), fig=fig)fig = dualma.slow_ma.iloc[:,0].vbt.plot(trace_kwargs=dict(name="Slow MA col %s"%str(dualma.slow_ma.iloc[:,0].name)), fig=fig)fig.show_svg()fast_windows: [10 15 20 25 30 35 40 45]slow_multis: [1.5 2. 2.5 3. 3.5 4. 4.5 5. ]
dualma.fast_ma.head(3)dualma_fast_window 10 15 20 25 30 35 40 45dualma_slow_multi 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0date2020-01-02 00:00:00+00:00 46.665 46.665 46.665 46.665 46.665 46.665 46.665 46.665 45.824667 45.824667 45.824667 45.824667 45.824667 45.824667 45.824667 45.824667 45.3025 45.3025 45.3025 45.3025 45.3025 45.3025 45.3025 45.3025 44.9476 44.9476 44.9476 44.9476 44.9476 44.9476 44.9476 44.9476 44.816667 44.816667 44.816667 44.816667 44.816667 44.816667 44.816667 44.816667 44.594571 44.594571 44.594571 44.594571 44.594571 44.594571 44.594571 44.594571 44.5425 44.5425 44.5425 44.5425 44.5425 44.5425 44.5425 44.5425 44.440222 44.440222 44.440222 44.440222 44.440222 44.440222 44.440222 44.4402222020-01-03 00:00:00+00:00 46.972 46.972 46.972 46.972 46.972 46.972 46.972 46.972 46.128667 46.128667 46.128667 46.128667 46.128667 46.128667 46.128667 46.128667 45.5025 45.5025 45.5025 45.5025 45.5025 45.5025 45.5025 45.5025 45.1420 45.1420 45.1420 45.1420 45.1420 45.1420 45.1420 45.1420 44.964000 44.964000 44.964000 44.964000 44.964000 44.964000 44.964000 44.964000 44.723714 44.723714 44.723714 44.723714 44.723714 44.723714 44.723714 44.723714 44.6265 44.6265 44.6265 44.6265 44.6265 44.6265 44.6265 44.6265 44.555556 44.555556 44.555556 44.555556 44.555556 44.555556 44.555556 44.5555562020-01-06 00:00:00+00:00 47.138 47.138 47.138 47.138 47.138 47.138 47.138 47.138 46.456000 46.456000 46.456000 46.456000 46.456000 46.456000 46.456000 46.456000 45.7310 45.7310 45.7310 45.7310 45.7310 45.7310 45.7310 45.7310 45.3376 45.3376 45.3376 45.3376 45.3376 45.3376 45.3376 45.3376 45.112667 45.112667 45.112667 45.112667 45.112667 45.112667 45.112667 45.112667 44.871143 44.871143 44.871143 44.871143 44.871143 44.871143 44.871143 44.871143 44.7115 44.7115 44.7115 44.7115 44.7115 44.7115 44.7115 44.7115 44.660222 44.660222 44.660222 44.660222 44.660222 44.660222 44.660222 44.660222dualma.slow_ma.head(3)dualma_fast_window 10 15 20 25 30 35 40 45dualma_slow_multi 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0date2020-01-02 00:00:00+00:00 45.824667 45.3025 44.9476 44.816667 44.594571 44.5425 44.440222 44.6384 45.180455 44.816667 44.545676 44.440222 44.717692 45.135167 45.513134 46.025200 44.816667 44.5425 44.6384 45.135167 45.697429 46.307750 46.683111 47.0983 44.545676 44.6384 45.235806 46.025200 46.560460 47.0983 47.997679 48.61136 44.440222 45.135167 46.025200 46.683111 47.425238 48.410917 48.769630 48.8484 44.717692 45.697429 46.560460 47.425238 48.496066 48.803714 48.852357 49.430914 45.135167 46.307750 47.0983 48.410917 48.803714 48.892313 49.622778 50.14240 45.513134 46.683111 47.997679 48.769630 48.852357 49.622778 50.162574 50.3758222020-01-03 00:00:00+00:00 46.128667 45.5025 45.1420 44.964000 44.723714 44.6265 44.555556 44.6660 45.373636 44.964000 44.652162 44.555556 44.741538 45.119167 45.485821 45.984267 44.964000 44.6265 44.6660 45.119167 45.666714 46.291125 46.643333 47.0707 44.652162 44.6660 45.229677 45.984267 46.549080 47.0707 47.936429 48.56848 44.555556 45.119167 45.984267 46.643333 47.349905 48.362083 48.758074 48.8320 44.741538 45.666714 46.549080 47.349905 48.460984 48.784357 48.838471 49.366457 45.119167 46.291125 47.0707 48.362083 48.784357 48.878875 49.584500 50.12260 45.485821 46.643333 47.936429 48.758074 48.838471 49.584500 50.141139 50.3797782020-01-06 00:00:00+00:00 46.456000 45.7310 45.3376 45.112667 44.871143 44.7115 44.660222 44.6908 45.562273 45.112667 44.787297 44.660222 44.773846 45.116667 45.474478 45.950800 45.112667 44.7115 44.6908 45.116667 45.641143 46.267875 46.621889 47.0449 44.787297 44.6908 45.232742 45.950800 46.534598 47.0449 47.864554 48.52880 44.660222 45.116667 45.950800 46.621889 47.278952 48.320667 48.743185 48.8232 44.773846 45.641143 46.534598 47.278952 48.406803 48.770500 48.833885 49.298743 45.116667 46.267875 47.0449 48.320667 48.770500 48.860063 49.552222 50.09115 45.474478 46.621889 47.864554 48.743185 48.833885 49.552222 50.122772 50.388044
21,网格参数-信号计算和可视化
仅可视化第一列
dmac_size.shape: (728, 64)
dmac_size.iloc[:3,:3]:dualma_fast_window 10dualma_slow_multi 1.5 2.0 2.5date2020-01-02 00:00:00+00:00 True True True2020-01-03 00:00:00+00:00 True True True2020-01-06 00:00:00+00:00 True True True

Start 2020-01-02 00:00:00+00:00End 2022-12-30 00:00:00+00:00Period 728Total 474.03125Rate [%] 65.114183First Index 2020-01-15 16:52:30+00:00Last Index 2022-11-07 20:15:00+00:00Norm Avg Index [-1, 1] -0.159967Distance: Min 1.0Distance: Max 82.734375Distance: Mean 1.464916Distance: Std 5.175417Total Partitions 6.671875Partition Rate [%] 1.510978Partition Length: Min 41.671875Partition Length: Max 211.171875Partition Length: Mean 110.468174Partition Length: Std 78.523847Partition Distance: Min 26.78125Partition Distance: Max 82.734375Partition Distance: Mean 51.365493Partition Distance: Std 28.015768Name: agg_func_mean, dtype: object22,行情,信号的滑窗处理
注意点:
01,训练集和验证集比例3:1,或者2:1,对应:window_len和set_lens为4<1>1>(或3<1>1>),过大了历史包袱沉重,无法及时响应最新行情,过小了则容易参数跳变,形成类似过拟合效果
a,参数设置和效果预览
代码中
#todo 这里是自然日计算的,但后面训练,验证集个数计算都完全正确,哪里应该和预想的不一致合理的。实测bar_days= 60时
print(in_indexes[0][0])print(in_indexes[1][0])print(in_indexes[0][53:55])
2019-01-02 00:00:00+00:002019-03-25 00:00:00+00:00DatetimeIndex(['2019-03-25 00:00:00+00:00', '2019-03-26 00:00:00+00:00'], dtype='datetime64[ns, UTC]', name='split_0', freq=None)可见第二行第一个位于第一行第53个,不足设置的60,就是由于切分优先保证了数据的足量,但是数据间隔方面则可能有所重叠。# 滚动周期参数设置和大致效果可视化start_end_days=int((end_date-start_date).days) #todo 这里是自然日计算的,但后面训练,验证集个数计算都完全正确,哪里应该和预想的不一致bar_days= 80 # 训练,验证集时间长度,以此为单位test_bar_num=2 # 训练集时间长度verify_bar_num=1 # 验证集时间长度verify_overlap=0 # 验证集重叠时间长度pre_test_days=0 # 由于测试集一部分时间用于计算指标,导致实际训练时间不足,这个是一定程度补充的days周期# n取值需要满足:确保验证集合收尾相接# => (n-1)*(verify_bar_num-verify_overlap)+(verify_bar_num+test_bar_num)=start_end_days/bar_days# => n=(start_end_days/bar_days-test_bar_num-verify_overlap)/(verify_bar_num-verify_overlap)calc_n=(start_end_days/bar_days-test_bar_num-verify_overlap)/(verify_bar_num-verify_overlap)
split_kwargs = dict( n=int(calc_n), window_len=int(bar_days*(test_bar_num+verify_bar_num)+pre_test_days), set_lens=(int(bar_days*verify_bar_num),), left_to_right=False) # 10 windows, each 2 years long, reserve 180 days for test# 合理设置n,最好确保验证集,连续且无重复pf_kwargs = dict( direction='both', # long and short freq='d')print('split_kwargs:',split_kwargs)
def roll_in_and_out_samples(price, **kwargs): return price.vbt.rolling_split(**kwargs)
# 验证:单列数据验证,橘黄色验证集连续且无重复roll_in_and_out_samples(price, **split_kwargs, plot=True, trace_names=['in-sample', 'out-sample']).show_svg()split_kwargs: {'n': 11, 'window_len': 240, 'set_lens': (80,), 'left_to_right': False}
b,根据滑窗参数切分行情数据和信号
in_price.shape: (160, 11)out_price.shape: (80, 11)
in_price.index: RangeIndex(start=0, stop=160, step=1)in_price.columns: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype='int64', name='split_idx')
in_price[0:3]:split_idx 0 1 2 3 4 5 6 7 8 9 100 49.17 58.15 51.20 43.39 48.15 97.90 167.98 239.52 202.00 251.77 253.141 48.06 56.16 49.50 43.15 49.73 96.55 164.08 225.00 214.11 252.50 266.492 50.65 55.36 50.29 43.79 52.25 94.50 168.03 208.99 227.02 246.86 266.08
###############################in_dmac_size.shape: (160, 704)out_dmac_size.shape: (80, 704)
in_dmac_size.iloc[:5,:5]:split_idx 0dualma_fast_window 10dualma_slow_multi 1.5 2.0 2.5 3.0 3.50 True True True True True1 True True True True True2 True True True True True3 True True True True True4 True True True True True23,滑窗的收益数据计算
a,持有参数收益
在此区间,基础标的物表现
def simulate_holding(price, **kwargs): pf = vbt.Portfolio.from_holding(price, **kwargs) return pf.sharpe_ratio()
in_hold_sharpe = simulate_holding(in_price, **pf_kwargs)print(in_hold_sharpe.head(5))
out_hold_sharpe = simulate_holding(out_price, **pf_kwargs)print(out_hold_sharpe.head(5))split_idx0 0.2354461 -1.6306162 0.5988893 2.6473974 4.501923Name: sharpe_ratio, dtype: float64split_idx0 -0.9299561 2.0659912 4.1003003 4.8012914 0.688785Name: sharpe_ratio, dtype: float64b,网格参数收益(训练集和验证集)
in_sharpe.shape: (704,)dualma_fast_window dualma_slow_multi split_idx10 1.5 0 0.235446 2.0 0 0.235446 2.5 0 0.235446 3.0 0 0.235446 3.5 0 0.235446 ...45 3.0 10 0.663486 3.5 10 0.663486 4.0 10 0.663486 4.5 10 0.663486 5.0 10 0.663486Name: sharpe_ratio, Length: 704, dtype: float64
out_sharpe.shape: (704,)dualma_fast_window dualma_slow_multi split_idx10 1.5 0 -0.929956 2.0 0 -0.820595 2.5 0 -0.820595 3.0 0 -0.820595 3.5 0 -0.820595 ...45 3.0 10 -0.554763 3.5 10 -0.554763 4.0 10 -0.554763 4.5 10 -0.554763 5.0 10 -0.554763Name: sharpe_ratio, Length: 704, dtype: float64c,训练集上的最佳参数用于验证集
大致思路:
01,获取各split_idx的最佳收益(sharp_radio)的参数组合idxmax,也就是fast_window,slow_window,split_idx,三维索引元组
02,按照split_idx进行聚类,取得各split_idx对应的最佳参数。实际含义就是各滑动窗口的最佳参数
def get_best_index(performance, higher_better=True): if higher_better: return performance[performance.groupby('split_idx').idxmax()].index return performance[performance.groupby('split_idx').idxmin()].indexin_best_index = get_best_index(in_sharpe)
print('in_best_index[:5]')print(in_best_index[:5])
# 参数走势可视化def get_best_params(best_index, level_name): return best_index.get_level_values(level_name).to_numpy()in_best_fast_windows = get_best_params(in_best_index, 'dualma_fast_window')in_best_slow_multi = get_best_params(in_best_index, 'dualma_slow_multi')in_best_slow_windows = in_best_fast_windows*in_best_slow_multiin_best_window_pairs = np.array(list(zip(in_best_fast_windows, in_best_slow_windows)))print()print('in_best_window_pairs[:5][:]:')print(in_best_window_pairs[:5][:])pd.DataFrame(in_best_window_pairs, columns=['fast_window', 'slow_window']).vbt.plot().show_svg()in_best_index[:5]MultiIndex([(40, 5.0, 0), (10, 3.0, 1), (10, 1.5, 2), (10, 1.5, 3), (10, 1.5, 4)], names=['dualma_fast_window', 'dualma_slow_multi', 'split_idx'])
in_best_window_pairs[:5][:]:[[ 40. 200.] [ 10. 30.] [ 10. 15.] [ 10. 15.] [ 10. 15.]]
将滚动获取的最佳参数用于验证集,统计收益信息
in_best_index.shape: (11,)
in_best_index:MultiIndex([(40, 5.0, 0), (10, 3.0, 1), (10, 1.5, 2), (10, 1.5, 3), (10, 1.5, 4), (10, 1.5, 5), (10, 1.5, 6), (45, 2.5, 7), (10, 1.5, 8), (25, 2.0, 9), (10, 2.5, 10)], names=['dualma_fast_window', 'dualma_slow_multi', 'split_idx'])
out_dmac_size.shape: (80, 704)
out_dmac_size_reindexed[in_best_index].shape: (80, 11)
dmac_pf_out.trades.records[:5] id col size entry_idx entry_price entry_fees exit_idx exit_price exit_fees pnl return direction status parent_id0 0 0 199.762836 0 49.934525 24.937656 79 46.85 0.0 -641.111119 -0.064271 0 0 01 1 1 222.599259 0 44.811750 24.937656 79 58.80 0.0 3088.836429 0.309656 0 0 12 2 2 182.338041 0 54.706425 24.937656 79 88.73 0.0 6178.854345 0.619430 0 0 23 3 3 114.462060 0 87.147325 24.937656 79 183.53 0.0 11007.221874 1.103474 0 0 34 4 4 59.581957 0 167.417500 24.937656 79 176.88 0.0 538.856616 0.054020 0 0 4
out_test_sharpe.head(5)dualma_fast_window dualma_slow_multi split_idx40 5.0 0 -0.92995610 3.0 1 2.065991 1.5 2 4.100300 3 4.801291 4 0.688785Name: sharpe_ratio, dtype: float6424,sharp ratio的汇总可视化
cv_results_df = pd.DataFrame({ 'in_sample_hold': in_hold_sharpe.values, 'in_sample_median': in_sharpe.groupby('split_idx').median().values, 'in_sample_best': in_sharpe[in_best_index].values, 'out_sample_hold': out_hold_sharpe.values, 'out_sample_median': out_sharpe.groupby('split_idx').median().values, 'out_sample_test': out_test_sharpe.values})
color_schema = vbt.settings['plotting']['color_schema']
cv_results_df.vbt.plot( trace_kwargs=[ dict(line_color=color_schema['blue']), dict(line_color=color_schema['blue'], line_dash='dash'), dict(line_color=color_schema['blue'], line_dash='dot'), dict(line_color=color_schema['orange']), dict(line_color=color_schema['orange'], line_dash='dash'), dict(line_color=color_schema['orange'], line_dash='dot') ]).show_svg()
关注点:
蓝色部分 正常排序是(从上到下):点线,实现,线段,
橘色部分
实线对实线
说明测试集和验证集的周期收益情况,二者同时出现0轴同侧较好(同时上涨,同时下跌,保持行情的稳定性or延续性)
线段对线段
二者一方面随着各自颜色的实线趋势变化(受各自实线影响较大),其他应该无必然联系
点线对点线
蓝色点高于橘色点线,蓝色是训练集内最佳,橘色则是训练集得到最优参数用于验证集结果收益,大概率低于验证集。
测试,验证集时间长度差异,引入偏差
由于测试集一般是验证集的2-3倍(或更多),对于单边行情(假如上涨),则(测试集的)实线收益。蓝色线大概率位于橘色线上方。
如果下跌,则相反。蓝色由于时间长,大概率位于橘色下方。
注意: 01,202406,对于当前case,y周取值为sharp ratio夏普比,而非收益率。所以数据点高低并不反映收益率。 所以,以上结论需要稍斟酌,并不完全准确。
25,滚动回测收益可视化
# 验证集:原始价格变动out_price_org=out_price.iloc[-1, :]/out_price.iloc[0, :]print('out_price_org shape:',out_price_org.shape)print('out_price_org.head(5)')print(out_price_org.head(5))
# 验证集:持有收益率def simulate_holding(price, **kwargs): pf = vbt.Portfolio.from_holding(price, **kwargs) return pf.total_return()
out_hold_return = simulate_holding(out_price, **pf_kwargs)print()print('out_hold_return shape:',out_hold_return.shape)print('out_hold_return.head(5) + 1')print(out_hold_return.head(5)+1)
print()print('out_test_return shape:',out_test_return.shape)print('out_test_return.head(5) + 1')print(out_test_return.head(5)+1)
cv_results_df = pd.DataFrame({ 'out_price_org': out_price_org.cumprod(), 'out_hold_return': (out_hold_return.values+1).cumprod(), 'out_test_return': (out_test_return.values+1).cumprod()})
color_dmac_pfschema = vbt.settings['plotting']['color_schema']
cv_results_df.vbt.plot( trace_kwargs=[ dict(line_color=color_schema['blue']), dict(line_color=color_schema['blue'], line_dash='dash'), dict(line_color=color_schema['blue'], line_dash='dot') ]).show_svg()out_price_org shape: (11,)out_price_org.head(5)split_idx0 0.9405741 1.3154362 1.6259853 2.1112394 1.059162dtype: float64
out_hold_return shape: (11,)out_hold_return.head(5) + 1split_idx0 0.9358891 1.3088842 1.6178853 2.1007224 1.053886Name: total_return, dtype: float64
out_test_return shape: (11,)out_test_return.head(5) + 1dualma_fast_window dualma_slow_multi split_idx40 5.0 0 0.93588910 3.0 1 1.308884 1.5 2 1.617885 3 2.100722 4 1.053886Name: total_return, dtype: float64
可见,在上次降低技术指标的预热时间优化的基础上,整体收益进一步提升。改进后的策略避免了参数过拟合,挺高了鲁棒性,带来了收益改善。
26,计算正确性验证(略)
a,准备校验数据,数据展示b,行情->指标 计算正确c,指标->信号 计算正确d,信号->交易 计算正确部分信息可能已经过时