三个主要步骤
1、导入模块
2、从wind自动获取螺纹钢主力合约价格和现货价格
3、计算螺纹钢基差
4、图形展示
@author: zhanglei
"""
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
from WindPy import w
w.start();
nowtime=datetime.now()
towindtime_1=nowtime.strftime('%Y-%m-%d')
to_wind_time=str(towindtime_1)
print('今天的日期是:',to_wind_time)
print('\n')
rb_futures_1=w.edb("M0067416","2009-03-27", to_wind_time,"Fill=Previous")
datefu=pd.to_datetime(rb_futures_1.Times)
rb_futures=pd.DataFrame({"datefu":datefu,"rbfutures":rb_futures_1.Data[0]})
rb_futures=rb_futures.set_index('datefu')
#从wind中读取期货主力合约价格,并转化为dataframe格式,设定日期为索引
#print(rb_futures)
rb_spot_1=w.edb("S0033227","2009-03-27", to_wind_time,"Fill=Previous")
#从wind中读取螺纹钢现货
datesp=pd.to_datetime(rb_spot_1.Times)
rb_spot=pd.DataFrame({"datesp":datesp,"rbspot":rb_spot_1.Data[0]})
rb_spot=rb_spot.set_index('datesp')
#把现货价格转化为dataframe格式,并设定日期为索引
rb_spot=rb_spot.reindex(datefu)
#把期货价格日期设定为现货价格的索引
#print (rb_spot)
rb_spot=rb_spot.fillna(method='ffill')
#填充现货价格的索引值
rbbasis=pd.DataFrame()
rbbasis['basis']=(rb_spot['rbspot'])/0.97-rb_futures['rbfutures']
rbbasis['spot']=rb_spot['rbspot']
rbbasis['futures']=rb_futures['rbfutures']
#print(rbbasis)
lastdate=max(rbbasis.index)
lastrbbasis=rbbasis.basis[lastdate]
print(lastdate.strftime('%Y-%m-%d')," 螺纹钢主力合约基差为:",'%.2f'%lastrbbasis)
#折线图
plt.plot(rbbasis.basis)
label=['rb-basis']
plt.legend(label,loc='best')
plt.ylabel("yuan/ton")
#plt.xlabel("date")
plt.title("RB MAIN CONTRACT BASIS")
plt.show()
#直方图
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(rbbasis['basis'], bins=50)
plt.title('RB basis distribution')
plt.xlabel('rb basis')
plt.ylabel('frequency')
plt.show()
运行结果
今天的日期是: 2018-10-15
2018-10-12 螺纹钢主力合约基差为: 625.96


d:\python\lib\site-packages\spyder\widgets\variableexplorer\utils.py:414: FutureWarning: 'summary' is deprecated and will be removed in a future version.
display = value.summary()
领取专属 10元无门槛券
私享最新 技术干货