掘金中没有直接获取期货加权指数的接口,怎样才能用原始数据合成出加权指数?
加权指数的计算原理就是将该品种每一天所有上市且未退市的合约按照当日持仓量作为权重加权求得,共包括:开盘价、收盘价、最高价和最低价。
对应接口:get_instruments()
对应接口:get_history_instruments()
对应接口:history()
# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *
import datetime
import pandas as pd
import numpy as np
# 加权指数(按照持仓量加权):回测模式
def init(context):
# 定义合约品种
context.symbol = 'DCE.y'
# 获取所有连续合约
all_contract = get_instruments(exchanges='DCE', df=True)
# 按照symbol将DCE.y选出来
context.data = all_contract[(all_contract['symbol'].str.contains(context.symbol))]
# 用来储存加权指数的变量
context.index = []
# 目标合约代码
context.all_symbols = []
# 目标合约持仓量
context.all_position = []
# 合约价格变量
context.high = []
context.low = []
context.close = []
context.open = []
# 设置定时任务,每天计算一次加权指数
schedule(schedule_func=algo, date_rule='1d', time_rule='10:00:00')
def algo(context):
data = context.data
now = context.now.date()
# 清空所有变量
context.all_symbols = []
context.all_position = []
context.high = []
context.low = []
context.close = []
context.open = []
# 遍历所有的合约
for i in range(len(data)):
symbol = data['symbol'].iloc[i]
listed_date = data['listed_date'].iloc[i].date()
delisted_date = data['delisted_date'].iloc[i].date()
# 如果当前日期正好是交易日,则存入待计算列表
if delisted_date > now and listed_date < now:
# 获取持仓量、收盘价等信息
instruments = get_history_instruments(symbols=symbol, fields='symbol,position',
start_date=context.now, end_date=context.now, df=True)
history_data = history(symbol=symbol, frequency='1d', start_time=now, end_time=now,
fields='open, close, low, high', adjust=ADJUST_PREV, df=True)
# 判断是否有数据
if len(history_data) != 0:
position = instruments['position'].iloc[0]
high = history_data['high'].iloc[0]
low = history_data['low'].iloc[0]
open = history_data['open'].iloc[0]
close = history_data['close'].iloc[0]
# 存入list
context.all_symbols.append(symbol)
context.all_position.append(position)
context.high.append(high)
context.low.append(low)
context.open.append(open)
context.close.append(close)
# 按照持仓量加权
if len(context.all_symbols) != 0:
weighted_open = sum((context.open[i] * context.all_position[i]) / sum(context.all_position) for i in
range(len(context.all_symbols)))
weighted_close = sum((context.close[i] * context.all_position[i]) / sum(context.all_position) for i in
range(len(context.all_symbols)))
weighted_high = sum((context.high[i] * context.all_position[i]) / sum(context.all_position) for i in
range(len(context.all_symbols)))
weighted_low = sum((context.low[i] * context.all_position[i]) / sum(context.all_position) for i in
range(len(context.all_symbols)))
index_list = [now, weighted_open, weighted_high, weighted_low, weighted_close]
context.index.append(index_list)
# 回测期结束,输出
if str(now) == context.backtest_end_time.split(' ')[0]:
context.index = pd.DataFrame(context.index,columns=['date', 'open', 'high', 'low', 'close'])
print(context.index)
if __name__ == '__main__':
run(strategy_id='f8167c80-255f-11eb-bf97-00ff7d998fe4',
filename='main.py',
mode=MODE_BACKTEST,
token='27e97bc5316b5fb321fa1b25c76c6ff276f2798a',
backtest_start_time='2020-11-10 08:00:00',
backtest_end_time='2020-11-13 15:00:00',
backtest_adjust=ADJUST_PREV,
backtest_initial_cash=10000000,
backtest_commission_ratio=0.0001,
backtest_slippage_ratio=0.0001
)
来源:掘金量化社区 作者:四两 原文链接:https://bbs.myquant.cn/topic/2057