前言:

市场行情概览一般是从各行业指数/ETF的涨跌开始研究,行业内部各股票价格涨跌有较强的一致性,只是强弱有所差异,本文对A股上市股票基于申万行业分级进行分组,对各组内的个股研究两两相关性,供股票交易参考。

股票申万分级:

申万分级是申万宏源证券对A股上市公司根据其经营业务进行的行业划分,划分粒度分为一二三级。具体分类方式隔几年有所微调,链接是已经爬取好的A股申万分级结果,无需积分C币即可下载:
https://download.csdn.net/download/weixin_37598719/85238607

A股上市公司股价获取:

可以通过安装tushare模块并注册,即可进行包括但不限于股价的上市公司各种资料的获取,具体注册、使用教程见tushare官网网站链接:https://tushare.pro/register?reg=510562

关联性分析:

主要包括
1.动态时间扭曲(DTW):可以对不同长度的序列分析(用距离d表示,d越小则相关性越强)
2.斯皮尔曼相关系数:对秩分析(值域[-1,1],为正表示正相关,越大则相关性越强,下同)
3.皮尔逊相关系数:对离群点敏感,先对数据进行标准化
以上方法的具体原理自行百度,python代码如下:

相关性实现函数:

def pearsonr_spearman_cor(df, fill=True, standard=True):"""计算df列之间的pearsonr、spearman相关系数"""# 空值填充(计算DTW可以不用填充)if fill:df.fillna(method='ffill', inplace=True)df.fillna(method='bfill', inplace=True)# 按列标准化(计算pearsonr要进行标准化)if standard:for col in df:if col != "trade_date":df[[col]] = StandardScaler().fit_transform(df[[col]])# 计算相关系数print(df.corr())# sns.heatmap(df.corr(), annot=True)# plt.show()print(df.corr(method="spearman"))# sns.heatmap(df.corr(method="spearman"), annot=True)# plt.show()def dtw_cor(df, fill=True, standard=True):"""计算df列之间的dtw距离"""# 空值填充(计算DTW可以不用填充)if fill:df.fillna(method='ffill', inplace=True)df.fillna(method='bfill', inplace=True)# 按列标准化(计算pearsonr要进行标准化)if standard:for col in df:if col != "trade_date":df[[col]] = StandardScaler().fit_transform(df[[col]])# 计算相关系数columns = [col for col in df.columns if col !="trade_date"]res_lst = {}for col1, col2 in itertools.combinations(columns, 2):d, cost_matrix, acc_cost_matrix, path = accelerated_dtw(df[[col1]], df[[col2]], dist='euclidean')# plt.imshow(acc_cost_matrix.T, origin='lower', cmap='gray', interpolation='nearest')# plt.plot(path[0], path[1], 'w')# plt.xlabel(col1)# plt.ylabel(col2)# plt.title(f'DTW Minimum Path with minimum distance: {np.round(d,2)}')# plt.show()# print("{} and {} DTW distance:".format(col1, col2), round(d, 2))res_lst.update({"{}_{}".format(col1, col2): round(d, 2)})# 将距离d从小到大缩放到[1,-1]srcRange = (min(res_lst.values()), max(res_lst.values()))  # 原始范围dstRange = (1, -1)  # 对应的目标范围for key, val in res_lst.items():res_lst[key] = (res_lst[key] - srcRange[0]) * (dstRange[1] - dstRange[0]) / (srcRange[1] - srcRange[0]) + dstRange[0]# 以矩阵的形式打印res_df = pd.DataFrame(columns=columns, index=columns)for key, val in res_lst.items():res_df.loc[key.split("_")[0], key.split("_")[1]] = valres_df.loc[key.split("_")[1], key.split("_")[0]] = valprint(res_df)

完整代码如下:

import pandas as pd
import itertools
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from scipy import stats
import numpy as np
from dtw import dtw, accelerated_dtw
from industry_index import sw_class# 读取日线数据
total_daily_df = pd.read_csv('daily_price.csv', usecols=["ts_code", "trade_date", "close"])
# 获取股票申万分级信息
# sw1_class sw2_class sw3_class code  name
sw_filepath = "sw3.txt"
df_sw = sw_class(sw_filepath)
# merge
total_daily_df["code"] = total_daily_df["ts_code"].apply(lambda x: x[:-3])
total_daily_df = total_daily_df.merge(df_sw, on='code', how="left")
total_daily_df.sort_values(["ts_code", "trade_date"], inplace=True)
total_daily_df.drop_duplicates(subset=["ts_code", "trade_date"], inplace=True)"""对每个行业进行相关性分析"""
for sw_code, daily_df in total_daily_df.groupby(["sw3_class"], as_index=False):  # 此处按申万三级行业分类进行分组# 数据行转列daily_df_T = pd.DataFrame()for ts_code, sub_df in daily_df.groupby(["ts_code"], as_index=False):sub_df = sub_df[["trade_date", "close"]]sub_df.rename(columns={'close': ts_code}, inplace=True)if daily_df_T.shape[0] == 0:daily_df_T = sub_dfelse:daily_df_T = daily_df_T.merge(sub_df, on="trade_date", how="outer")# 按时间排序daily_df_T.sort_values(["trade_date"], inplace=True)# 删除日期列del daily_df_T["trade_date"]try:# pearsonr_spearman相关性分析pearsonr_spearman_cor(daily_df_T, fill=True, standard=True)# DTW相关性分析dtw_cor(daily_df_T, fill=True, standard=True)print("*********** end sw3 industry {} ***********".format(sw_code))except:continue

股票价格走势的行业关联性相关推荐

  1. matlab:预测股票价格走势

    matlab:预测股票价格走势 以ARIMA模型为例,介绍使用MATLAB进行股票价格走势预测 数据准备 模型拟合 模型预测 模型评估 股票价格走势预测是金融领域的一个重要问题,而MATLAB是一种强 ...

  2. 股票实战技巧——行业是选股核心原则(转载)

    2010-7-14 股票实战技巧--行业是选股核心原则 从 NEW星星 的博客 作者:NEW星星 股票实战技巧--行业是选股核心原则 Steven 人无远虑,必有近忧!一个人如果没有长远的谋划,就会有 ...

  3. 打造个人股票监控系统 实时跟踪股票价格走势

    每日股票监控器 对于非全职股民来说,很难日日盯盘,但又不想错过股市的赚钱机会,希望有个帮忙盯盘的小助手,因此开发个股票小助理 主要功能: 下载A股每日k线数据 计算每只股票的M5上穿M10时间 如果股 ...

  4. 用python读取股票价格_我用Python分析股票价格走势,学以致用获取第一桶金!

    [AI科技大本营导读]比来,A股市场尤其是上证指数走势凌厉,让营长有种身在牛市中的错觉.然而大盘天天涨,营长账户中仍是那几百万,甚至还有所缩水.夜深人静的时辰,营长经常会点着一支烟,考虑到底有没有一个 ...

  5. 计算机应用做银行it业务股票,中信建投--计算机应用行业:重视银行IT行业大拐点.pdf...

    证券研究报告 ·行业简评报告 重视银行 IT行业大拐点 计算机应用 事件: 维持 买入 据<财经>杂志报道,由人民银行牵头,工农中建四大国有行与 石泽蕤 三大运营商共同参与的央行法定数字货 ...

  6. 用python画股票价格走势图

    第一步.通过tushare模块爬取指定股票代码的数据存储到csv文件中. 知识点如下: 1.pip install 安装模块 2.tushare模块的 get_hist_data方法 3.df数据的. ...

  7. python时序预测股票价格走势

    股市有风险,投资需谨慎!!本程序对未来10天股票价格预测,具有一定的参考价值,但不代表股市的实际价格!!! 本程序基于holt-winter时序算法编写,只需输入股票名称及代码,通过tushare自动 ...

  8. 用聚宽量化炒股-5获取数据函数-5)获取当前时间股票数据函数get_current_data、查询股票所属行业get_industry

    1.get_current_data(security_list=None) 默认为None,代表当前universe中的股票. 该函数的返回值为一个dict对象.字典的key为股票代码,字典的val ...

  9. 动态分析股票走势算法图,股票趋势预测算法

    股票动态市盈率怎么计算出来的? 谈论起市盈率,这可真是有人爱,有人恨,有人认为有用,也认为无用.这个市盈率到底有没有用,咋用? 在为大家介绍我使用市盈率买股票的方法之前,先和大家推荐机构近期值得关注的 ...

最新文章

  1. 统计简单学_常用统计量
  2. java se 6u111_linux下查看已经安装的jdk 并卸载jdk
  3. Sql server profiler抓出的语句不可信
  4. BZOJ 3112 Zjoi2013 防守战线 单纯形
  5. MyEclipse导入新项目后,不能发布到Tomcat
  6. WeihanLi.Npoi 1.7.0 更新介绍
  7. php搜索图片不显示不出来了,PHP CURL采集百度搜寻结果图片不显示问题的解决方法【第1/4页】...
  8. 学习TeXworks编辑器(一)自定义快捷键详解
  9. java.io.File 的一些记录
  10. 数字图像处理·SLIC超像素分割算法C++实现
  11. 脊柱外科患者资料管理系统
  12. html页面嵌入高德地图,高德地图WEB版基础控件展示
  13. 【手把手 带你准备电赛】解答小课堂——串口通信和串行通信
  14. c++图像处理之对比度拉伸变换
  15. 品达通用_9. pd-tools-log
  16. RestTemplate技术预研——OkHttp
  17. 入职字节外包一个月,我离职了
  18. App关键字(100字符)优化的方法
  19. 电脑计算机显示调用失败和未执行,远程调用过程失败且未执行的详细处理方法...
  20. Linux ps命令和pstree命令

热门文章

  1. 基于STM32的TFDU4101红外通信IRDA+串口DMA方式
  2. 工地视频监控人员行为分析yoloV5
  3. 【PSV】GRAVITY DAZE(重力眩晕)
  4. Mathematica基本绘图
  5. VisualVM Mac 安装和
  6. 【短信插件】JSHOP_V2.4系统短信功能对接流程
  7. linux下vimrc文件
  8. 圣斗士星矢服务器维护时间,圣斗士星矢手游8月2日服务器内BUG说明公告
  9. matlab 修改语言环境,VS Code配置Matlab环境
  10. navicat怎么查看mysql版本_navicat怎么看版本