继续学习人民邮电出版的《机器学习实践指南》,第7章股市预测,模型直接拿来用于上证指数,动态时间扭曲建模,结果跟教程预测标普500差别很大。
文中涉及pandas_profiling模块,图像是嵌入式,Markdown没有显示结果。

本文仅用于python数据分析之DataFrame操作学习!

一 、指数搜索

import tushare as ts
ts.get_index()
code name change open preclose close high low volume amount
0 000001 上证指数 1.61 2727.0186 2702.1296 2745.6182 2751.8964 2702.4933 252019507 2815.8337
1 000002 A股指数 1.61 2857.6618 2831.5502 2877.1556 2883.7260 2831.9092 251741036 2814.3846
2 000003 B股指数 1.06 220.9384 220.0086 222.3326 223.2548 220.5027 278471 1.4491
3 000008 综合指数 1.73 2544.9532 2522.4297 2565.9899 2574.0928 2528.0644 53368275 585.2588
4 000009 上证380 1.46 4579.1702 4537.5197 4603.5710 4609.5472 4528.2879 55041282 629.8522
5 000010 上证180 1.88 7734.6028 7654.7969 7798.7930 7821.4258 7661.7982 83125699 1155.2277
6 000011 基金指数 0.91 6009.5347 5985.2705 6039.5412 6040.9660 5964.3047 153023459 407.7303
7 000012 国债指数 0.03 180.8213 180.8046 180.8513 180.8523 180.8106 400973 4.0256
8 000016 上证50 2.28 2597.9793 2569.7891 2628.4161 2636.1406 2580.3573 37231436 618.8246
9 000017 新综指 1.61 2304.1910 2283.1352 2319.9088 2325.2075 2283.4227 249192522 2677.9100
10 000300 沪深300 1.79 3629.5126 3589.0926 3653.2239 3663.9517 3588.7766 139603000 2112.2307
11 000905 中证500 1.19 5217.4880 5157.8235 5219.2809 5225.0268 5129.0733 127513289 1315.1903
12 399001 深证成指 1.30 10150.7840 10019.8580 10150.1250 10174.5090 9964.2860 38004697447 4354.5853
13 399002 深成指R 1.30 12453.4930 12292.8670 12452.6860 12482.6010 12224.6880 15836815504 2267.2686
14 399003 成份B指 1.57 4664.6670 4648.4650 4721.5380 4721.5380 4619.9620 10341618 0.7069
15 399004 深证100R 1.54 5590.8520 5518.6460 5603.5730 5620.6970 5501.8790 5399802857 993.9201
16 399005 中小板指 0.71 6681.1970 6588.8830 6635.7860 6699.7590 6525.1590 17873990979 1922.1422
17 399006 创业板指 1.06 1923.9600 1894.9430 1915.0460 1928.8790 1878.8490 9944795691 1473.2099
18 399008 中小300 0.79 1287.6060 1270.6290 1280.6110 1290.9450 1259.3420 9323739585 1237.4965
19 399100 新 指 数 1.33 7766.5520 7673.6800 7775.6440 7784.8760 7640.9580 37295220442 4316.5081
20 399101 中小板综 1.06 9720.5630 9601.0040 9702.4630 9740.9030 9546.9760 17873990979 1922.1422
21 399106 深证综指 1.28 1702.9490 1682.9300 1704.4620 1707.0660 1675.4420 38004697447 4354.5853
22 399107 深证A指 1.28 1781.9020 1760.9240 1783.4680 1786.2040 1753.0940 37985716774 4353.5633
23 399108 深证B指 0.87 821.9270 819.7140 826.8650 827.0460 814.0530 18980673 1.0220
24 399333 中小板R 0.71 7521.6910 7417.7640 7470.5670 7542.5880 7346.0230 3718392677 695.0080
25 399606 创业板R 1.06 2029.7650 1999.1520 2020.3610 2034.9540 1982.1730 2292605286 496.8369

二、导入上证指数数据

import pandas as pd
import numpy as np
#import pandas_datareader as pdr
cons = ts.get_apis()#建立连接#start_date = pd.to_datetime('2010-01-01')
#stop_date = pd.to_datetime('2020-03-12')
shx = ts.bar('000001',conn=cons,asset='INDEX',start_date='2019-01-01',end_date="")
shx = shx.dropna()#删除所有null行
shx.sort_values(['datetime'],inplace=True)#日期顺序
shx
code open close high low vol amount p_change
datetime
2019-01-03 000001 2461.78 2464.36 2488.48 2455.93 1243975.0 1.069228e+11 -0.04
2019-01-04 000001 2446.02 2514.87 2515.32 2440.91 1688776.0 1.392987e+11 2.05
2019-01-07 000001 2528.70 2533.09 2536.98 2515.51 1773050.0 1.455132e+11 0.72
2019-01-08 000001 2530.30 2526.46 2531.35 2520.16 1580991.0 1.233790e+11 -0.26
2019-01-09 000001 2536.42 2544.35 2574.41 2536.16 1918879.0 1.608125e+11 0.71
... ... ... ... ... ... ... ... ...
2020-03-16 000001 2897.30 2789.25 2898.04 2784.66 3518786.0 3.756270e+11 -3.40
2020-03-17 000001 2796.28 2779.64 2826.91 2715.22 3061496.0 3.230128e+11 -0.34
2020-03-18 000001 2792.32 2728.76 2815.87 2728.76 2911598.0 3.186114e+11 -1.83
2020-03-19 000001 2719.41 2702.13 2736.82 2646.80 3023027.0 3.305180e+11 -0.98
2020-03-20 000001 2727.02 2745.62 2751.90 2702.49 2520195.0 2.815834e+11 1.61

294 rows × 8 columns

1.简单数据汇总统计

shx.describe()
open close high low vol amount p_change
count 294.000000 294.000000 294.000000 294.000000 2.940000e+02 2.940000e+02 294.000000
mean 2926.098231 2929.446020 2946.941088 2907.772211 2.352751e+06 2.442761e+11 0.044728
std 151.817767 149.509525 151.194112 148.731806 1.014456e+06 1.007551e+11 1.272543
min 2446.020000 2464.360000 2488.480000 2440.910000 1.166468e+06 1.011039e+11 -7.720000
25% 2879.745000 2884.847500 2899.290000 2868.017500 1.577666e+06 1.656336e+11 -0.507500
50% 2931.255000 2937.880000 2949.600000 2916.680000 2.069502e+06 2.137574e+11 0.050000
75% 3006.552500 3008.082500 3027.267500 2989.060000 2.928917e+06 3.071326e+11 0.690000
max 3278.490000 3270.800000 3288.450000 3241.830000 5.838171e+06 5.257252e+11 5.600000
shx.corr()
open close high low vol amount p_change
open 1.000000 0.980505 0.990863 0.992840 0.436932 0.521928 -0.093711
close 0.980505 1.000000 0.992466 0.989918 0.467074 0.553057 0.062175
high 0.990863 0.992466 1.000000 0.989397 0.500027 0.581069 -0.018746
low 0.992840 0.989918 0.989397 1.000000 0.416248 0.503933 -0.022462
vol 0.436932 0.467074 0.500027 0.416248 1.000000 0.967034 0.062993
amount 0.521928 0.553057 0.581069 0.503933 0.967034 1.000000 0.046905
p_change -0.093711 0.062175 -0.018746 -0.022462 0.062993 0.046905 1.000000
from pandas_profiling import ProfileReport
profile=ProfileReport(shx, title='Pandas Profiling Report', html={'style':{'full_width':True}})
profile.to_widgets()

Report generated with pandas-profiling.

三、绘制历史收盘价

import matplotlib.pyplot as plt
#plt.style.use('ggplot')
%matplotlib inline
plt.subplots(figsize=(15,10))
shx['close'].plot(color='black')
plt.xlabel("datetime")
plt.title('SHX', fontsize=20)
Text(0.5, 1.0, 'SHX')

四、动态时间规整建模分析

动态时间规整(dynamic time)所做的事情是提供一个表示两个时间序列之间相似性的度量。

from scipy.spatial.distance import euclidean
from fastdtw import fastdtw

创建一个函数,接受两个序列,并返回他们之间的距离:

def dtw_dist(x,y):distance, path = fastdtw(x, y, dist=euclidean)return distance

将时间序列数据分成不同时期,每个期间长度为5天。为每个期间配上一个附加的点,用于创建x、y数据:

tseries = []
tlen = 5
for i in range(tlen, len(shx), tlen):   pctc = shx['close'].iloc[i-tlen:i].pct_change()[1:].values*100res = shx['close'].iloc[i-tlen:i+1].pct_change()[-1]*100tseries.append((pctc, res))
tseries[0]
(array([ 2.04961937,  0.72449073, -0.26173567,  0.70810541]),-0.36355061214062845)

有了序列,通过算法运行,获得每个序列相对于其他序列的距离度量:

dist_pairs = []
for i in range(len(tseries)):for j in range(len(tseries)):dist = dtw_dist(tseries[i][0], tseries[j][0])dist_pairs.append((i, j, dist, tseries[i][1], tseries[j][1]))

将数据放入DataFrame对象,删除相互距离为零的序列,因为它代表相同的序列,根据日期进行排序,只观测第一个序列在时间上排第二个序列之前的数据:

dist_frame = pd.DataFrame(dist_pairs, columns=['A','B','Dist','A Ret', 'B Ret'])
sf = dist_frame[dist_frame['Dist']>0].sort_values(['A','B']).reset_index(drop=1)
sfe = sf[sf['A']<sf['B']]
sfe
A B Dist A Ret B Ret
0 0 1 3.131531 -0.363551 -0.419387
1 0 2 2.370863 -0.363551 0.414181
2 0 3 3.664034 -0.363551 0.349048
3 0 4 3.457300 -0.363551 -0.050348
4 0 5 5.547099 -0.363551 -0.341154
... ... ... ... ... ...
3133 54 56 5.352938 -0.599757 1.816675
3134 54 57 8.648978 -0.599757 -0.344537
3190 55 56 11.521801 0.739499 1.816675
3191 55 57 8.997378 0.739499 -0.344537
3248 56 57 5.228805 1.816675 -0.344537

1653 rows × 5 columns

最后,将交易限制到相互距离小于1,而第一个序列的回报为正的情况:

winf = sfe[(sfe['Dist']<=1)&(sfe['A Ret']>0)]
winf
A B Dist A Ret B Ret
195 3 25 0.656402 0.349048 -1.040697
197 3 27 0.743235 0.349048 -0.809545
203 3 33 0.910900 0.349048 0.745477
213 3 43 0.832141 0.349048 -0.612869
794 13 54 0.704738 0.633807 -0.599757
1232 21 36 0.635324 2.375763 0.880344
1278 22 25 0.970138 0.689115 -1.040697
1295 22 42 0.912325 0.689115 -0.631965
1922 33 42 0.991940 0.745477 -0.631965
1923 33 43 0.596595 0.745477 -0.612869
2205 38 40 0.600886 0.476382 -0.487795
2210 38 45 0.748358 0.476382 1.782762
2264 39 42 0.663635 0.994858 -0.631965

绘制排名靠前的模式:

import matplotlib.pyplot as plt
%matplotlib inline
plt.subplots(figsize=(6,4))
plt.plot(np.arange(4), tseries[13][0])

plt.subplots(figsize=(6,4))
plt.plot(np.arange(4),tseries[54][0])
[<matplotlib.lines.Line2D at 0x2c5f6940c88>]

构造另一个函数评估交易,对于相似的历史曲线,只要返回正向盈利,就买入,否则,删除它们:

excluded = {}
return_list = []
def get_returns(r):if excluded.get(r['A']) is None:return_list.append(r['B Ret'])if r['B Ret']<0:excluded.update({r['A']:1})
winf.apply(get_returns, axis=1);
def get_stats(s, n=252):wins = len(s[s>0])losses = len(s[s<0])evens = len(s[s==0])mean_w = round(s[s>0].mean(),3)mean_l = round(s[s<0].mean(),3)win_r = round(wins/losses, 3)mean_trd = round(s.mean(),3)sd = round(np.std(s),3)max_l = round(s.min(),3)max_w = round(s.max(),3)sharpe_r = round((s.mean()/np.std(s))*np.sqrt(n),4)cnt = len(s)print('Trades:', cnt,\'\nWins:',wins,\'\nLosses:',losses,\'\nBreakeven:',evens,\'\nWin/Loss Ratio:',win_r,\'\nMean Win:',mean_w,\'\nMean Loss:',mean_l,\'\nMean',mean_trd,\'\nStd Dev:',sd,\'\nMax Loss:',max_l,\'\nMax win:',max_w,\'\nSharpe Ratio:',sharpe_r)
get_stats(pd.Series(return_list))
Trades: 7
Wins: 1
Losses: 6
Breakeven: 0
Win/Loss Ratio: 0.167
Mean Win: 0.88
Mean Loss: -0.739
Mean -0.508
Std Dev: 0.602
Max Loss: -1.041
Max win: 0.88
Sharpe Ratio: -13.3886

上述结果很差劲,模型没什么用!

上证指数预测之python建模与动态时间扭曲相关推荐

  1. Python实现基于动态时间规整的股市交易策略测试

    Python实现基于动态时间规整的股市交易策略测试 一.策略简介 二.策略原理 三.代码实现 四.测试策略 五.完整代码 一.策略简介 该项目采用Python语言,利用动态时间规整算法对沪深300市场 ...

  2. 交通物流模型 | Python建模实现动态交通分配优化问题求解

    文章目录 效果一览 文章概述 研究内容 程序设计 参考资料 效果一览 文章概述 交通物流模型 | Pyomo建模框架实现动态交通分配优化问题求解,DTA 交通分配问题通常需要考虑许多因素,例如道路容量 ...

  3. python动态映射_使用python进行动态时间扭曲(最终映射)

    我需要对齐两个声音信号,以便将一个信号映射到另一个(两个信号对应于相同的行为).我尝试从以下位置实现python代码: https://nipunbatra.github.io/blog/2014/d ...

  4. 动态时间规整算法: 从DTW到FastDTW

    目录 动态时间规整算法: 从DTW到FastDTW 总结: 简介[^1] DTW[^1] FastDTW:使用多级粗化的方法[^1] 结果 动态时间规整算法: 从DTW到FastDTW 总结: Fas ...

  5. 动态时间规整算法(dynamic time warping)

    动态时间规整 DT W 动态 时间 规整 DTW(dynamic time warping) 曾经是语音识 别的一种主流方法. 其 思想是:由于 语音信号是一种具有相当大随机性的信 号,即使相同说话者 ...

  6. 动态弯曲距离 java_DTW 动态时间弯曲距离 dynamic time warping Distance

    DTW 动态时间弯曲距离 dynamic time warping Distance it lists its algorithm(general) and its algorithm with re ...

  7. python灰色预测_【数学建模】灰色预测及Python实现

    关键词:灰色预测.Python.pandas.numpy 一.前言 本文的目的是用Python和类对灰色预测进行封装 二.原理简述 1.灰色预测概述 灰色预测是用灰色模型GM(1,1)来进行定量分析的 ...

  8. 2023年美赛C题Wordle预测问题二建模及Python代码详细讲解

    更新时间:2023-2-19 相关链接 (1)2023年美赛C题Wordle预测问题一建模及Python代码详细讲解 (2)2023年美赛C题Wordle预测问题二建模及Python代码详细讲解 (3 ...

  9. 【Python】监督学习-上证指数预测涨跌-SVM

    本实例来源于 MOOC_Python机器学习应用_第二周有监督学习_分类_上证指数预测涨跌. 由于下载不了课程所附的源数据,我采取了另一种渠道(调用tushare数据)来获取上证指数及个股数据. 附课 ...

最新文章

  1. pyqt designer connect无响应_【JavaWeb】HTTP协议的请求与响应
  2. MyBatis无限输出日志
  3. php reset input,PHP reset() 函数
  4. Blend制作的下载动画
  5. 变量 常量 作用域和命名规范
  6. 01迷宫(洛谷-P1141)
  7. Java中isAssignableFrom()方法与instanceof()方法用法
  8. ROS学习笔记五:理解ROS topics
  9. 时间序列经济python_(13)Python初入坑之时间序列基础内容
  10. 浅谈5类过零检测电路
  11. jsp post中文乱码
  12. 闲置的eSATA接口,会影响Windows 7的启动速度
  13. 投资学U14 债券的估值和收益率 习题解读
  14. DirectX12初始化三——DirectX图形基础结构,功能支持检测,资源驻留
  15. 110 Ruby 版本管理器【Rails后端开发训练营】
  16. Nginx最新教程通俗易懂
  17. python使用BeautifulSoup爬取2345电影网
  18. OCA全贴合材料工艺解析
  19. 12_心理咨询_微信小程序项目实战_数据交互_深入理解小程序
  20. 一些名词解释记录--计算机网络实验

热门文章

  1. android实现悬浮按钮功能
  2. 非线性方程求解 不动点迭代法
  3. 深入分析linux内核的内存分配函数devm_kzalloc
  4. Git 常用基本操作
  5. JS使用Lodop控件打印表单和二维码
  6. 一起来聊聊MySQL 8.0 的特性及排名可好?
  7. edge for android 6.0,Microsoft Edge for Android v44
  8. Java 时间戳转换为日期格式
  9. Windows磁盘管理(虚拟磁盘)
  10. 白帽子讲WEB安全读书笔记(慢慢更新)