其他分享
首页 > 其他分享> > 使用Tushare接口做中证500基差图

使用Tushare接口做中证500基差图

作者:互联网

tushare id:463640

# 基差
import pandas as pd

import datetime
import time
import numpy as np
import tushare as ts
# 获取今天(现在时间)
today = datetime.datetime.today()
yesterday = today - datetime.timedelta(days=1)
# 昨天
day_yes = 10000 * yesterday.year + 100 * yesterday.month + yesterday.day
# 前年昨天
year_yes2 = 10000 * (yesterday.year-2) + 100 * yesterday.month + yesterday.day
#pro = ts.pro_api('70a8f0ba9e0cf7cbb006b179f321ec7c2866f5e9aae2e59711c7f516')
# 
#df = pro.fut_daily(start_date=str(year_yes2),end_date=str(day_yes),ts_code = 'IC2008.CFE')

# 数据接口//***填Tushare接口token
pro = ts.pro_api('***')

'''
# 新浪财经接口
import requests
import sys
IC_list = ['IC2008.CFE','IC2009.CFE','IC2012.CFE','IC2103.CFE','IC2106.CFE','IC2109.CFE','IC2203.CFE',]

future_code = 'IC2008'
url_str = ('http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesDailyKLine?symbol='
 +future_code)
r = requests.get(url_str)
r_json = r.json()
r_lists = list(r_json)
print('future_code,date,open,high,low,close,vol')


for r_list in r_lists:
    for v in r_list:
        print(v + ',',end='')
    print('\n')
'''

# akshare接口
import akshare as ak

futures_main_sina_hist = ak.futures_main_sina(symbol="IC2203", trade_date="20210929")
print(futures_main_sina_hist)

#返回相差天数
def Caltime(date1,date2):
    date1=time.strptime(date1,"%Y-%m-%d")
    date2=time.strptime(date2,"%Y%m%d")
    date1=datetime.datetime(date1[0],date1[1],date1[2])
    date2=datetime.datetime(date2[0],date2[1],date2[2])

    return (date2-date1).days

# WIND数据接口
from WindPy import w
w.start()
w.isconnected()
IC_list = ['IC2008.CFE','IC2009.CFE','IC2012.CFE','IC2103.CFE','IC2106.CFE','IC2109.CFE','IC2203.CFE',]
df = pd.DataFrame()
for value in IC_list:
    df_tmp = w.wsd(value, "trade_hiscode,close,ltdate_new", "2020-01-01", str(day_yes), 'Days=Alldays;Fill=Previous;TradingCalendar=CFFEX',usedf=True)[1]
    df_tmp.columns = [value[:6],value[:6]+'收盘价',value[:6]+'最后交易日']
    df_tmp[value[:6]+'date'] = '20'+value[2:6]+'20'
    df =pd.concat([df,df_tmp],axis=1)
df_zz500 = w.wsd("000905.SH", "trade_hiscode,close", "2020-01-01", str(day_yes), "Days=Alldays;Fill=Previous",usedf=True)[1]
df_zz500.columns = ["000905.SH",'中证500收盘价']
df = pd.concat([df_zz500,df],axis=1)
df = df.reset_index()
df[['index']] = df[['index']].astype(str)
for value in IC_list:
    df[value[:6]+'时间差'] = np.nan
    for i in range(df.shape[0]):
        df[value[:6]+'时间差'].iloc[i] = Caltime(df['index'].iloc[i],df[value[:6]+'date'].iloc[i])

for value in IC_list:
    df[value[:6]+'基差']=(df[value[:6]+'收盘价']/df['中证500收盘价']-1)*365/df[value[:6]+'时间差']

data = df.iloc[:,-len(IC_list):]
data = pd.concat([df['index'],data],axis=1)
data = data.set_index(['index'])                
data = data[data.columns[::-1]]
data = data.dropna(axis=0,how='all') 
data['基差序列'] = np.nan
for indexs in data.index:
    data['基差序列'].loc[indexs] = data.loc[indexs][np.isfinite(data.loc[indexs])][0]
data['基差序列'] = data['基差序列'].apply(lambda x: round(float(x)*100,2))


# 基差图
import pyecharts.options as opts
from pyecharts.charts import Line
l2 = (
    Line(init_opts=opts.InitOpts(width="1500px", height="360px"))
    .add_xaxis(xaxis_data=data.index.tolist())
    .add_yaxis(
        series_name="百分比%",
        y_axis=data['基差序列'].tolist(),
        label_opts=opts.LabelOpts(is_show=False),
        linestyle_opts=opts.LineStyleOpts(width=1.5),
        is_smooth=True
    ) 
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="基差图",
            pos_left="center",
            pos_top="top",
        ),
        tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
        legend_opts=opts.LegendOpts(is_show=False),
        datazoom_opts=[
            opts.DataZoomOpts(range_start=0, range_end=100),
            opts.DataZoomOpts(type_="inside", range_start=0, range_end=100),
        ],
        xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False,position="top"),
        yaxis_opts=opts.AxisOpts(name="百分比%", type_="value",name_location = "start"),
    )
    #.render("基差图.html")
)

# (
#     Grid(init_opts=opts.InitOpts(width="1520px", height="700px"))
#     .add(chart=l1, grid_opts=opts.GridOpts(pos_left=50, pos_right=50, height="35%"))
#     .add(chart=l2,grid_opts=opts.GridOpts(pos_left=50, pos_right=50, pos_top="55%", height="35%"),
#     )
#     .render("监控图.html")
# )
page = Page(layout=Page.SimplePageLayout)
page.add(l1,l2)
page.render("监控图.html")
import webbrowser
webbrowser.open_new_tab('监控图.html')

标签:Tushare,基差,中证,df,CFE,value,import,data,opts
来源: https://blog.csdn.net/m0_60243445/article/details/121034881