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/

    i can't figure out extending lines

    General Code/Help
    5
    8
    187
    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.
    • B
      bobaleaux last edited by

      hell all,
      no matter how many examples i try, i can't seem to get my columns to use.
      i must have an error in what exactly i am calling to use on the bt.indicators because they don't match with the values in my dataframe...
      and i think processing would be a lot faster if i only needed to calculate from my already known values..
      this is for monitoring right now....

      sorry, again, i tried pasting but it came out like below..

      here is my code..

      data = pd.read_sql("""
      select datetime, open, high, low, close, volume, sma_20, sma_50, ema_8, mom, lin_ang
      from stock_price_15
      where symbol = :symbol
      and sma_50 is not 0
      and datetime > '2021-01-26'
      and strftime('%H:%M:%S', datetime) >= '09:30:00'
      and strftime('%H:%M:%S', datetime) < '16:00:00'
      order by datetime asc
      """, conn, params={"symbol": stock['symbol']}, index_col='datetime', parse_dates=['datetime'])

      data = bt.feeds.PandasDirectData(dataname=data)
      cerebro.adddata(data)
      

      #CREATES THIS DF
      == Analysing A ==
      open high low close volume sma_20 sma_50 ema_8 mom
      datetime
      2021-01-26 09:30:00 125.50 125.95 124.550 125.040 92435 125.072505 125.919682 125.203493 0
      2021-01-26 09:45:00 125.09 125.16 124.430 125.005 88188 125.070255 125.887382 125.159384 0
      2021-01-26 10:00:00 125.04 125.36 124.740 124.845 39486 125.055005 125.850682 125.089521 0
      2021-01-26 10:15:00 124.82 125.29 124.630 125.210 29410 125.072005 125.819482 125.116294 0
      2021-01-26 10:30:00 125.24 125.66 125.170 125.550 43447 125.119005 125.791882 125.212673 0
      ... ... ... ... ... ... ... ... ... ...
      2021-01-28 10:45:00 121.18 121.68 121.180 121.400 40882 120.019275 121.871370 120.669654 0
      2021-01-28 11:00:00 121.43 121.89 121.340 121.870 43707 120.081025 121.810170 120.936397 0
      2021-01-28 11:15:00 121.87 122.04 121.390 121.640 53618 120.141025 121.746970 121.092753 0
      2021-01-28 11:30:00 121.65 122.25 121.550 122.195 37105 120.213775 121.691670 121.337697 0
      2021-01-28 11:45:00 122.25 122.67 122.115 122.500 54387 120.31

      then.............

      create a Strategy

      class OpeningRangeBreakout(bt.Strategy):
      #class TestStrategy(bt.Strategy):
      params = (
      dict(num_opening_bars=15)
      )

      def log(self, txt, dt=None):
          ''' Logging function for this strategy'''
          if dt is None:
              dt = self.datas[0].datetime.datetime(0)
          print('%s, %s' % (dt, txt))
      
      ########## DEFINING THE TEMPLATE AND VARIABLES TO USE
      
      def __init__(self):
        
          self.dataclose = self.datas[0].close
      
          self.opening_range_low = 0
          self.opening_range_high = 0
          self.opening_range = 0
          self.bought_today = False
          self.order = None
          self.buyprice = None
          self.buycomm = None
      
          ## ADD INDICATORS ###########
          self.sma_20 = bt.indicators.SimpleMovingAverage(
              self.datas[0], period=20)
          self.sma_50 = bt.indicators.SimpleMovingAverage(
              self.datas[0], period=50)
          # Indicators for the plotting show
          self.ema_8 = bt.indicators.ExponentialMovingAverage(self.datas[0], period=8)
      

      def next(self):

          ######### THE CURRENT SESSION #########################################
          current_bar_ = self.data.num2date(self.data.datetime[0])       
          previous_bar = self.data.num2date(self.data.datetime[-1])        
          two__bars_back = self.data.num2date(self.data.datetime[-2])
          three_bars_back = self.data.num2date(self.data.datetime[-3])
      
      A 1 Reply Last reply Reply Quote 0
      • A
        ab_trader @bobaleaux last edited by

        @bobaleaux said in i can't figure out extending lines:

        sorry, again, i tried pasting but it came out like below..

        Use backticks as stated on top of the page to make code and output blocks readable.

        • If my answer helped, hit reputation up arrow at lower right corner of the post.
        • Python Debugging With Pdb
        • New to python and bt - check this out
        B 1 Reply Last reply Reply Quote 0
        • B
          bobaleaux @ab_trader last edited by

          @ab_trader
          thanks... wish extending lines was so straight forward...

          i am so new to coding withthe volume of information i'm trying digest i skim over way too many details that make things work...
          and end up here....

          any assistance will be greatly appreciated

          data = pd.read_sql("""
                      select datetime, open, high, low, close, volume, sma_20, sma_50, ema_8, mom, lin_ang
                      from stock_price_15
                      where symbol = :symbol
                      and sma_50 is not 0
                      and datetime > '2021-01-26'
                      and strftime('%H:%M:%S', datetime) >= '09:30:00' 
                      and strftime('%H:%M:%S', datetime) < '16:00:00'
                      order by datetime asc
                  """, conn, params={"symbol": stock['symbol']}, index_col='datetime', parse_dates=['datetime'])
          
                  data = bt.feeds.PandasDirectData(dataname=data)
          
                  cerebro.adddata(data)
          
          

          cd13061a-6346-4332-9dc2-7af590cf8f3e-image.png

          class OpeningRangeBreakout(bt.Strategy):
          
              params = (
                  dict(num_opening_bars=15)
              )
           
              def log(self, txt, dt=None):
                  ''' Logging function for this strategy'''
                  if dt is None:
                      dt = self.datas[0].datetime.datetime(0)
                  print('%s, %s' % (dt, txt))   
          
              def __init__(self):
                  
                  self.dataclose = self.datas[0].close
          
                  # To keep track of
                  self.opening_range_low = 0
                  self.opening_range_high = 0
                  self.opening_range = 0
                  self.bought_today = False
                  self.order = None
                  self.buyprice = None
                  self.buycomm = None
          
                  ## ADD INDICATORS ###########
                  self.sma_20 = bt.indicators.SimpleMovingAverage(
                      self.datas[0], period=20)
                  self.sma_50 = bt.indicators.SimpleMovingAverage(
                      self.datas[0], period=50)
                  # Indicators for the plotting show
                  self.ema_8 = bt.indicators.ExponentialMovingAverage(self.datas[0], period=8)
          
              def next(self):
                
                  current_bar_datetime = self.data.num2date(self.data.datetime[0])        
                  previous_bar_datetime = self.data.num2date(self.data.datetime[-1])       
                  two_bars_back = self.data.num2date(self.data.datetime[-2])
                  three_bars_back = self.data.num2date(self.data.datetime[-3])
                 
                  self.log(self.data.close[0])
          
                  #self.log(self.datavolume[0])
          
          
                  #print(f'dataclose',(self.dataclose[0]) )
                  #print(f'ema_8', self.ema_8[0])
                  #print(f'sma_20', self.sma_20[0])
                  #print(f'sma_50', self.sma_50[0])
          
          
                  ############## THE FIRST SESSION OF THE NEW DAY  ROUTE 1####################
                  if current_bar_datetime.date() != previous_bar_datetime.date():
                      self.opening_range_high = self.data.high[0]
                      opening_high = self.data.high
                      #print(f'opening high', opening_high[0])
                      self.opening_range_low = self.data.low[0]
                      #print(f'opening range low',self.data.low[0])
          
                      #### OPENING RANGE ###
                      opening_range_start_time = time(9, 30, 0)
                      dt = datetime.combine(datetime.today(), opening_range_start_time) + timedelta(minutes=self.p.num_opening_bars)
                      opening_range_end_time = dt.time()
                      ###################
          
                      print(f'opening close', self.dataclose[0])
          
          run-out 1 Reply Last reply Reply Quote 0
          • run-out
            run-out @bobaleaux last edited by

            @bobaleaux
            I'm enclosing below as full sample of loading OHLCV from csv, adding in 20 adn 50 SMA, and then loading it into backtrader. I hope this helps you on your way.

            import backtrader as bt
            import pandas as pd
            import btalib
            
            
            class CustomDataLoader(bt.feeds.PandasData):
                """
                An example of a pandas extraline loader.
                """
            
                lines = (
                    "sma_20",
                    "sma_50",
                )
            
                params = (
                    ("sma_20", 5),
                    ("sma_50", 6),
                )
            
                datafields = bt.feeds.PandasData.datafields + (["sma_20", "sma_50",])
            
            
            class Strategy(bt.Strategy):
                def log(self, txt, dt=None):
                    """ Logging function fot this strategy"""
                    dt = dt or self.data.datetime[0]
                    if isinstance(dt, float):
                        dt = bt.num2date(dt)
                    print("%s, %s" % (dt, txt))
            
                def print_signal(self):
            
                    self.log(
                        "o {:5.2f}\th {:5.2f}\tl {:5.2f}\tc {:5.2f}\tv {:5.0f}\t20 {:5.2f}\t50 {:5.2f}".format(
                            self.datas[0].open[0],
                            self.datas[0].high[0],
                            self.datas[0].low[0],
                            self.datas[0].close[0],
                            self.datas[0].volume[0],
                            self.datas[0].sma_20[0],
                            self.datas[0].sma_50[0],
                        )
                    )
            
                def next(self):
                    self.print_signal()
            
            
            if __name__ == "__main__":
            
                cerebro = bt.Cerebro()
            
                # Create dataframe with extended lines.
                datapath = "data/dev.csv"
                dataframe = pd.read_csv(datapath, header=None, parse_dates=True, index_col=0)
                dataframe.columns = ["high", "low", "open", "close", "cumvol", "volume"]
                dataframe["sma_20"] = btalib.sma(dataframe, period=20).df
                dataframe["sma_50"] = btalib.sma(dataframe, period=50).df
                dataframe = dataframe.dropna()
                dataframe = dataframe.iloc[:20, :]
            
                data = CustomDataLoader(dataname=dataframe)
            
                cerebro.adddata(data)
            
                cerebro.addstrategy(Strategy)
            
                # Execute
                cerebro.run()
            
            

            RunBacktest.com

            R 1 Reply Last reply Reply Quote 1
            • R
              rajanprabu @run-out last edited by

              @run-out on this note.. what happens to the values of additional lines if one resample this input data ?

              vladisld B 2 Replies Last reply Reply Quote 0
              • vladisld
                vladisld @rajanprabu last edited by

                @rajanprabu

                resampling will ignore any non OHLC extra lines by default. See the following post ( and linked posts inside it ) for more info: https://community.backtrader.com/topic/2812/resample-for-extra-information-in-lines/2

                R 1 Reply Last reply Reply Quote 3
                • R
                  rajanprabu @vladisld last edited by

                  @vladisld Thanks.. very helpful

                  1 Reply Last reply Reply Quote 1
                  • B
                    bobaleaux @rajanprabu last edited by

                    @rajanprabu Thank you, Thank you, thank you!

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