Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Installazione librerie backtrade e matplotlib
- !pip install backtrader
- !pip install matplotlib==3.2.2
- # Definizione strategia
- import backtrader as bt
- import datetime
- from backtrader import CommInfoBase
- class GapAzionario(bt.Strategy):
- params = (
- ('gapPerc', 1),
- ('atrPeriodo', 3),
- ('riskPerTrade', 1),
- ('takeProfitMult', 1.5),
- ('longActive', True),
- ('shortActive', True),
- )
- def __init__(self):
- self.atr = bt.ind.ATR(period=self.params.atrPeriodo)
- self.openPrice = self.datas[0].open
- self.highPrice = self.datas[0].high
- self.lowPrice = self.datas[0].low
- self.closePrice = self.datas[0].close
- # Calcolo % della distanza tra apertura attuale e chiusura precedente passati in input
- def gapPercentuale(self, apertura, chiusura):
- return (abs(apertura - chiusura) / chiusura) * 100
- # Ritorna Vero se la candela è bullish (prezzo di chiusura > prezzo apertura), falso altrimenti
- def isCandelaVerde(self, apertura, chiusura):
- return True if chiusura > apertura else False
- def next(self):
- gap = self.gapPercentuale(self.openPrice, self.closePrice[-1])
- if (gap >= self.params.gapPerc) and self.data.datetime.time() == datetime.time(14, 30):
- if not self.isCandelaVerde(self.openPrice[-1], self.closePrice[-1]) and self.isCandelaVerde(self.openPrice, self.closePrice) and self.position.size == 0 and self.params.longActive:
- stopLoss = self.lowPrice - self.atr
- volume = (self.broker.getvalue() * (self.params.riskPerTrade / 100)) / (self.closePrice - stopLoss)
- self.buy_bracket(size=volume, stopprice=stopLoss,
- limitprice=(self.closePrice + ((self.closePrice - stopLoss) * self.params.takeProfitMult)),
- exectype=bt.Order.Market)
- elif self.isCandelaVerde(self.openPrice[-1], self.closePrice[-1]) and not self.isCandelaVerde(self.openPrice, self.closePrice) and self.position.size == 0 and self.params.shortActive:
- stopLoss = self.highPrice + self.atr
- volume = (self.broker.getvalue() * (self.params.riskPerTrade / 100)) / (stopLoss - self.closePrice)
- self.sell_bracket(size=volume, stopprice=stopLoss,
- limitprice=(self.closePrice - ((stopLoss - self.closePrice) * self.params.takeProfitMult)),
- exectype=bt.Order.Market)
- # Motore backtest (capitale, parametri, data feed...)
- initCapital = 10000
- cerebro = bt.Cerebro()
- cerebro.broker.setcommission(commission=0.05, commtype=CommInfoBase.COMM_FIXED)
- data = bt.feeds.GenericCSVData(
- dataname='STOCK_US_AAPL_30m_20100101_20211001.csv',
- timeframe=bt.TimeFrame.Minutes,
- compression=30,
- fromdate=datetime.datetime(2017, 1, 1),
- todate=datetime.datetime(2021, 10, 1),
- dtformat=('%Y%m%d'),
- tmformat=('%H%M'),
- date=0,
- time=1,
- open=2,
- high=3,
- low=4,
- close=5,
- volume=6,
- openinterest=-1
- )
- # Add the data to Cerebro
- cerebro.adddata(data)
- # Set our desired cash start
- cerebro.broker.setcash(initCapital)
- cerebro.addanalyzer(bt.analyzers.DrawDown, _name="drawdown")
- cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="trade")
- cerebro.addanalyzer(bt.analyzers.TimeReturn, _name="timereturn")
- # Run over everything
- cerebro.addstrategy(GapAzionario)
- result = cerebro.run()
- # Plotting
- cerebro.plot(style="candlestick", volume=False)
- # Statistiche personalizzate
- finalCapital = initCapital + result[0].analyzers.trade.get_analysis()['pnl']['net']['total']
- print("+++++++++++++++++++++++++++++++++++++++++++++++++++++")
- print("+++++++++++++++++++++ Backtest ++++++++++++++++++++++")
- print("+++++++++++++++++++++++++++++++++++++++++++++++++++++")
- print("")
- print("Ordini Totali..........: {}".format(result[0].analyzers.trade.get_analysis()['total']['total']))
- print("Ordini Streak vinti....: {}".format(result[0].analyzers.trade.get_analysis()['streak']['won']['current']))
- print("Ordini Streak persi....: {}".format(result[0].analyzers.trade.get_analysis()['streak']['lost']['current']))
- print("Profit Factor..........: {}".format(
- abs(result[0].analyzers.trade.get_analysis()['won']['pnl']['total']) / abs(
- result[0].analyzers.trade.get_analysis()['lost']['pnl']['total'])))
- print("Drawdown Max %.........: {}".format(result[0].analyzers.drawdown.get_analysis()['max']['drawdown']))
- print("Capitale finale........: {}".format(finalCapital))
- print("Profitto %.............: {}".format(((finalCapital - initCapital) / initCapital) * 100))
- print("PNL lorda..............: {}".format(result[0].analyzers.trade.get_analysis()['pnl']['gross']['total']))
- print("PNL netta..............: {}".format(result[0].analyzers.trade.get_analysis()['pnl']['net']['total']))
- print("---------------- Vincite -------------")
- print("Trade totali...........: {}".format(result[0].analyzers.trade.get_analysis()['won']['total']))
- print("Trade PNL totale.......: {}".format(result[0].analyzers.trade.get_analysis()['won']['pnl']['total']))
- print("Trade PNL medio........: {}".format(result[0].analyzers.trade.get_analysis()['won']['pnl']['average']))
- print("Trade PNL massimo......: {}".format(result[0].analyzers.trade.get_analysis()['won']['pnl']['max']))
- print("---------------- Perdite -------------")
- print("Trade totali...........: {}".format(result[0].analyzers.trade.get_analysis()['lost']['total']))
- print("Trade PNL totale.......: {}".format(result[0].analyzers.trade.get_analysis()['lost']['pnl']['total']))
- print("Trade PNL medio........: {}".format(result[0].analyzers.trade.get_analysis()['lost']['pnl']['average']))
- print("Trade PNL massimo......: {}".format(result[0].analyzers.trade.get_analysis()['lost']['pnl']['max']))
- print("----------------- Long ---------------")
- print("Trade totali...........: {}".format(result[0].analyzers.trade.get_analysis()['long']['total']))
- print("Trade vinti............: {}".format(result[0].analyzers.trade.get_analysis()['long']['won']))
- print("Trade persi............: {}".format(result[0].analyzers.trade.get_analysis()['long']['lost']))
- print("Win/Loss Ratio.........: {}".format(
- result[0].analyzers.trade.get_analysis()['long']['won'] / result[0].analyzers.trade.get_analysis()['long'][
- 'total']))
- print("Trade PNL totale.......: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['total']))
- print("Trade PNL Medio........: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['average']))
- print("Trade Vincite Totali...: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['won']['total']))
- print(
- "Trade Vincita Media....: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['won']['average']))
- print("Trade Vincita Massima..: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['won']['max']))
- print(
- "Trade Perdita Totali...: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['lost']['total']))
- print("Trade Perdita Media....: {}".format(
- result[0].analyzers.trade.get_analysis()['long']['pnl']['lost']['average']))
- print("Trade Perdita Massima..: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['lost']['max']))
- print("----------------- Short ---------------")
- print("Trade totali...........: {}".format(result[0].analyzers.trade.get_analysis()['short']['total']))
- print("Trade vinti............: {}".format(result[0].analyzers.trade.get_analysis()['short']['won']))
- print("Trade persi............: {}".format(result[0].analyzers.trade.get_analysis()['short']['lost']))
- print("Win/Loss Ratio.........: {}".format(
- result[0].analyzers.trade.get_analysis()['short']['won'] / result[0].analyzers.trade.get_analysis()['short'][
- 'total']))
- print("Trade PNL totale.......: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['total']))
- print("Trade PNL Medio........: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['average']))
- print(
- "Trade Vincite Totali...: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['won']['total']))
- print("Trade Vincita Media....: {}".format(
- result[0].analyzers.trade.get_analysis()['short']['pnl']['won']['average']))
- print("Trade Vincita Massima..: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['won']['max']))
- print(
- "Trade Perdita Totali...: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['lost']['total']))
- print("Trade Perdita Media....: {}".format(
- result[0].analyzers.trade.get_analysis()['short']['pnl']['lost']['average']))
- print("Trade Perdita Massima..: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['lost']['max']))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement