老师好:
我编了段代码,玉米期货日内交易,即以开盘后30分钟的最高价和最低价为依据,突破最高价开仓买入;当价格小于最高价-(最高价-最低价)/3时止损;当时间到15.00时平仓。代码可以得出当天的收益率,**请教怎么计算一段日期的累计收益率?**代码如下:
# 导入函数库
from jqdata import *
pd.set_option('display.max_columns', None)#显示所有列
## 初始化函数,设定基准等等
def initialize(context):
# 设定沪深300作为基准
set_benchmark('000300.XSHG')
# 开启动态复权模式(真实价格)
set_option('use_real_price', True)
# 过滤掉order系列API产生的比error级别低的log
# log.set_level('order', 'error')
# 输出内容到日志 log.info()
log.info('初始函数开始运行且全局只运行一次')
g.security = 'C9999.XDCE' #玉米合约
# 开盘时运行
run_daily(market_open, time='every_bar', reference_security='000300.XSHG')
# 开盘时运行函数
def market_open(context):
log.info('函数运行时间(market_open):'+str(context.current_dt.time()))
security = g.security
date1=(context.current_dt)#每天开盘时间
date2=(context.current_dt+datetime.timedelta(minutes=30))#开盘后30分钟时间
date3=(context.current_dt+datetime.timedelta(minutes=320))#收盘前10分钟时间
#获取开盘后30分钟的最高H和最低价L
df=get_price(security, start_date=date1, end_date=date2, frequency='10m', fields=['high', 'low'], fq='pre')
print(df)
H=df['high'].max()
L=df['low'].min()
print(H)
print(L)
#获取每天数据(1分钟周期的'high', 'low','close')
df1=get_price(security, start_date=context.current_dt, end_date=(context.current_dt+datetime.timedelta(minutes=330)), frequency='1m', fields=['high', 'low','close'], fq='pre')
df1[ 'open1_signal']=0
df1['close1_signal']=0
df1['colse2_signal']=0
for i in range(len(df1)):
a=df1.index[i]
if date2<a<=date3:
if df1.loc[a,'close']>H:
df1.ix[i, 'open1_signal'] = 1 # 买入开仓信号
elif df1.loc[a,'close']<(H-(H-L)/3):
df1.ix[i, 'close1_signal'] = -1 #卖出平仓信号
elif a==(context.current_dt+datetime.timedelta(minutes=330)):
df1.ix[i, 'colse2_signal'] = -1 #卖出平仓信号
df1['close_signal']=df1['close1_signal']+df1['colse2_signal']
df1['signal']=df1[ 'open1_signal']+df1[ 'close_signal']
#数据清洗,去除['signal']中重复的1,-1
df1.drop_duplicates(subset=['signal'], keep='first', inplace=True)
#-1先于1,属无效信号,将其转换成
df1['signal'] = np.where((df1['signal'] == -1)
& (df1['signal'].shift(-1) == 1), 0, df1['signal'])
#数据清洗,去除['signal']中有0的行
df1 = df1.loc[df1['signal'] * df1['high'] != 0]
#计算当次收益率
df1['profit-pct']=(df1['close']-df1['close'].shift(1))/df1['close'].shift(1)
df1=df1[df1['signal']==-1]
#计算累计收益率(这里只能计算当天的累计收益率)
df1['cum_profit'] = pd.DataFrame(1 + df1['profit-pct']).cumprod() - 1
print(df1)