COCO研究院

 找回密碼
 註冊
搜索
查看: 2011|回復: 1

1分鐘線數據給backtrader用

[複製鏈接]
發表於 23-2-12 02:33 | 顯示全部樓層 |閱讀模式
本帖最後由 綠茶妹 於 23-2-12 02:36 編輯

感覺很簡單的東西我弄了一整天



請先參考這一篇
https://www.backtrader.com/docu/datafeed/

Datatrader的Data feed有以下幾種
  • Yahoo (online or already saved to a file)
  • VisualChart (see www.visualchart.com
  • Backtrader CSV (own cooked format for testing)
  • Generic CSV support


網路上的sample 多為第一種Yahoo,但是因為我是用1分鐘線圖。所以要改一下。

下面是寫好的


  1. from datetime import datetime
  2. import backtrader as bt
  3. import yfinance as yf
  4. import pandas as pd

  5. # Create a subclass of Strategy to define the indicators and logic

  6. class SmaCross(bt.Strategy):
  7.     # list of parameters which are configurable for the strategy
  8.     params = dict(
  9.         pfast=10,  # period for the fast moving average
  10.         pslow=30   # period for the slow moving average
  11.     )

  12.     def __init__(self):
  13.         sma1 = bt.ind.SMA(period=self.params.pfast)  # fast moving average
  14.         sma2 = bt.ind.SMA(period=self.params.pslow)  # slow moving average
  15.         self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal

  16.     def next(self):
  17.         if not self.position:  # not in the market
  18.             if self.crossover > 0:  # if fast crosses slow to the upside
  19.                 self.buy()  # enter long

  20.         elif self.crossover < 0:  # in the market & cross to the downside
  21.             self.close()  # close long position

  22. # Create a cerebro instance to run the strategy
  23. cerebro = bt.Cerebro()

  24. #data = bt.feeds.GenericCSVData(dataname='dow_futures_1min.csv')

  25. data = bt.feeds.GenericCSVData(
  26.     dataname='dow_futures_1min.csv',
  27.     fromdate=None,      # 起止日期
  28.     todate=None,
  29.     nullvalue=0.0,
  30.     dtformat="%Y-%m-%d %H:%M:%S",
  31.     timeframe=bt.TimeFrame.Minutes,
  32.     datetime=0,             # 各列的位置,从0开始,如列缺失则为None,-1表示自动根据列名判断
  33.     high=1,
  34.     low=2,
  35.     open=3,
  36.     close=4,
  37.     volume=None,
  38.     openinterest=None
  39. )

  40. cerebro.adddata(data)

  41. # Add the strategy to cerebro
  42. cerebro.addstrategy(SmaCross)

  43. # Run the strategy
  44. cerebro.run()

  45. # Plot the result
  46. cerebro.plot()
複製代碼


這個CSV檔有用Excel整理過,因為日期的格式有一點落差
dow_futures_1min.zip (7.55 KB, 下載次數: 73)


圖可以畫出來了。但是我覺得回測的部份好像是錯誤的,應該要有訊號才對。
明天再研究看看吧。


pic.png



參考資料:
https://blog.csdn.net/weixin_436 ... m_relevant_index=16

評分

參與人數 1金錢 +2 收起 理由
tinyding + 2 感謝分享

查看全部評分

 樓主| 發表於 23-2-12 20:37 | 顯示全部樓層
本帖最後由 綠茶妹 於 23-2-12 20:42 編輯

今天又改了一下
1) 從IB抓1分鐘線 檔名store-1.py
  1. from ibapi.client import EClient
  2. from ibapi.wrapper import EWrapper
  3. from ibapi.contract import Contract

  4. import threading
  5. import time

  6. class IBapi(EWrapper, EClient):
  7.         def __init__(self):
  8.                 EClient.__init__(self, self)
  9.                 self.data = [] #Initialize variable to store candle

  10.         def historicalData(self, reqId, bar):
  11.                 print(f'Time: {bar.date} Close: {bar.close}')
  12.                 self.data.append([bar.date, bar.open,bar.high,bar.low,bar.close])
  13.                
  14. def run_loop():
  15.         app.run()

  16. app = IBapi()
  17. app.connect('127.0.0.1', 7497, 123)

  18. #Start the socket in a thread
  19. api_thread = threading.Thread(target=run_loop, daemon=True)
  20. api_thread.start()

  21. time.sleep(1) #Sleep interval to allow time for connection to server

  22. #Create contract object
  23. contract = Contract()
  24. contract.symbol = "MYM"
  25. contract.secType = "FUT"
  26. contract.exchange = "CBOT"
  27. contract.currency = "USD"
  28. contract.lastTradeDateOrContractMonth = "202303"


  29. #Request historical candles
  30. app.reqHistoricalData(1, contract, '', '2 D', '1 min', 'TRADES', 1, 2, False, [])

  31. time.sleep(10) #sleep to allow enough time for data to be returned

  32. #Working with Pandas DataFrames
  33. import pandas

  34. df = pandas.DataFrame(app.data, columns=['DateTime', 'Open','High','Low','Close'])
  35. df['DateTime'] = pandas.to_datetime(df['DateTime'],unit='s')
  36. df['DateTime'] = pandas.to_datetime(df['DateTime'], format='%d/%m/%y %H:%M:%S').dt.strftime('%Y-%m-%d %H:%M:%S')
  37. df.to_csv('dow_futures_1min.csv', header=False, index=False)  

  38. print(df)


  39. app.disconnect()

複製代碼




2) 把這個1分鐘線拿去回測。檔名 backtrader-1.py

  1. from datetime import datetime
  2. import backtrader as bt
  3. import yfinance as yf
  4. import pandas as pd

  5. # Create a subclass of Strategy to define the indicators and logic

  6. class SmaCross(bt.Strategy):
  7.     # list of parameters which are configurable for the strategy
  8.     params = dict(
  9.         pfast=10,  # period for the fast moving average
  10.         pslow=30   # period for the slow moving average
  11.     )

  12.     def __init__(self):
  13.         sma1 = bt.ind.SMA(period=self.params.pfast)  # fast moving average
  14.         sma2 = bt.ind.SMA(period=self.params.pslow)  # slow moving average
  15.         self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal

  16.     def next(self):
  17.         if not self.position:  # not in the market
  18.             if self.crossover > 0:  # if fast crosses slow to the upside
  19.                 self.buy()  # enter long

  20.         elif self.crossover < 0:  # in the market & cross to the downside
  21.             self.close()  # close long position

  22. # Create a cerebro instance to run the strategy
  23. cerebro = bt.Cerebro()

  24. #data = bt.feeds.GenericCSVData(dataname='dow_futures_1min.csv')

  25. data = bt.feeds.GenericCSVData(
  26.     dataname='dow_futures_1min.csv',
  27.     fromdate=None,      # 起止日期
  28.     todate=None,
  29.     nullvalue=0.0,
  30.     dtformat="%Y-%m-%d %H:%M:%S",
  31.     timeframe=bt.TimeFrame.Minutes,
  32.     datetime=0,             # 各列的位置,从0开始,如列缺失则为None,-1表示自动根据列名判断
  33.     high=1,
  34.     low=2,
  35.     open=3,
  36.     close=4,
  37.     volume=None,
  38.     openinterest=None
  39. )

  40. cerebro.adddata(data)

  41. # Add the strategy to cerebro
  42. cerebro.addstrategy(SmaCross)

  43. # Run the strategy
  44. cerebro.run()

  45. # Plot the result
  46. cerebro.plot()
複製代碼





上面這個沒有買進和賣出的符號,等我有空再看。今天主要只是處理數據。

您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

手機版|Archiver|站長信箱|廣告洽詢|COCO研究院

GMT+8, 24-12-2 13:08

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.

快速回復 返回頂部 返回列表
理財討論網站 |