还在学习python中,这次用api提取数据并进行简单的策略回测,代码还在优化中。。。
from huobi.client.generic import *
from huobi.client.market import *
from huobi.constant.definition import *
# 取数据
market_client = MarketClient()
# 三倍做多
list_obj_l = market_client.get_candlestick("eth3lusdt", CandlestickInterval.MIN1, 2000)
# 三倍做空
list_obj_s = market_client.get_candlestick("eth3susdt", CandlestickInterval.MIN1, 2000)
list_close_eth3l = []
list_close_eth3s = []
for i in range(len(list_obj_l)) :
l = list_obj_l[i].close
s = list_obj_s[i].close
list_close_eth3l.append(l)
list_close_eth3s.append(s)
# print(list_close_eth3l)
# print(list_close_eth3s)
import pandas as pd
# 设置参数
trade_rate = 2.5 / 1000 # 千分之2.5的交易费用远高于市场平均水平
momentum = 1 # 计算多少天的涨跌幅
df = pd.DataFrame({'eth3l': list_close_eth3l,'eth3s': list_close_eth3s})
# 计算N日的涨跌幅momentum
df['mom_eth3l'] = df['eth3l'].pct_change(periods=momentum)
df['mom_eth3s'] = df['eth3s'].pct_change(periods=momentum)
# 轮动条件
df.loc[df['mom_eth3l'] > df['mom_eth3s'], 'style'] = 'eth3l'
df.loc[df['mom_eth3l'] < df['mom_eth3s'], 'style'] = 'eth3s'
df.loc[(df['mom_eth3l'] < 0.003) & (df['mom_eth3s'] < 0.003), 'style'] = 'empty'
# 相等时维持原来的仓位。
df['style'].fillna(method='ffill', inplace=True)
# 收盘才能确定风格,实际的持仓pos要晚一天。
df['pos'] = df['style'].shift(1)
# 删除持仓为nan的天数
df.dropna(subset=['pos'], inplace=True)
# 计算策略的整体涨跌幅strategy_pct
df.loc[df['pos'] == 'eth3l', 'strategy_pct'] = df['mom_eth3l']
df.loc[df['pos'] == 'eth3s', 'strategy_pct'] = df['mom_eth3l']
df.loc[df['pos'] == 'empty', 'strategy_pct'] = 0
df['strategy_net'] = (1 + df['strategy_pct']).cumprod()
print(df.tail(10))
df.to_csv('数字货币轮动_改进.csv', encoding='gbk', index=False)
print(df)