Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Code runs without error but results don't make sense

    General Code/Help
    1
    2
    28
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • C
      Cal last edited by

      Here's the code:

      from __future__ import (absolute_import, division, print_function, unicode_literals)
      
      import datetime
      import backtrader as bt
      import backtrader.feeds as btfeeds
      import yfinance as yf
      
      import backtrader.analyzers as btanalyzers
      import backtrader.strategies as btstrats
      
      # Create a strategy
      class SmaCross(bt.Strategy):
          # list of parameters which are configurable for the strategy
          params = dict(
              pfast=9,  # period for the fast moving average
              pslow=80   # period for the slow moving average
          )
      
          def __init__(self):
              sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
              sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
              self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal
      
          def next(self):
              if not self.position:  # not in the market
                  if self.crossover > 0:  # if fast crosses slow to the upside
                      self.buy()  # enter long
      
              elif self.crossover < 0:  # in the market & cross to the downside
                  self.close()  # close long position
      
      cerebro = bt.Cerebro()
      
      data = bt.feeds.PandasData(dataname=yf.download('AAPL', '2013-01-01', '2017-12-31', auto_adjust=True))
      
      cerebro.adddata(data)
      
      cerebro.addstrategy(SmaCross)
      
      cerebro.addanalyzer(btanalyzers.TradeAnalyzer, _name='myanalysis')
      thestrats = cerebro.run()
      thestrat = thestrats[0]
      result = thestrat.analyzers.myanalysis.get_analysis()
      
      # Printig Analyses:
      print("Total Trades: ", result.total.total)
      print("Gross Total: ", round(result.pnl.gross.total,4))
      print("Average/Trade: ", round(result.pnl.gross.average,4))
      print("Bars per Trade: ", round(result.len.average,2))
      
      # cerebro.plot()
      

      This results in:

      [*********************100%***********************]  1 of 1 completed
      Total Trades:  12
      Gross Total:  11.8395
      Average/Trade:  1.0763
      Bars per Trade:  67.73
      
      Process finished with exit code 0
      

      It's a trade and reverse system (always in). Why wouldn't BarsPerTrade*TotalTrades = TotalTradingDaysInPeriod - slowSMA?

      1 Reply Last reply Reply Quote 0
      • C
        Cal last edited by

        I duplicated the strategy in Excel. Everything looks good except Bars per Trade. Should be 147.5 instead of 67.73.

        1 Reply Last reply Reply Quote 0
        • 1 / 1
        • First post
          Last post
        Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors