Backtrader: Working with Heikin Ashi
import backtrader as bt
from datetime import datetime
import math
import argparse
import requests
import json
import time
import math
from datetime import datetime
import pandas as pd
def get_polonix() :
time_depth = 500
start_day = 500
st_time=time.time()-start_day*24*60*60
end_time=st_time+time_depth*60*60*24
pair = 'USDT_BTC'
#resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=1800" % (pair,st_time,end_time))
resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=14400" % (pair,st_time,end_time))
#resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=300" % (pair,st_time,end_time))
#resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=86400" % (pair,st_time,end_time))
#resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=21600" % (pair,st_time,end_time))
data=[]
chart_data={}
chart_data = json.loads(resource.text)
for elems in chart_data:
data.append(elems)
df = pd.DataFrame(data, columns=['date', 'open', 'high', 'low', 'close', 'volume'])
df['openinterest']=0
df['date'] = pd.to_datetime(df['date'], unit='s')
#df = df[(df['date'] > '2018-1-1') & (df['date'] <= '2018-2-1')]
#df = df[(df['date'] > '2017-9-1') & (df['date'] <= '2018-1-1')]
df = df[(df['date'] >= '2018-4-1')]
df = df.set_index('date')
#print(df)
return df
def parse_args():
parser = argparse.ArgumentParser(description='Ngyuen: Price/Volume Anomaly Detection Strategy')
parser.add_argument('--debug',
action ='store_true',
help=('Print Debugs'))
return parser.parse_args()
class HeikinStrategy(bt.Strategy):
params = (('debug', False),)
def __init__(self):
# Set some pointers / references
for i, d in enumerate(self.datas):
if d._name == 'Real':
self.real = d
elif d._name == 'Heikin':
self.hk = d
def next(self):
pos = self.getposition(self.real).size
if not pos:
if self.hk.close[0] > self.hk.open[0]: # Green Heikin
self.buy(self.real, size=100)
elif self.hk.close[0] < self.hk.open[0]: #Red Heikin
self.sell(self.real, size=100)
else:
pass # Closed neutral
else:
if pos > 0 and self.hk.close[0] < self.hk.open[0]: # Red Heikin
self.sell(self.real, size=200) # Reverse Position
elif pos < 0 and self.hk.close[0] > self.hk.open[0]: # Green Heikin
self.buy(self.real, size=200) # Reverse Position
else:
pass
if self.p.debug:
print('---------------------------- NEXT ----------------------------------')
print("1: Data Name: {}".format(data._name))
print("2: Bar Num: {}".format(len(data)))
print("3: Current date: {}".format(data.datetime.datetime()))
print('4: Open: {}'.format(data.open[0]))
print('5: High: {}'.format(data.high[0]))
print('6: Low: {}'.format(data.low[0]))
print('7: Close: {}'.format(data.close[0]))
print('8: Volume: {}'.format(data.volume[0]))
print('--------------------------------------------------------------------')
def notify_trade(self,trade):
if trade.isclosed:
dt = self.data.datetime.date()
print('---------------------------- TRADE ---------------------------------')
print("1: Data Name: {}".format(trade.data._name))
print("2: Bar Num: {}".format(len(trade.data)))
print("3: Current date: {}".format(dt))
print('4: Status: Trade Complete')
print('5: Ref: {}'.format(trade.ref))
print('6: PnL: {}'.format(round(trade.pnl,2)))
print('--------------------------------------------------------------------')
args = parse_args()
#Variable for our starting cash
startcash = 1000000
#Create an instance of cerebro
cerebro = bt.Cerebro()
#Add our strategy
cerebro.addstrategy(HeikinStrategy, debug=args.debug)
df = get_polonix()
data = bt.feeds.PandasData(dataname=df)
dataHK = bt.feeds.PandasData(dataname=df)
#data = bt.feeds.Quandl(
#dataname='F',
#fromdate = datetime(2016,1,1),
#todate = datetime(2017,1,1),
#buffered= True
#)
#dataHK = bt.feeds.Quandl(
#dataname='F',
#fromdate = datetime(2016,1,1),
#todate = datetime(2017,1,1),
#buffered= True
#)
#Add the filter
dataHK.addfilter(bt.filters.HeikinAshi(dataHK))
#Add the data to Cerebro
cerebro.adddata(data, name="Real")
cerebro.adddata(dataHK, name="Heikin")
# Set our desired cash start
cerebro.broker.setcash(startcash)
# Run over everything
cerebro.run()
#Get final portfolio Value
portvalue = cerebro.broker.getvalue()
pnl = portvalue - startcash
#Print out the final result
print('Final Portfolio Value: ${}'.format(round(portvalue,2)))
print('P/L: ${}'.format(round(pnl,2)))
#Finally plot the end results
cerebro.plot(style='candlestick')
import backtrader as bt
from datetime import datetime
import math
import argparse
import requests
import json
import time
import math
from datetime import datetime
import pandas as pd
def get_polonix() :
time_depth = 500
start_day = 500
st_time=time.time()-start_day*24*60*60
end_time=st_time+time_depth*60*60*24
pair = 'USDT_BTC'
#resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=1800" % (pair,st_time,end_time))
resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=14400" % (pair,st_time,end_time))
#resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=300" % (pair,st_time,end_time))
#resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=86400" % (pair,st_time,end_time))
#resource=requests.get("https://poloniex.com/public?command=returnChartData¤cyPair=%s&start=%s&end=%s&period=21600" % (pair,st_time,end_time))
data=[]
chart_data={}
chart_data = json.loads(resource.text)
for elems in chart_data:
data.append(elems)
df = pd.DataFrame(data, columns=['date', 'open', 'high', 'low', 'close', 'volume'])
df['openinterest']=0
df['date'] = pd.to_datetime(df['date'], unit='s')
#df = df[(df['date'] > '2018-1-1') & (df['date'] <= '2018-2-1')]
#df = df[(df['date'] > '2017-9-1') & (df['date'] <= '2018-1-1')]
df = df[(df['date'] >= '2018-4-1')]
df = df.set_index('date')
#print(df)
return df
def parse_args():
parser = argparse.ArgumentParser(description='Ngyuen: Price/Volume Anomaly Detection Strategy')
parser.add_argument('--debug',
action ='store_true',
help=('Print Debugs'))
return parser.parse_args()
class HeikinStrategy(bt.Strategy):
params = (('debug', False),)
def __init__(self):
# Set some pointers / references
for i, d in enumerate(self.datas):
if d._name == 'Real':
self.real = d
elif d._name == 'Heikin':
self.hk = d
def next(self):
pos = self.getposition(self.real).size
if not pos:
if self.hk.close[0] > self.hk.open[0]: # Green Heikin
self.buy(self.real, size=100)
elif self.hk.close[0] < self.hk.open[0]: #Red Heikin
self.sell(self.real, size=100)
else:
pass # Closed neutral
else:
if pos > 0 and self.hk.close[0] < self.hk.open[0]: # Red Heikin
self.sell(self.real, size=200) # Reverse Position
elif pos < 0 and self.hk.close[0] > self.hk.open[0]: # Green Heikin
self.buy(self.real, size=200) # Reverse Position
else:
pass
if self.p.debug:
print('---------------------------- NEXT ----------------------------------')
print("1: Data Name: {}".format(data._name))
print("2: Bar Num: {}".format(len(data)))
print("3: Current date: {}".format(data.datetime.datetime()))
print('4: Open: {}'.format(data.open[0]))
print('5: High: {}'.format(data.high[0]))
print('6: Low: {}'.format(data.low[0]))
print('7: Close: {}'.format(data.close[0]))
print('8: Volume: {}'.format(data.volume[0]))
print('--------------------------------------------------------------------')
def notify_trade(self,trade):
if trade.isclosed:
dt = self.data.datetime.date()
print('---------------------------- TRADE ---------------------------------')
print("1: Data Name: {}".format(trade.data._name))
print("2: Bar Num: {}".format(len(trade.data)))
print("3: Current date: {}".format(dt))
print('4: Status: Trade Complete')
print('5: Ref: {}'.format(trade.ref))
print('6: PnL: {}'.format(round(trade.pnl,2)))
print('--------------------------------------------------------------------')
args = parse_args()
#Variable for our starting cash
startcash = 1000000
#Create an instance of cerebro
cerebro = bt.Cerebro()
#Add our strategy
cerebro.addstrategy(HeikinStrategy, debug=args.debug)
df = get_polonix()
data = bt.feeds.PandasData(dataname=df)
dataHK = bt.feeds.PandasData(dataname=df)
#data = bt.feeds.Quandl(
#dataname='F',
#fromdate = datetime(2016,1,1),
#todate = datetime(2017,1,1),
#buffered= True
#)
#dataHK = bt.feeds.Quandl(
#dataname='F',
#fromdate = datetime(2016,1,1),
#todate = datetime(2017,1,1),
#buffered= True
#)
#Add the filter
dataHK.addfilter(bt.filters.HeikinAshi(dataHK))
#Add the data to Cerebro
cerebro.adddata(data, name="Real")
cerebro.adddata(dataHK, name="Heikin")
# Set our desired cash start
cerebro.broker.setcash(startcash)
# Run over everything
cerebro.run()
#Get final portfolio Value
portvalue = cerebro.broker.getvalue()
pnl = portvalue - startcash
#Print out the final result
print('Final Portfolio Value: ${}'.format(round(portvalue,2)))
print('P/L: ${}'.format(round(pnl,2)))
#Finally plot the end results
cerebro.plot(style='candlestick')
Комментариев нет:
Отправить комментарий