自学内容网 自学内容网

金融数据的pandas模块应用

金融数据的pandas模块应用

数据链接:https://pan.baidu.com/s/1VMh8-4IeCUYXB9p3rL45qw
提取码:c6ys

1. 导入所需基础库

import pandas as pd
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif']=['FangSong']
mpl.rcParams['axes.unicode_minus']=False

2. 读入数据

SH_Index = pd.read_excel('data/上证综指每个交易日价格数据(2020年).xlsx',sheet_name='Sheet1',header=0,index_col=0)
SH_Index.head()

在这里插入图片描述

3. 查看数据格式

SH_Index.tail()

在这里插入图片描述

SH_Index.index  # 查看数据框索引

在这里插入图片描述

SH_Index.shape  # 查看数据框的行数和列数

(243, 4)

SH_Index.describe()  # 查看数据框的基本统计指标

在这里插入图片描述

time1 = pd.date_range(start='2021-01-01',end='2022-12-31',freq='B') # 创建 2021年至2022年每个工作日的时间序列(选择不输入参数periods)
time1

在这里插入图片描述

SH_Index.plot(kind='line', subplots=True, sharex=True, sharey=True, layout=(2,2), figsize=(11,9), title='2020 年上证综指每个交易日价格走势图', grid=True, fontsize=13)
plt.show()

在这里插入图片描述

缺失值处理

SH_Index.isnull().any()

开盘价 False
最高价 False
最低价 False
收盘价 False
dtype: bool

Index_global=pd.read_excel('data/全球主要股指2020年4月日收盘价数据.xlsx',sheet_name='Sheet1',header=0,index_col=0)
Index_global.isnull().any() # 查找每一列发hi否存在缺失值

上证综指 True
道琼斯指数 True
富时100指数 True
日经225指数 True
dtype: bool

Index_global[Index_global.isnull().values==True] # 查找缺失值所在行

在这里插入图片描述

Index_dropna = Index_global.dropna()  # 直接删除
Index_dropna

在这里插入图片描述

Index_fillzero=Index_global.fillna(value=0) # 零值补齐
Index_fillzero

在这里插入图片描述

Index_ffill = Index_global.fillna(method='ffill') # 前值补齐法
Index_ffill

在这里插入图片描述

Index_bfill = Index_global.fillna(method='bfill') # 后值补齐法
Index_bfill

在这里插入图片描述

利用concat进行数据框的合并

SH_Index_2019=pd.read_excel('data/上证综指每个交易日价格数据(2019年).xlsx',sheet_name='Sheet1',header=0,index_col=0)

SH_Index_new = pd.concat([SH_Index_2019, SH_Index], axis=0)
SH_Index_new.head()

在这里插入图片描述

移动平均

SH_Index_MA10 = SH_Index_new['收盘价'].rolling(window=10).mean() #创建10日均值收盘价的序列
SH_Index_MA10=SH_Index_MA10.to_frame() # 将序列变为数据框
SH_Index_MA10=SH_Index_MA10.rename(columns={'收盘价': '10日平均收盘价(M10)'}) # 修改数据框列名
SH_Index_close=SH_Index_new['收盘价'].to_frame() # 创建一个每日收盘价的数据框
SH_Index_new1 = pd.concat([SH_Index_close, SH_Index_MA10], axis=1) # 合并成一个包括每日收盘价、10日均值收盘价的数据框
SH_Index_new1.plot(figsize=(9,6),title='2019-2020年上证综指走势',grid=True,fontsize=13)

在这里插入图片描述

移动波动率

SH_Index_rollstd=SH_Index_new['收盘价'].rolling(window=30).std() # 创建30日移动波动率的序列
SH_Index_rollstd=SH_Index_rollstd.to_frame() # 将序列变为数据框
SH_Index_rollstd=SH_Index_rollstd.rename(columns={'收盘价':'30日收盘价的移动波动率'}) # 修改数据框列名
SH_Index_rollstd.plot(figsize=(9,6),title='2019-2020 年上证综指移动波动率的走势',grid=True,fontsize=12)

在这里插入图片描述

SH_Index_rollcorr = SH_Index_new1.rolling(window=60).corr() # 计算移动相关系数
SH_Index_rollcorr

在这里插入图片描述

SH_Index_rollcorr=SH_Index_rollcorr.dropna() #删除缺失值
SH_Index_rollcorr.head() 

在这里插入图片描述


原文地址:https://blog.csdn.net/weixin_40234309/article/details/140551514

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!