导包:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
import tushare as ts
token = ''
pro = ts.pro_api(token)
import statsmodels.api as sm
import talib as ta
spr_festival = {2005:[20050131,20050222],2006:[20060119,20060210],
2007:[20070212,20070305],2008:[20080130,20080219],
2009:[20090119,20090206],2010:[20100208,20100226],
2011:[20110126,20110214],2012:[20120116,20120203],
2013:[20130204,20130222],2014:[20140123,20140213],
2015:[20150211,20150303],2016:[20160201,20160219],
2017:[20170120,20170209],2018:[20180208,20180228],
2019:[20190128,20190215],2020:[20200117,20200207],
}
returns = dict()
for k,v in spr_festival.items():
data = pro.index_daily(ts_code='000001.SH',start_date = v[0],end_date= v[1])
#print(data)
data['returns'] = (data.pct_chg/100+1).cumprod()-1
print(k,data.iloc[-1][-1])
returns[k] = [round(data.iloc[-1][-1],3)*100]
df = pd.DataFrame(returns)
fig = plt.figure(figsize = (10,4))
fig = plt.bar(df.columns,df.iloc[0],width=1.0,bottom=0,color='y',edgecolor='black')
for f in fig:
height = f.get_height()
plt.text(f.get_x()+f.get_width()/2-0.3,
1.006*height,'%s'%height,fontsize=12)
plt.title("上证指数春节前后10个交易日累计收益率",fontsize=16)
plt.xlabel('日期')
plt.ylabel('累计收益率%')
#检验不同参数下牛熊指标与中证指数的相关度
#检验不同参数下牛熊指标与中证指数的相关度
index = pro.index_daily(ts_code='000905.SH')[['trade_date','close','high','low']]
index_dailybasic1 = pro.index_dailybasic(ts_code='000016.SH')[['trade_date','turnover_rate_f']]
index_dailybasic2 = pro.index_dailybasic(ts_code='000016.SH',start_date='20050104',end_date='20230626')[['trade_date','turnover_rate_f']]
index_dailybasic = index_dailybasic1.append(index_dailybasic2)
data= pd.merge(index,index_dailybasic)
data.index = pd.to_datetime(data['trade_date'])
data.sort_index(ascending=True,inplace =True)
length = [2,5,10,20,30,60,90,120,150,180,250]
for i in length:
data[str(i)+'日真实波动率'] = ta.NATR(data.high,data.low,data.close,timeperiod=i)
data[str(i)+'日均换手率'] = ta.SMA(data.turnover_rate_f,timeperiod=i)
data['牛熊指标'] = data[str(i)+'日真实波动率'] / data[str(i)+'日均换手率']
df = data[['close','牛熊指标']].corr().iloc[0,1]
print(f"{i}日牛熊指标和收盘价的相关系数是:{df}")