Advertisement
Maurizio-Ciullo

Strategia Completa GAP Azionario - Esempio Backtest AAPL Dotto

Oct 5th, 2021 (edited)
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.02 KB | None | 0 0
  1. # Installazione librerie backtrade e matplotlib
  2.  
  3. !pip install backtrader
  4. !pip install matplotlib==3.2.2
  5.  
  6. # Definizione strategia
  7.  
  8. import backtrader as bt
  9. import datetime
  10. from backtrader import CommInfoBase
  11.  
  12.  
  13. class GapAzionario(bt.Strategy):
  14.    
  15.     params = (
  16.         ('gapPerc', 1),
  17.         ('atrPeriodo', 3),
  18.         ('riskPerTrade', 1),
  19.         ('takeProfitMult', 1.5),
  20.         ('longActive', True),
  21.         ('shortActive', True),
  22.     )
  23.  
  24.     def __init__(self):
  25.         self.atr = bt.ind.ATR(period=self.params.atrPeriodo)
  26.         self.openPrice = self.datas[0].open
  27.         self.highPrice = self.datas[0].high
  28.         self.lowPrice = self.datas[0].low
  29.         self.closePrice = self.datas[0].close
  30.  
  31.     # Calcolo % della distanza tra apertura attuale e chiusura precedente passati in input
  32.     def gapPercentuale(self, apertura, chiusura):
  33.         return (abs(apertura - chiusura) / chiusura) * 100
  34.  
  35.     # Ritorna Vero se la candela รจ bullish (prezzo di chiusura > prezzo apertura), falso altrimenti
  36.     def isCandelaVerde(self, apertura, chiusura):
  37.         return True if chiusura > apertura else False
  38.  
  39.     def next(self):
  40.         gap = self.gapPercentuale(self.openPrice, self.closePrice[-1])
  41.  
  42.         if (gap >= self.params.gapPerc) and self.data.datetime.time() == datetime.time(14, 30):
  43.  
  44.             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:
  45.  
  46.                 stopLoss = self.lowPrice - self.atr
  47.                 volume = (self.broker.getvalue() * (self.params.riskPerTrade / 100)) / (self.closePrice - stopLoss)
  48.                 self.buy_bracket(size=volume, stopprice=stopLoss,
  49.                                  limitprice=(self.closePrice + ((self.closePrice - stopLoss) * self.params.takeProfitMult)),
  50.                                  exectype=bt.Order.Market)
  51.  
  52.             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:
  53.                
  54.                 stopLoss = self.highPrice + self.atr
  55.                 volume = (self.broker.getvalue() * (self.params.riskPerTrade / 100)) / (stopLoss - self.closePrice)
  56.                 self.sell_bracket(size=volume, stopprice=stopLoss,
  57.                                   limitprice=(self.closePrice - ((stopLoss - self.closePrice) * self.params.takeProfitMult)),
  58.                                   exectype=bt.Order.Market)
  59.  
  60. # Motore backtest (capitale, parametri, data feed...)
  61.  
  62. initCapital = 10000
  63. cerebro = bt.Cerebro()
  64.  
  65. cerebro.broker.setcommission(commission=0.05, commtype=CommInfoBase.COMM_FIXED)
  66.  
  67. data = bt.feeds.GenericCSVData(
  68.     dataname='STOCK_US_AAPL_30m_20100101_20211001.csv',
  69.     timeframe=bt.TimeFrame.Minutes,
  70.     compression=30,
  71.     fromdate=datetime.datetime(2017, 1, 1),
  72.     todate=datetime.datetime(2021, 10, 1),
  73.     dtformat=('%Y%m%d'),
  74.     tmformat=('%H%M'),
  75.     date=0,
  76.     time=1,
  77.     open=2,
  78.     high=3,
  79.     low=4,
  80.     close=5,
  81.     volume=6,
  82.     openinterest=-1
  83. )
  84. # Add the data to Cerebro
  85. cerebro.adddata(data)
  86. # Set our desired cash start
  87. cerebro.broker.setcash(initCapital)
  88.  
  89. cerebro.addanalyzer(bt.analyzers.DrawDown, _name="drawdown")
  90. cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="trade")
  91. cerebro.addanalyzer(bt.analyzers.TimeReturn, _name="timereturn")
  92.  
  93. # Run over everything
  94.  
  95. cerebro.addstrategy(GapAzionario)
  96.  
  97. result = cerebro.run()
  98.  
  99. # Plotting
  100.  
  101. cerebro.plot(style="candlestick", volume=False)
  102.  
  103. # Statistiche personalizzate
  104.  
  105. finalCapital = initCapital + result[0].analyzers.trade.get_analysis()['pnl']['net']['total']
  106.  
  107.     print("+++++++++++++++++++++++++++++++++++++++++++++++++++++")
  108.     print("+++++++++++++++++++++ Backtest ++++++++++++++++++++++")
  109.     print("+++++++++++++++++++++++++++++++++++++++++++++++++++++")
  110.     print("")
  111.     print("Ordini Totali..........: {}".format(result[0].analyzers.trade.get_analysis()['total']['total']))
  112.     print("Ordini Streak vinti....: {}".format(result[0].analyzers.trade.get_analysis()['streak']['won']['current']))
  113.     print("Ordini Streak persi....: {}".format(result[0].analyzers.trade.get_analysis()['streak']['lost']['current']))
  114.     print("Profit Factor..........: {}".format(
  115.         abs(result[0].analyzers.trade.get_analysis()['won']['pnl']['total']) / abs(
  116.             result[0].analyzers.trade.get_analysis()['lost']['pnl']['total'])))
  117.     print("Drawdown Max %.........: {}".format(result[0].analyzers.drawdown.get_analysis()['max']['drawdown']))
  118.     print("Capitale finale........: {}".format(finalCapital))
  119.     print("Profitto %.............: {}".format(((finalCapital - initCapital) / initCapital) * 100))
  120.     print("PNL lorda..............: {}".format(result[0].analyzers.trade.get_analysis()['pnl']['gross']['total']))
  121.     print("PNL netta..............: {}".format(result[0].analyzers.trade.get_analysis()['pnl']['net']['total']))
  122.     print("---------------- Vincite -------------")
  123.     print("Trade totali...........: {}".format(result[0].analyzers.trade.get_analysis()['won']['total']))
  124.     print("Trade PNL totale.......: {}".format(result[0].analyzers.trade.get_analysis()['won']['pnl']['total']))
  125.     print("Trade PNL medio........: {}".format(result[0].analyzers.trade.get_analysis()['won']['pnl']['average']))
  126.     print("Trade PNL massimo......: {}".format(result[0].analyzers.trade.get_analysis()['won']['pnl']['max']))
  127.     print("---------------- Perdite -------------")
  128.     print("Trade totali...........: {}".format(result[0].analyzers.trade.get_analysis()['lost']['total']))
  129.     print("Trade PNL totale.......: {}".format(result[0].analyzers.trade.get_analysis()['lost']['pnl']['total']))
  130.     print("Trade PNL medio........: {}".format(result[0].analyzers.trade.get_analysis()['lost']['pnl']['average']))
  131.     print("Trade PNL massimo......: {}".format(result[0].analyzers.trade.get_analysis()['lost']['pnl']['max']))
  132.     print("----------------- Long ---------------")
  133.     print("Trade totali...........: {}".format(result[0].analyzers.trade.get_analysis()['long']['total']))
  134.     print("Trade vinti............: {}".format(result[0].analyzers.trade.get_analysis()['long']['won']))
  135.     print("Trade persi............: {}".format(result[0].analyzers.trade.get_analysis()['long']['lost']))
  136.     print("Win/Loss Ratio.........: {}".format(
  137.         result[0].analyzers.trade.get_analysis()['long']['won'] / result[0].analyzers.trade.get_analysis()['long'][
  138.             'total']))
  139.     print("Trade PNL totale.......: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['total']))
  140.     print("Trade PNL Medio........: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['average']))
  141.     print("Trade Vincite Totali...: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['won']['total']))
  142.     print(
  143.         "Trade Vincita Media....: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['won']['average']))
  144.     print("Trade Vincita Massima..: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['won']['max']))
  145.     print(
  146.         "Trade Perdita Totali...: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['lost']['total']))
  147.     print("Trade Perdita Media....: {}".format(
  148.         result[0].analyzers.trade.get_analysis()['long']['pnl']['lost']['average']))
  149.     print("Trade Perdita Massima..: {}".format(result[0].analyzers.trade.get_analysis()['long']['pnl']['lost']['max']))
  150.     print("----------------- Short ---------------")
  151.     print("Trade totali...........: {}".format(result[0].analyzers.trade.get_analysis()['short']['total']))
  152.     print("Trade vinti............: {}".format(result[0].analyzers.trade.get_analysis()['short']['won']))
  153.     print("Trade persi............: {}".format(result[0].analyzers.trade.get_analysis()['short']['lost']))
  154.     print("Win/Loss Ratio.........: {}".format(
  155.         result[0].analyzers.trade.get_analysis()['short']['won'] / result[0].analyzers.trade.get_analysis()['short'][
  156.             'total']))
  157.     print("Trade PNL totale.......: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['total']))
  158.     print("Trade PNL Medio........: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['average']))
  159.     print(
  160.         "Trade Vincite Totali...: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['won']['total']))
  161.     print("Trade Vincita Media....: {}".format(
  162.         result[0].analyzers.trade.get_analysis()['short']['pnl']['won']['average']))
  163.     print("Trade Vincita Massima..: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['won']['max']))
  164.     print(
  165.         "Trade Perdita Totali...: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['lost']['total']))
  166.     print("Trade Perdita Media....: {}".format(
  167.         result[0].analyzers.trade.get_analysis()['short']['pnl']['lost']['average']))
  168.     print("Trade Perdita Massima..: {}".format(result[0].analyzers.trade.get_analysis()['short']['pnl']['lost']['max']))
  169.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement