经过一段时间的测试,在第一版代码的基础上做了不少修改
第一版代码:
相对活力指数指标(RVI)指标ETH模拟量化交易https://mp.csdn.net/mp_blog/creation/editor/120299311https://mp.csdn.net/mp_blog/creation/editor/120299311
与第一版代码相比,修改内容如下:
指标个数的判断;买卖方法的调用;K线数据的请求
具体修改后的代码如下:
from huobi.client.generic import *
from huobi.client.market import *
from huobi.constant.definition import *
from huobi.client.account import *
from huobi.client.trade import *
from huobi.client.market import *
import pandas as pd
import datetime as dt
import time
import talib as ta
import backtrader as bt
import numpy as np
import mathclass RVI(bt.Indicator):lines = ('std','pos','neg','rvi')plotlines = dict(std=dict(_plotskip=True),pos=dict(_plotskip=True),neg=dict(_plotskip=True),rvi=dict(_plotskip=False))params = (('period', 20),)def __init__(self):self.lines.std = bt.talib.STDDEV(self.datas[0].close, timeperiod=8, nbdev=2.0)def next(self):if self.lines.std[0] > self.lines.std[-1]:self.lines.pos[0] = self.lines.std[0]else:self.lines.pos[0] = 0if self.lines.std[0] < self.lines.std[-1]:self.lines.neg[0] = self.lines.std[0]else:self.lines.neg[0] = 0pos_nan = np.nan_to_num(self.lines.pos.get(size=self.params.period))neg_nan = np.nan_to_num(self.lines.neg.get(size=self.params.period))Usum = math.fsum(pos_nan)Dsum = math.fsum(neg_nan)if (Usum + Dsum) == 0:self.lines.rvi[0] = 0returnself.lines.rvi[0] = 100 * Usum / (Usum+Dsum)class read_csv():def __init__(self):# time(时间),currency(币种),balance(余额),type(类型),symbol(交易对),amount(交易量),price(交易价格),order-id(订单ID)self.list_new = []#交易日期及时间now_time = dt.datetime.now().strftime('%F %T')self.list_new.append(now_time)def readcsv(self):self.date = pd.read_csv('交易模拟测试.csv',encoding='utf-8')try :# 取最后一行symbol数据date_old = self.date.iloc[-1,:]logger.info('取最后一行symbol数据')symbol_old = date_old['symbol']if date_old['symbol'] != 'usdt' :symbol_old = symbol_old.replace('usdt', '')amount_new = date_old['amount'] * 0.9965self.list_new.append(symbol_old)self.list_new.append(amount_new)except IndexError as err:spot = 1547906account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)balance_list = account_client.get_balance(spot)# 账户中交易币种信息及余额c_list = ['usdt', 'eth3s', 'eth3l']c_list_1 = []for i in balance_list:currency = i.__dict__if currency['currency'] in c_list:c_list_1.append(currency)date_1 = pd.DataFrame(c_list_1)date_1['balance'] = date_1['balance'].astype('float')trade_1 = date_1.loc[(date_1['type'] == 'trade') & (date_1['balance'] > 0.01)]trade_1.reset_index(drop=True, inplace=True)self.list_new.append(trade_1['currency'][0])self.list_new.append(trade_1['balance'][0])return self.list_new, self.dateclass huobi_Strategy(bt.Strategy):def __init__(self):self.rvi = RVI()def amount_result(self,num):# 取小数点后四位self.num = numnum_x, num_y = str(self.num).split('.')self.num = float(num_x + '.' + num_y[0:4])return self.numdef market_data(self):# 取得最新价格market_client = MarketClient(api_key=g_api_key, secret_key=g_secret_key)market_trade = market_client.get_market_trade('eth3lusdt')for i in market_trade:market_trade_1 = i.__dict__# order_min = round(5.5 / market_trade_1['price'], 4) # 最小订单数量为 5/价格self.price_1 = market_trade_1['price']return self.price_1def huobi_buy(self):if self.list_new[1] == 'usdt' :price_1 = huobi_Strategy.market_data(self)amount_1 = huobi_Strategy.amount_result(self,self.list_new[2] * price_1)self.list_new.append('buy')self.list_new.append('eth3l')self.list_new.append(amount_1)self.list_new.append(price_1)self.list_new.append('id')f = pd.DataFrame(self.list_new).Tf.columns = self.columnsdate = pd.concat([self.date,f])date.to_csv('交易模拟测试.csv',encoding='utf-8',index=False)def huobi_sell(self):if self.list_new[1] == 'eth3l' :price_1 = huobi_Strategy.market_data(self)amount_1 = huobi_Strategy.amount_result(self,self.list_new[2] / price_1)self.list_new.append('sell')self.list_new.append('usdt')self.list_new.append(amount_1)self.list_new.append(price_1)self.list_new.append('id')# csv最后增加一行f = pd.DataFrame(self.list_new).Tf.columns = self.columnsdate = pd.concat([self.date, f])date.to_csv('交易模拟测试.csv', encoding='utf-8', index=False)def next(self):up = 80down = 20self.order = 'keep'if self.rvi.rvi[-1] > up:if self.rvi.rvi[-2] < up and self.rvi.rvi[-3] < up:self.order = 'buy'elif self.rvi.rvi[-1] < down:if self.rvi.rvi[-2] > down and self.rvi.rvi[-3] > down:self.order = 'sell'returndef stop(self):if self.order == 'buy':self.list_new, self.date = read_csv().readcsv()huobi_Strategy.huobi_buy(self)elif self.order == 'sell':self.list_new, self.date = read_csv().readcsv()huobi_Strategy.huobi_sell(self)def get_data():# 取当前及30min前的烛台数据market_client = MarketClient()data_ethusdt = market_client.get_candlestick('ethusdt', CandlestickInterval.MIN5, 100)id_1 = []high_1 = []low_1 = []open_1 = []close_1 = []vol_1 = []for i in range(len(data_ethusdt) - 1, -1, -1):id_1 = data_ethusdt[i].idhigh_1.append(data_ethusdt[i].high)low_1.append(data_ethusdt[i].low)open_1.append(data_ethusdt[i].open)close_1.append(data_ethusdt[i].close)# amount = data_ethusdt[i].amount# count = data_ethusdt[i].countvol_1.append(data_ethusdt[i].vol)datas = pd.DataFrame({'datetime': id_1, 'open': open_1,'high': high_1, 'low': low_1,'close': close_1, 'volume': vol_1})datas['datetime'] = pd.to_datetime(datas['datetime'], unit='s')datas.set_index('datetime', drop=True, append=False)return datas'''
程序结束
'''
# 程序执行:
if __name__ == '__main__':while True :time_start = time.perf_counter()logger.info('-'*5 + 'start' + '-'*5)# 策略加载df = get_data()cerebro = bt.Cerebro()data = bt.feeds.PandasData(dataname=df,datetime='datetime',open='open',high='high',low='low',close='close',volume='volume',openinterest=-1)cerebro.adddata(data)cerebro.addstrategy(huobi_Strategy)result = cerebro.run()# 统计运行时间time_used = time.perf_counter() - time_starttime.sleep(300)
有兴趣的朋友可以相互讨论