量化学习——50指数对冲

#获取股票数据并进行策略收益组合
import akshare as ak
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plot
import talib    #计算均线的库,随便学一下,几分钟就懂
#获取50指数成分
index_stock_info_df = ak.index_stock_cons('000300')
stock_list = index_stock_info_df['品种代码']
star='20170117'
end="20230810"
last = pd.DataFrame()
last['trade_date'] = 0
last['strategy'] = 0
for i in stock_list:
    #print(i)
    try:
        df = ak.stock_zh_a_hist(symbol=i, period="daily", start_date=star, end_date=end, adjust="")
        df.rename(columns={"日期":'trade_date',"开盘":'open',"收盘":'close',"最高":'high',"最低":'low',"涨跌幅":'change'},inplace = True)
        df = df.sort_index()   #建立索引
        df['ma10'] = df['close'].rolling(20).mean()
        df['ma20'] = df['close'].rolling(60).mean()
        #计算股票收益,有两种计算收益率方法:1.离散收益率  2.连续收益率
        df['position'] = np.where(df['ma10'] > df['ma20'], 1, 0)  #当20日均线大于60日均线时记录1,反之记录-1
        df['returns'] = df['close']/df['close'].shift(1)-1  #连续收益率计算
        #data['returns_dis'] = data['close']/data['close'].shift(1) - 1  #离散收益率计算
        df['strategy'] = df['position'].shift(1)*df['returns']
        df['trade_date']=pd.to_datetime(df.trade_date,format="%Y-%m-%d")
        #print(df.head())
        #df['code'] = i
        #下面需将得到的收益ret序列变成按日期由低到高排列
        #cum=df['strategy']+cum#等权重配置一篮子股票,计算权重和
        last = pd.merge(df[['trade_date','strategy']],last,on='trade_date',how= 'left')
        #last = last.set_index('trade_date')
        #print(cum)
        #print(last)
    except:
        continue
#(cum/len(stock_list)).cumsum().apply(np.exp).plot(figsize=(10, 6))
last = last.set_index('trade_date')
last = last.fillna(0)
last['Row_sum'] = last.apply(lambda x: x.sum(), axis=1)/len(stock_list)
last = last.reset_index()
last
#获取股指期货数据
df3 = ak.futures_main_sina(symbol="IF0")
df3.rename(columns={"日期":'trade_date',"开盘价":'open',"收盘价":'close',"最高价":'high',"最低价":'low'},inplace = True)
df3.sort_index()
#df3.index=pd.to_datetime(df3.trade_date,format="%Y-%m-%d")
df3 = df3[(df3['trade_date']>=datetime.date(2017,1,17))&(df3['trade_date']<=datetime.date(2023,8,13))]
df3['returns'] = df3['close']/df3['close'].shift(1)-1  #连续收益率计算
#data['returns_dis'] = data['close']/data['close'].shift(1) - 1  #离散收益率计算
df3['returns'].cumsum()
df3.trade_date=pd.to_datetime(df3.trade_date,format="%Y-%m-%d")
df3
la = pd.merge(last,df3,on='trade_date')
plt.plot(la.Row_sum.cumsum()-la.returns.cumsum(),label="稳定的alph收益",color="y")
plt.plot(la.Row_sum.cumsum(),label="股票组合",color='r')
plt.plot(-la.returns.cumsum(),label="指数期货收益",color='g')
plt.title("alpha股+指期对冲策略")
plt.legend()
#做空沪深300股指期货
#df3 = pro.fut_daily(ts_code='IF2012.CFX', start_date='20200411', end_date='20200812')
df3 = ak.futures_main_sina(symbol="IF0")
df3.rename(columns={"日期":'trade_date',"开盘价":'open',"收盘价":'close',"最高价":'high',"最低价":'low'},inplace = True)
df3.sort_index()
#df3.index=pd.to_datetime(df3.trade_date,format="%Y-%m-%d")
df3 = df3[(df3['trade_date']>=datetime.date(2010,4,13))&(df3['trade_date']<=datetime.date(2023,8,13))]

ret13=df3.close/df3.close.shift(1)-1
sy=pd.Series(1,index=df3.close.index)
sy2=ret13*sy.shift(1).dropna()
cum13=sy2.cumsum()

cum13 = cum13[-len(cum)-1:]
cum13 = pd.Series(list(cum13))
cum13 = cum13.sort_index()
#cum13 = (cum13.fillna(method='ffill'))
cum13 = (cum13.fillna(0))
# f=cum[-2]*250/len(df3.close)-cum13[-2]*250/len(df3.close)
# f1=100*f#换成百分制
#plt.plot(cum12,label="沪深300",color='b')
plt.plot(cum-cum13,label="稳定的alph收益",color="y")
plt.plot(cum,label="股票组合",color='r')
plt.plot(-cum13,label="指数期货收益",color='g')
plt.title("alpha股+指期对冲策略")
plt.legend()
#print("alpha年化收益率:{:.2f}%".format(f1))

 

df3 = ak.futures_main_sina(symbol="IF0")
df3.rename(columns={"日期":'trade_date',"开盘价":'open',"收盘价":'close',"最高价":'high',"最低价":'low'},inplace = True)
df3.sort_index()
#df3.index=pd.to_datetime(df3.trade_date,format="%Y-%m-%d")
df3 = df3[(df3['trade_date']>=datetime.date(2017,1,17))&(df3['trade_date']<=datetime.date(2023,8,13))]
df3['returns'] = df3['close']/df3['close'].shift(1)-1  #连续收益率计算
#data['returns_dis'] = data['close']/data['close'].shift(1) - 1  #离散收益率计算
df3['returns'].cumsum()

last = last.reset_index()

#plt.plot((last['Row_sum']+1).cumprod()-df3['returns'].cumsum(),label="稳定的alph收益",color="y")
plt.plot((last['Row_sum']+1).cumprod(),label="股票组合",color='r')
plt.plot(-df3['returns'].cumsum(),label="指数期货收益",color='g')
plt.title("alpha股+指期对冲策略")
plt.legend()

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神出鬼没,指的就是我!

必须花钱,数据超好

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值