本帖最後由 綠茶妹 於 23-2-12 20:42 編輯
今天又改了一下
1) 從IB抓1分鐘線 檔名store-1.py
- from ibapi.client import EClient
- from ibapi.wrapper import EWrapper
- from ibapi.contract import Contract
- import threading
- import time
- class IBapi(EWrapper, EClient):
- def __init__(self):
- EClient.__init__(self, self)
- self.data = [] #Initialize variable to store candle
- def historicalData(self, reqId, bar):
- print(f'Time: {bar.date} Close: {bar.close}')
- self.data.append([bar.date, bar.open,bar.high,bar.low,bar.close])
-
- def run_loop():
- app.run()
- app = IBapi()
- app.connect('127.0.0.1', 7497, 123)
- #Start the socket in a thread
- api_thread = threading.Thread(target=run_loop, daemon=True)
- api_thread.start()
- time.sleep(1) #Sleep interval to allow time for connection to server
- #Create contract object
- contract = Contract()
- contract.symbol = "MYM"
- contract.secType = "FUT"
- contract.exchange = "CBOT"
- contract.currency = "USD"
- contract.lastTradeDateOrContractMonth = "202303"
- #Request historical candles
- app.reqHistoricalData(1, contract, '', '2 D', '1 min', 'TRADES', 1, 2, False, [])
- time.sleep(10) #sleep to allow enough time for data to be returned
- #Working with Pandas DataFrames
- import pandas
- df = pandas.DataFrame(app.data, columns=['DateTime', 'Open','High','Low','Close'])
- df['DateTime'] = pandas.to_datetime(df['DateTime'],unit='s')
- df['DateTime'] = pandas.to_datetime(df['DateTime'], format='%d/%m/%y %H:%M:%S').dt.strftime('%Y-%m-%d %H:%M:%S')
- df.to_csv('dow_futures_1min.csv', header=False, index=False)
- print(df)
- app.disconnect()
複製代碼
2) 把這個1分鐘線拿去回測。檔名 backtrader-1.py
- from datetime import datetime
- import backtrader as bt
- import yfinance as yf
- import pandas as pd
- # Create a subclass of Strategy to define the indicators and logic
- class SmaCross(bt.Strategy):
- # list of parameters which are configurable for the strategy
- params = dict(
- pfast=10, # period for the fast moving average
- pslow=30 # period for the slow moving average
- )
- def __init__(self):
- sma1 = bt.ind.SMA(period=self.params.pfast) # fast moving average
- sma2 = bt.ind.SMA(period=self.params.pslow) # slow moving average
- self.crossover = bt.ind.CrossOver(sma1, sma2) # crossover signal
- def next(self):
- if not self.position: # not in the market
- if self.crossover > 0: # if fast crosses slow to the upside
- self.buy() # enter long
- elif self.crossover < 0: # in the market & cross to the downside
- self.close() # close long position
- # Create a cerebro instance to run the strategy
- cerebro = bt.Cerebro()
- #data = bt.feeds.GenericCSVData(dataname='dow_futures_1min.csv')
- data = bt.feeds.GenericCSVData(
- dataname='dow_futures_1min.csv',
- fromdate=None, # 起止日期
- todate=None,
- nullvalue=0.0,
- dtformat="%Y-%m-%d %H:%M:%S",
- timeframe=bt.TimeFrame.Minutes,
- datetime=0, # 各列的位置,从0开始,如列缺失则为None,-1表示自动根据列名判断
- high=1,
- low=2,
- open=3,
- close=4,
- volume=None,
- openinterest=None
- )
-
- cerebro.adddata(data)
- # Add the strategy to cerebro
- cerebro.addstrategy(SmaCross)
- # Run the strategy
- cerebro.run()
- # Plot the result
- cerebro.plot()
複製代碼
上面這個沒有買進和賣出的符號,等我有空再看。今天主要只是處理數據。
|