沪深300股票聚类可视化案例||tushare完整可运行代码逐行解释
上篇文章:《可视化股票市场结构||沪深300股票聚类可视化》逐行代码解释了sklearn中的一个案例:可视化股票市场结构。案例中采用的数据是美股。这篇文章将其移植到A股市场,看看我们的沪深300股票市场结构如何。采用的分类及可视化手段与sklearn案例完全一样。
沪深300
沪深300指数1是由上海和深圳证券市场中选取市值大、流动性好的300支A股作为样本编制而成的成份股指数。沪深300指数样本覆盖了沪深市场六成左右的市值,具有良好的市场代表性。由中证指数有限公司2编制负责。
可以通过tushare获取:
- 首先获取沪深300成分列表
- 再获取个股历史纪录,只保留时间、开盘价、收盘价,截取2017年到2019年间数据
import numpy as np
import matplotlib.pyplot as plt
import tushare as ts
hs_datas = ts.get_hs300s()
symbols_name = np.array(hs_datas['name'])
symbols_code = np.array(hs_datas['code'])
quotes = []
for index, code in enumerate(symbols_code):stock_data = ts.get_hist_data(code, start='2017-01-01', end='2019-01-01')stock_data.sort_values(by=['date'], inplace=True)stock_data.reset_index(inplace=True)stock_data = stock_data[['date', 'open', 'close']]quotes.append(stock_data)row_now = hs_datas[hs_datas['code'] == code]name = row_now.iloc[0]['name']print('已获取第', index + 1, '只股:', code, name, '2017-01-01 到 2019-01-01的历史数据')# exit()
print(quotes)
- 数据整理,转为可为模型使用的数据
close_prices = np.vstack([q['close'] for q in quotes])
open_prices = np.vstack([q['open'] for q in quotes])
# 每日价格变换可能承载我们所需信息
variation = close_prices - open_prices
通过这三步操作,就完成了沪深300指数个股的历史记录。
上述第2部分的代码所得结果,在处理第3步时,会出现如下错误:(已解决)ValueError: all the input array dimensions except for the concatenation axis must match exactly。3上面给出了原因及解决方案,仔细研究应该时可以解决的,如果没搞懂,可以留言问我要完整代码。
学习一个图结构
采用稀疏逆协方差评估来寻找哪些报价之间存在有条件的关联。
edge_model = covariance.GraphicalLassoCV(cv=5)
X = variation.copy().T
X /= X.std(axis=0)
edge_model.fit(X)
聚类
采用Affinity Propagation(近邻传播);因为它不强求相同大小的类,并且能从数据中自动确定类的数目。
_, labels = cluster.affinity_propagation(edge_model.covariance_)
n_labels = labels.max()
names = symbols_name[0:11]
for i in range(n_labels + 1):print('Cluster %i: %s' % ((i + 1), ', '.join(names[labels == i])))
嵌入到2D画布
采用 Manifold learning(流形学习)技术来实现2D嵌入。
node_position_model = manifold.LocallyLinearEmbedding(n_components=2, eigen_solver='dense', n_neighbors=6)embedding = node_position_model.fit_transform(X.T).T
可视化
3个模型的输出结合在一个2D图形上,节点表示股票,边表示:
- 簇标签用于定义节点颜色
- 稀疏协方差模型用于展示边的强度
- 2D嵌入用于定位平面中的节点
# Visualization
plt.figure(1, facecolor='w', figsize=(10, 8))
plt.clf()
ax = plt.axes([0., 0., 1., 1.])
plt.axis('off')# Display a graph of the partial correlations
partial_correlations = edge_model.precision_.copy() #偏相关分析
d = 1 / np.sqrt(np.diag(partial_correlations))
partial_correlations *= d
partial_correlations *= d[:, np.newaxis]
non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02)# Plot the nodes using the coordinates of our embedding
plt.scatter(embedding[0], embedding[1], s=100 * d ** 2, c=labels,cmap=plt.cm.nipy_spectral)# Plot the edges
start_idx, end_idx = np.where(non_zero)
# a sequence of (*line0*, *line1*, *line2*), where::
# linen = (x0, y0), (x1, y1), ... (xm, ym)segments = [[embedding[:, start], embedding[:, stop]]for start, stop in zip(start_idx, end_idx)]
values = np.abs(partial_correlations[non_zero])
lc = LineCollection(segments,zorder=0, cmap=plt.cm.hot_r,norm=plt.Normalize(0, .7 * values.max()))
lc.set_array(values)
lc.set_linewidths(15 * values)
ax.add_collection(lc)# Add a label to each node. The challenge here is that we want to
# position the labels to avoid overlap with other labels
for index, (name, label, (x, y)) in enumerate(zip(names, labels, embedding.T)):dx = x - embedding[0]dx[index] = 1dy = y - embedding[1]dy[index] = 1this_dx = dx[np.argmin(np.abs(dy))]this_dy = dy[np.argmin(np.abs(dx))]# print(dx)# print(this_dx)# exit()if this_dx > 0:horizontalalignment = 'left'x = x + .002else:horizontalalignment = 'right'x = x - .002if this_dy > 0:verticalalignment = 'bottom'y = y + .002else:verticalalignment = 'top'y = y - .002plt.text(x, y, name, size=10,horizontalalignment=horizontalalignment,verticalalignment=verticalalignment,bbox=dict(facecolor='w',edgecolor=plt.cm.nipy_spectral(label / float(n_labels)),alpha=.6))plt.xlim(embedding[0].min() - .15 * embedding[0].ptp(),embedding[0].max() + .10 * embedding[0].ptp(),)
plt.ylim(embedding[1].min() - .03 * embedding[1].ptp(),embedding[1].max() + .03 * embedding[1].ptp())plt.show()
输出结果
综述,整个过程除了获取沪深300指数个股资料部分的代码,其余各部分操作与《可视化股票市场结构||沪深300股票聚类可视化》4中完全一样,如需详细了解,可参考上文,特别是上文附录了大量相关细节。
如需完整代码,请留言索取。
Reference
维基百科 ↩︎
中证指数有限公司 ↩︎
(已解决)ValueError: all the input array dimensions except for the concatenation axis must match exactly ↩︎
《可视化股票市场结构||沪深300股票聚类可视化》 ↩︎
沪深300股票聚类可视化案例||tushare完整可运行代码逐行解释相关推荐
- 可视化股票市场结构||沪深300股票聚类可视化
前半部分是Visulizing the stock maket structure文章翻译,对代码进行逐行解释,并在文后附录所有参考链接.后半部分是基于案例做的沪深300可视化 此案例采用了几种非监督 ...
- tushare获取沪深300指数历史_在tushare上提取沪深300指交易数据
import numpy as np import pandas as pd import tushare as ts import MySQLdb as mdb #获取沪深300指数的股票名单 hs ...
- 最新沪深300股票一览
933 神火股份 300能源 68 赛格三星 300可选 937 金牛能源 300能源 527 美的电器 300可选 983 西山煤电 300能源 541 佛山照明 300可选 600028 中国石化 ...
- tushare获取沪深300指数历史_从Tushare获取历史行情数据
从Tushare获取历史行情数据,分为两种,一种是后复权(daily_hfq)数据,一种是不复权(daily)数据,获取到的数据存储在MongoDB数据库中,每个集合(collection)中,数据字 ...
- 基于支持向量机SVM的沪深300股票预测股票涨跌方向
结果参考:https://www.bilibili.com/video/BV1nY411z7Kk/?spm_id_from=333.999.0.0 附完整代码+数据
- 择时策略 —— 基于扩散指标的沪深300指数择时
1.策略概述 扩散指标的原始值是最近一段时间以来,股票池中符合要求的股票占股票池总数的比例,如果这个指标值比较高,一般认为说明市场方向性比较明确.理论上来说,任何单个股票的指标都能"扩散化& ...
- 量化入门系列:沪深300、中证500、中证1000的估值百分位
本系列通过一些实例介绍量化的入门知识,适合零基础的初学者.本篇计算三个宽基指数:沪深300.中证500.中证1000的估值百分位,并将其与价格百分位比较. 本文的程序运行前要先导入数据源和pandas ...
- tushare获得沪深300和中证500的股票
tushare获得沪深300和中证500的股票 import tushare as tsresult = ts.get_zz500s() result.to_csv("zz500.csv&q ...
- Tushare介绍和入门级实践(1)——使用tushare接口获取沪深300成分股交易日涨跌数据
这篇文章会介绍到的内容: Python部分一些基础操作 Tushare中的部分function 整合数据成我想要的数据样式 这篇文章难度为零,适合Python初学者. tushare是国内现有的免费数 ...
最新文章
- Swift3.0语言教程分割字符串与截取字符串
- linux mint 硬件配置,安装 - 硬件设置 - 《Linux Mint 学习笔记》 - 书栈网 · BookStack...
- JUC多线程:AQS抽象队列同步器原理
- 方法分享:有序集合分段
- access update语句执行_SQL Server与Access数据库sql语法十大差异
- java学习(68):局部内部类
- PXE(preboot execution environment):【网络】预启动执行环节:引导 live光盘 ubuntu livecd 16.4:成功...
- oracle12c正在检查环境变量,oracle11g安装客户端检查先决条件失败
- Koa框架教程,Koa框架开发指南,Koa框架中文使用手册,Koa框架中文文档
- 谈一谈chrome浏览器使用
- 01-SQL基本语句
- linux全局启动tomcat,linux下启动tomcat服务
- C语言有限域的构造,有限域(3)——多项式环的商环构造有限域
- CHM文件制作方法及制作中遇到的坑
- 2018-2019赛季多校联合新生训练赛第七场补题和题解(中石油)
- 如何用CSS实现角标
- Android实现平板的类股票列表联动
- 如何鼠标悬浮显示隐藏图片
- Gaussdb,国产数据库的崛起
- 嵌入式Linux学习经典书籍-学完你就是高手
热门文章
- 医疗图像论文笔记三:《HEp-2 Specimen Image Segmentation and Classification Using Very Deep Fully Convolutional》
- 分别以逆时针和顺时针旋转坐标点
- HDMI接口与HDMI协议
- 如果移动办公OA行业也有世界杯,OA厂商谁能夺冠?
- 【华为OD机试真题 JAVA】连续出牌数量
- C++函数传参int a,int *a,int a,const int a的区别
- 【预训练视觉-语言模型文献阅读】VL-BERT: PRE-TRAINING OF GENERIC VISUAL- LINGUISTIC REPRESENTATIONS(ICLR 2020)
- 小程序传布尔_拥抱和传布禅宗编码
- 机器学习编译入门课程学习笔记第二讲 张量程序抽象
- LED音乐频谱之概述