Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. stochastick
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    S
    • Profile
    • Following 0
    • Followers 0
    • Topics 0
    • Posts 3
    • Best 2
    • Groups 0

    stochastick

    @stochastick

    2
    Reputation
    15
    Profile views
    3
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    stochastick Unfollow Follow

    Best posts made by stochastick

    • RE: How to get the data as array of the sma1 and sma2

      Maybe try something list this.. Initialize empty list during init, and add to it during next(). Finally, during stop(), combine into a df and export/use for your own purposes.

      @Ronan-Dunham said in How to get the data as array of the sma1 and sma2:

      class SmaCross(bt.SignalStrategy):
          def __init__(self):
              sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
              crossover = bt.ind.CrossOver(sma1, sma2)
              self.signal_add(bt.SIGNAL_LONG, crossover)
              self.ma1 = []     # Initialize empty lists to hold indicator values
              self.ma2 = []     # Initialize empty lists to hold indicator values
      
          def next(self):
              # Create data frame columns here by appending data to a list
              self.ma1.append(sma1)   
              self.ma2.append(sma2)   
      
          def stop(self):
              # Combine and export pandas DataFrame here   
      
      cerebro = bt.Cerebro()
      cerebro.addstrategy(SmaCross)
      store = alpaca_backtrader_api.AlpacaStore(key_id=ALPACA_API_KEY,secret_key=ALPACA_SECRET_KEY,paper=ALPACA_PAPER)
      DataFactory = store.getdata
      
      data0 = DataFactory(
              dataname=symbol_to_check,
              timeframe=bt.TimeFrame.TFrame("Minutes"),
              fromdate=pd.Timestamp('2019-11-15'),compression =1,
      #         todate=pd.Timestamp('2018-11-17'),
              historical=True)
      
      cerebro.adddata(data0)
      
      cerebro.run()
      cerebro.plot()
      posted in General Code/Help
      S
      stochastick
    • RE: How to get the data as array of the sma1 and sma2

      There is most certainly a more efficient way to accomplish what you seek, but nonetheless here is a working sample that accomplishes I believe what you are searching for. The data frame is simply saved to CSV here, but you could do whatever you want with it. Data is loaded from my own sources, but just substitute with yours.

      import backtrader as bt
      import pandas as pd
      
      
      class SmaCross(bt.SignalStrategy):
      
          # Global Parameters
          globalParams = {'symbols': ['EUR_USD'],
                          'startDate': '01-01-2018',
                          'endDate': '01-05-2018'}
      
          def __init__(self):
              self.sma1 = bt.ind.SMA(period=10)
              self.sma2 = bt.ind.SMA(period=30)
              self.crossover = bt.ind.CrossOver(self.sma1, self.sma2)
              self.signal_add(bt.SIGNAL_LONG, self.crossover)
      
              # Initialize empty lists to hold values
              self.date_time = []
              self.close_px = []
              self.ma1 = []
              self.ma2 = []
      
          def log(self, txt, dt=None):
              """ Logging function """
              dt = dt or self.datas[0].datetime.datetime()
              print('%s, %s' % (dt.isoformat(), txt))
      
          def next(self):
              """Log data to console and save to lists"""
              
              self.log('%s '
                       '| O %.5f '
                       '| H %.5f '
                       '| L %.5f '
                       '| C %.5f '
                       '| SMA1 %.5f '
                       '| SMA2 %.5f '
                       %
                    (self.datas[0]._name,
                     self.datas[0].open[0],
                     self.datas[0].high[0],
                     self.datas[0].low[0],
                     self.datas[0].close[0],
                     self.sma1[0],
                     self.sma2[0]))
      
              self.date_time.append(self.datas[0].datetime.datetime())
              self.close_px.append(self.datas[0].close[0])
              self.ma1.append(self.sma1[0])
              self.ma2.append(self.sma2[0])
      
          def stop(self):
              df = pd.DataFrame(index=self.date_time)
              df['Close'] = self.close_px
              df['SMA1'] = self.ma1
              df['SMA2'] = self.ma2
              df.to_csv('trade_history.csv', sep='\t')
      
      
      cerebro = bt.Cerebro()
      cerebro.addstrategy(SmaCross)
      
      symbols = SmaCross.globalParams['symbols']
      
      for symbol in symbols:
          mktData = pd.read_json('../sample-data/FX/training_' + symbol + '.json')
          mktData['time'] = pd.to_datetime(mktData['time'])
          timeSlice = ((mktData['time'] > SmaCross.globalParams['startDate']) &
                       (mktData['time'] < SmaCross.globalParams['endDate']))
          mktData = mktData.loc[timeSlice]
          mktData = bt.feeds.PandasData(dataname=mktData, timeframe=bt.TimeFrame.Minutes, datetime='time', close='close')
          cerebro.resampledata(mktData, timeframe=bt.TimeFrame.Minutes, compression=5, name=symbol)
      
      cerebro.run()
      
      

      This creates a CSV file formatted as such.

      6542e877-fce6-4584-9061-7b89fb665248-image.png

      posted in General Code/Help
      S
      stochastick

    Latest posts made by stochastick

    • RE: How to get the data as array of the sma1 and sma2

      There is most certainly a more efficient way to accomplish what you seek, but nonetheless here is a working sample that accomplishes I believe what you are searching for. The data frame is simply saved to CSV here, but you could do whatever you want with it. Data is loaded from my own sources, but just substitute with yours.

      import backtrader as bt
      import pandas as pd
      
      
      class SmaCross(bt.SignalStrategy):
      
          # Global Parameters
          globalParams = {'symbols': ['EUR_USD'],
                          'startDate': '01-01-2018',
                          'endDate': '01-05-2018'}
      
          def __init__(self):
              self.sma1 = bt.ind.SMA(period=10)
              self.sma2 = bt.ind.SMA(period=30)
              self.crossover = bt.ind.CrossOver(self.sma1, self.sma2)
              self.signal_add(bt.SIGNAL_LONG, self.crossover)
      
              # Initialize empty lists to hold values
              self.date_time = []
              self.close_px = []
              self.ma1 = []
              self.ma2 = []
      
          def log(self, txt, dt=None):
              """ Logging function """
              dt = dt or self.datas[0].datetime.datetime()
              print('%s, %s' % (dt.isoformat(), txt))
      
          def next(self):
              """Log data to console and save to lists"""
              
              self.log('%s '
                       '| O %.5f '
                       '| H %.5f '
                       '| L %.5f '
                       '| C %.5f '
                       '| SMA1 %.5f '
                       '| SMA2 %.5f '
                       %
                    (self.datas[0]._name,
                     self.datas[0].open[0],
                     self.datas[0].high[0],
                     self.datas[0].low[0],
                     self.datas[0].close[0],
                     self.sma1[0],
                     self.sma2[0]))
      
              self.date_time.append(self.datas[0].datetime.datetime())
              self.close_px.append(self.datas[0].close[0])
              self.ma1.append(self.sma1[0])
              self.ma2.append(self.sma2[0])
      
          def stop(self):
              df = pd.DataFrame(index=self.date_time)
              df['Close'] = self.close_px
              df['SMA1'] = self.ma1
              df['SMA2'] = self.ma2
              df.to_csv('trade_history.csv', sep='\t')
      
      
      cerebro = bt.Cerebro()
      cerebro.addstrategy(SmaCross)
      
      symbols = SmaCross.globalParams['symbols']
      
      for symbol in symbols:
          mktData = pd.read_json('../sample-data/FX/training_' + symbol + '.json')
          mktData['time'] = pd.to_datetime(mktData['time'])
          timeSlice = ((mktData['time'] > SmaCross.globalParams['startDate']) &
                       (mktData['time'] < SmaCross.globalParams['endDate']))
          mktData = mktData.loc[timeSlice]
          mktData = bt.feeds.PandasData(dataname=mktData, timeframe=bt.TimeFrame.Minutes, datetime='time', close='close')
          cerebro.resampledata(mktData, timeframe=bt.TimeFrame.Minutes, compression=5, name=symbol)
      
      cerebro.run()
      
      

      This creates a CSV file formatted as such.

      6542e877-fce6-4584-9061-7b89fb665248-image.png

      posted in General Code/Help
      S
      stochastick
    • RE: How to get the data as array of the sma1 and sma2

      Maybe try something list this.. Initialize empty list during init, and add to it during next(). Finally, during stop(), combine into a df and export/use for your own purposes.

      @Ronan-Dunham said in How to get the data as array of the sma1 and sma2:

      class SmaCross(bt.SignalStrategy):
          def __init__(self):
              sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
              crossover = bt.ind.CrossOver(sma1, sma2)
              self.signal_add(bt.SIGNAL_LONG, crossover)
              self.ma1 = []     # Initialize empty lists to hold indicator values
              self.ma2 = []     # Initialize empty lists to hold indicator values
      
          def next(self):
              # Create data frame columns here by appending data to a list
              self.ma1.append(sma1)   
              self.ma2.append(sma2)   
      
          def stop(self):
              # Combine and export pandas DataFrame here   
      
      cerebro = bt.Cerebro()
      cerebro.addstrategy(SmaCross)
      store = alpaca_backtrader_api.AlpacaStore(key_id=ALPACA_API_KEY,secret_key=ALPACA_SECRET_KEY,paper=ALPACA_PAPER)
      DataFactory = store.getdata
      
      data0 = DataFactory(
              dataname=symbol_to_check,
              timeframe=bt.TimeFrame.TFrame("Minutes"),
              fromdate=pd.Timestamp('2019-11-15'),compression =1,
      #         todate=pd.Timestamp('2018-11-17'),
              historical=True)
      
      cerebro.adddata(data0)
      
      cerebro.run()
      cerebro.plot()
      posted in General Code/Help
      S
      stochastick
    • RE: Strategy execution on different timeframes and multi-data

      I am revisiting this old thread as it seems to be a good jumping off point for a problem I'm stuck on. How might we extend this code to incorporate multiple unique symbols?

      @backtrader said in Strategy execution on different timeframes and multi-data:

      next is called for any tick which any data produces. Concentrating on a specific data is a matter of looking at the len of the data.

      When the len of the data changes (it will always go up) you know you got a tick of that data

      def start(self):
          self.lendata1 = 0
      def next(self):
          if len(self.data1) > self.lendata1:
              self.lendata1 += 1
              do_something_here()
      

      I am trying to run a test across multiple symbols by evaluating trade signals on one time frame and completing executions on another.

      When using the aforementioned code within an enumeration, only trades for the first added data feed are acted upon.

      This is a snippet of the code I am working with, which parallel's that @backtrader outlines above:

      '''python

      def start(self):
          self.datas[1].len = 0
      
      def next(self):
          for i, d in enumerate(self.datas):
              if len(self.datas[1]) > self.datas[1].len:
                  self.datas[1].len += 1
                  TRADE_LOGIC_HERE
      

      '''

      It seems like something else needs to be done other than just wrapping this in enumerate(). I have tried many different versions and have been stuck on this problem for the last several weeks, so any help is appreciated. If needed, I can create a unique thread for this problem.

      posted in General Code/Help
      S
      stochastick