請選擇 進入手機版 | 繼續訪問電腦版

COCO研究院

 找回密碼
 註冊
搜索
查看: 927|回復: 2

[程式新手日誌] [轉貼] Backtrader量化平台教程(一):backtrader的整体框架

[複製鏈接]
發表於 23-3-13 22:26 | 顯示全部樓層 |閱讀模式

Backtrader量化平台教程(一):backtrader的整体框架



這一篇寫的很好
重點是範例檔會動,之前我抓過好幾個程式都不能用,東缺西缺的。

程式碼如下
  1. from __future__ import (absolute_import, division, print_function,
  2.                         unicode_literals)

  3. import datetime  # For datetime objects
  4. import os.path  # To manage paths
  5. import sys  # To find out the script name (in argv[0])
  6. import pandas as pd
  7. #from WindPy import w
  8. # Import the backtrader platform
  9. import backtrader as bt


  10. # Create a Stratey
  11. class TestStrategy(bt.Strategy):

  12.     def log(self, txt, dt=None):
  13.         ''' Logging function fot this strategy'''
  14.         dt = dt or self.datas[0].datetime.date(0)
  15.         print('%s, %s' % (dt.isoformat(), txt))

  16.     def __init__(self):
  17.         # Keep a reference to the "close" line in the data[0] dataseries
  18.         self.dataclose = self.datas[0].close
  19.         # To keep track of pending orders
  20.         self.order = None

  21.     def notify(self, order):
  22.         if order.status in [order.Submitted, order.Accepted]:
  23.             # Buy/Sell order submitted/accepted to/by broker - Nothing to do
  24.             return

  25.         # Check if an order has been completed
  26.         # Attention: broker could reject order if not enougth cash
  27.         if order.status in [order.Completed, order.Canceled, order.Margin]:
  28.             if order.isbuy():
  29.                 self.log('BUY EXECUTED, %.2f' % order.executed.price)
  30.             elif order.issell():
  31.                 self.log('SELL EXECUTED, %.2f' % order.executed.price)

  32.             self.bar_executed = len(self)

  33.         # Write down: no pending order
  34.         self.order = None

  35.     def next(self):
  36.         # Simply log the closing price of the series from the reference
  37.         self.log('Close, %.2f' % self.dataclose[0])

  38.         # Check if an order is pending ... if yes, we cannot send a 2nd one
  39.         if self.order:
  40.             return

  41.         # Check if we are in the market
  42.         if not self.position:

  43.             # Not yet ... we MIGHT BUY if ...
  44.             if self.dataclose[0] < self.dataclose[-1]:
  45.                 # current close less than previous close

  46.                 if self.dataclose[-1] < self.dataclose[-2]:
  47.                     # previous close less than the previous close

  48.                     # BUY, BUY, BUY!!! (with default parameters)
  49.                     self.log('BUY CREATE, %.2f' % self.dataclose[0])

  50.                     # Keep track of the created order to avoid a 2nd order
  51.                     self.order = self.buy()

  52.         else:

  53.             # Already in the market ... we might sell
  54.             if len(self) >= (self.bar_executed + 5):
  55.                 # SELL, SELL, SELL!!! (with all possible default parameters)
  56.                 self.log('SELL CREATE, %.2f' % self.dataclose[0])

  57.                 # Keep track of the created order to avoid a 2nd order
  58.                 self.order = self.sell()


  59. if __name__ == '__main__':
  60.     # Create a cerebro entity
  61.     cerebro = bt.Cerebro()

  62.     # Add a strategy
  63.     cerebro.addstrategy(TestStrategy)

  64.     # Create a Data Feed
  65.     # 本地数据,笔者用Wind获取的东风汽车数据以csv形式存储在本地。
  66.     # parase_dates = True是为了读取csv为dataframe的时候能够自动识别datetime格式的字符串,big作为index
  67.     # 注意,这里最后的pandas要符合backtrader的要求的格式
  68.     dataframe = pd.read_csv('dfqc.csv', index_col=0, parse_dates=True)
  69.     dataframe['openinterest'] = 0
  70.     data = bt.feeds.PandasData(dataname=dataframe,
  71.                         fromdate = datetime.datetime(2015, 1, 1),
  72.                         todate = datetime.datetime(2016, 12, 31)
  73.                         )
  74.     # Add the Data Feed to Cerebro
  75.     cerebro.adddata(data)

  76.     # Set our desired cash start
  77.     cerebro.broker.setcash(100000.0)

  78.     # Print out the starting conditions
  79.     print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

  80.     # Run over everything
  81.     cerebro.run()

  82.     # Print out the final result
  83.     print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
  84.     # Plot the result
  85.     cerebro.plot()
複製代碼



裡面的範例在下面這裡
dfqc.7z (9.39 KB, 下載次數: 42)

評分

參與人數 2金錢 +4 收起 理由
takashi888 + 2 感謝分享
manmanlai + 2 感謝分享

查看全部評分

發表於 23-3-14 07:22 | 顯示全部樓層
感謝分享,把 from __future__ import (absolute_import, division, print_function, unicode_literals) 拿掉,可以在 python3 執行,測試成功

評分

參與人數 1金錢 +5 收起 理由
綠茶妹 + 5 謝謝^^

查看全部評分

回復 支持 1 反對 0

使用道具 舉報

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

本版積分規則

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

GMT+8, 24-3-29 01:48

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.

快速回復 返回頂部 返回列表
理財討論網站 | AI繪圖AI超擬真美女AI beauty AI Stable DiffusionAI正妹AI Lookbook