Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. stochastick
    3. Best
    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

    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
    • 1 / 1