Backtrader Community

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

    Could I resample the bidaskcsv?

    General Code/Help
    2
    3
    32
    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.
    • 陆韬
      陆韬 last edited by

      HI everyone, I want to resample my bidask csv(temp.csv) like below and write it to a new csv:

      datetime,bid,ask
      07/23/2023 21:05:13,1.11246,1.11278
      07/23/2023 21:05:14,1.11248,1.11278
      

      Here is my code:

      import pandas as pd
      import backtrader as bt
      import backtrader.feeds as btfeeds
      
      
      class MyStrategy(bt.Strategy):
      
          def stop(self):
              data = self.datas[0]
              df = pd.DataFrame({
                  'Date Time': [bt.num2date(x) for x in data.datetime.array],
                  'bid': data.bid.array,
                  'ask': data.ask.array
              })
              df.to_csv("outputresult.csv", index=False)
      
      
      class BidAskCSV(btfeeds.GenericCSVData):
          linesoverride = True  # discard usual OHLC structure
          # datetime must be present and last
          lines = ('bid', 'ask', 'datetime')
          # datetime (always 1st) and then the desired order for
          params = (
              ('dtformat', '%m/%d/%Y %H:%M:%S'),
              ('datetime', 0),  # inherited from parent class
              ('bid', 1),  # default field pos 1
              ('ask', 2),  # default field pos 2
          )
      
      
      def resample(timeframe, compression, name):
          cerebro = bt.Cerebro()
          cerebro.addstrategy(MyStrategy)
          data = BidAskCSV(dataname=name, dtformat='%m/%d/%Y %H:%M:%S')
      
          cerebro.resampledata(data, timeframe=timeframe, compression=compression)
      
          cerebro.run()
      
          # cerebro.plot(volume=False, openinterest=False, cash=False, style='candle')
      
      
      if __name__ == '__main__':
          resample(bt.TimeFrame.Seconds, 1, "temp.csv")
      
      

      The following exception occurred when I was running my code:

      D:\software\anaconda\envs\py38_lh\python.exe D:\project\code\mqlutil\convert_util_new.py 
      Traceback (most recent call last):
        File "D:\project\code\mqlutil\convert_util_new.py", line 77, in <module>
          resample(bt.TimeFrame.Seconds, 1, "temp.csv")
        File "D:\project\code\mqlutil\convert_util_new.py", line 71, in resample
          cerebro.run()
        File "D:\software\anaconda\envs\py38_lh\lib\site-packages\backtrader\cerebro.py", line 1127, in run
          runstrat = self.runstrategies(iterstrat)
        File "D:\software\anaconda\envs\py38_lh\lib\site-packages\backtrader\cerebro.py", line 1298, in runstrategies
          self._runnext(runstrats)
        File "D:\software\anaconda\envs\py38_lh\lib\site-packages\backtrader\cerebro.py", line 1542, in _runnext
          drets.append(d.next(ticks=False))
        File "D:\software\anaconda\envs\py38_lh\lib\site-packages\backtrader\feed.py", line 407, in next
          ret = self.load()
        File "D:\software\anaconda\envs\py38_lh\lib\site-packages\backtrader\feed.py", line 523, in load
          retff = ff(self, *fargs, **fkwargs)
        File "D:\software\anaconda\envs\py38_lh\lib\site-packages\backtrader\resamplerfilter.py", line 522, in __call__
          self.bar.bupdate(data)  # update new or existing bar
        File "D:\software\anaconda\envs\py38_lh\lib\site-packages\backtrader\dataseries.py", line 199, in bupdate
          self.high = max(self.high, data.high[0])
        File "D:\software\anaconda\envs\py38_lh\lib\site-packages\backtrader\lineseries.py", line 461, in __getattr__
          return getattr(self.lines, name)
      AttributeError: 'Lines_LineSeries_DataSeries_OHLC_OHLCDateTime_Abst' object has no attribute 'high'
      

      I want to know is cerebro.resampledata could use for bidask csv?If possible, what is the problem with my code? Thank you.

      陆韬 1 Reply Last reply Reply Quote 0
      • 陆韬
        陆韬 @陆韬 last edited by

        Can anyone help me. Thank you

        1 Reply Last reply Reply Quote 0
        • Hanery
          Hanery last edited by

          Python
          import pandas as pd

          Read the bidaskcsv file into a Pandas DataFrame

          df = pd.read_csv("bidaskcsv.csv")

          Resample the DataFrame to 1 minute intervals

          df = df.resample('1T').agg({'bid': 'mean', 'ask': 'mean'})

          Save the resampled DataFrame to a new file

          df.to_csv("bidask_1min.csv")
          Use code with caution. Learn more
          This code will read the bidaskcsv file into a Pandas DataFrame and then resample the DataFrame to 1 minute intervals. The resampled DataFrame will be saved to a new file called bidask_1min.csv.

          The resample() method in Pandas takes a string as its first argument. This string specifies the frequency of the resampling. In this case, we are resampling the DataFrame to 1 minute intervals, so we use the string '1T'.

          The resample() method also takes a dictionary as its second argument. This dictionary specifies the aggregation functions that should be used for each column. In this case, we are averaging the bid and ask prices, so we use the aggregation functions 'mean' for both columns.

          Once the DataFrame has been resampled, it can be saved to a new file using the to_csv() method.

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