双指标sma+cci,回测长源电力

在这里插入图片描述

# -*- coding: utf-8 -*-
"""
Created on Mon Nov  8 16:04:38 2021

@author: ThinkPad
"""
import numpy as np
import pandas as pd
import talib as ta
import tushare as ts
import matplotlib  as mpl
import matplotlib.pyplot as plt
from pylab import*
import seaborn as sns
#%matplotlib inline
from IPython import get_ipython#获取数据
def get_from_tushare_pro(code,adj='hfq',start='2020-01-01',end='2021-11-07'):
    #code:输入数字字符串,如‘300002’
    #start和end输入'年-月-日'需转为'年月日'格式
    if code.startswith('6'):
        code=code+'.SH'
    else:
        code=code+'.SZ'
    start=''.join(start.split('-'))
    end=''.join(end.split('-'))
    df=ts.pro_bar(ts_code=code,adj=adj,start_date=start,end_date=end)
    #原数据是倒序的,所以将时间设置为索引,根据索引重新排序
    df.index=pd.to_datetime(df.trade_date)
    df=df.sort_index()
    return df

stock_index=get_from_tushare_pro('000966')
get_ipython().run_line_magic('matplotlib', 'inline')

matplotlib.rcParams['axes.unicode_minus']=False
mpl.rcParams['font.sans-serif']=['SimHei']
import datetime as dt
#token初始化
ts.set_token('token')
pro = ts.pro_api()
pro = ts.pro_api('token')

 #计算指标
stock_index['sma']=ta.SMA(np.asarray(stock_index['close']),5)
stock_index['cci']=ta.CCI(np.asarray(stock_index['high']),np.asarray(stock_index['low']),np.asarray(stock_index['close']),timeperiod=20)

plt.subplot(2, 1,1)
plt.title('长源电力   SMA +CCI 图')
plt.gca().axes.get_xaxis().set_visible(False)
stock_index['close'].plot(figsize=(10,8))
stock_index['sma'].plot(figsize=(10,8))
plt.legend()
plt.subplot(2, 1,2)
stock_index['cci'].plot(figsize=(10,8))
plt.legend()
plt.show()




#交易信号
stock_index['yes_close']=stock_index['close'].shift(1)
stock_index['yes_sma']=stock_index['sma'].shift(1)
stock_index['yes_cci']=stock_index['cci'].shift(1)
stock_index['daybeforeyes_close']=stock_index['close'].shift(2)
stock_index['daybeforeyes_sma']=stock_index['sma'].shift(2)
#产生交易信号
#sma开多信号,昨天股价上穿sma
stock_index['sma_signal']=np.where(np.logical_and( stock_index['daybeforeyes_close'] < stock_index['daybeforeyes_sma'],stock_index['yes_close']>stock_index['yes_sma']),1,0)
#sma开空信号,昨天股价下穿sma
stock_index['sma_signal']=np.where(np.logical_and(stock_index['daybeforeyes_close']>stock_index['daybeforeyes_sma'],stock_index['yes_close']<stock_index['yes_sma']),-1,stock_index['sma_signal'])
#产生cci做多过滤信号
stock_index['cci_filter']=np.where(stock_index['yes_cci']<-100,1,0)
#产生cci做空过滤信号
stock_index['cci_filter']=np.where(stock_index['yes_cci']>100,-1, stock_index['cci_filter'])
#过滤后的开多信号
stock_index['filtered_signal']=np.where(stock_index['sma_signal']+stock_index['cci_filter'] ==2,1,0)
#过滤后的开空信号
stock_index['filtered_signal']=np.where(stock_index['sma_signal']+stock_index['cci_filter'] ==-2,-1,stock_index['filtered_signal'])


 
plt.subplot(3, 1,1)
plt.title('长源电力 sma cci 交易信号图')
plt.gca().axes.get_xaxis().set_visible(False)
stock_index['close'].plot(figsize=(12,8))
stock_index['sma'].plot()
plt.legend(loc='upper left')
plt.subplot(3,1,2)
stock_index['cci'].plot(figsize=(12,8))
plt.legend(loc='upper left')
plt.subplot(3,1,3)
stock_index['filtered_signal'].plot(figsize=(12,8))
plt.plot(stock_index['filtered_signal'],marker='o',linestyle='')
plt.legend(loc='upper left')
plt.show()
#持仓信号

#使用position标记持仓情况
position=0
#对每个交易日进行循环
for item in stock_index.iterrows():
        #判断交易信号
        if item[1]['filtered_signal']==1:
            #交易信号为1,则记录仓位为1
            position =1
        elif item[1]['filtered_signal']==-1:
            #交易信号为-1,则记录仓位为-1
            position=-1
        else:
            pass
        #记录每日持仓情况
        stock_index.loc[item[0],'position']=position
 
 
  
plt.subplot(3, 1,1)
plt.title('长源电力 cci持仓图')
plt.gca().axes.get_xaxis().set_visible(False)

stock_index['close'].plot(figsize=(12,12))
plt.legend()

stock_index['sma'].plot()
plt.legend(loc='upper left')


plt.subplot(3,1,2)
stock_index['cci'].plot(figsize=(12,12 ))
plt.legend()
plt.gca().axes.get_xaxis().set_visible(False)

plt.subplot(3,1,3)
stock_index['position'].plot(figsize=(12,12))
plt.plot(stock_index['position'],marker='o',linestyle='')
plt.legend()
plt.show()
 #策略收益和数据可视化
 #计算股票每日收益率
stock_index['pct_change']=stock_index['close'].pct_change()
#计算策略每日收益率
stock_index['strategy_return']=stock_index['position']*stock_index['pct_change']
#计算股票累计收益率
stock_index['return']=(stock_index['pct_change']+1).cumprod()
#计算策略累计收益率
stock_index['cum _strategy_return']=(stock_index['strategy_return']+1).cumprod()
stock_index[['return','cum _strategy_return']].plot(figsize=(12,6))
plt.title(' 长源电力 收益曲线图')
plt.legend()
plt.show()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值