簡體   English   中英

如何在 Backtrade 中處理 GenericCSVData 中的日期格式

[英]How To Handle date format in GenericCSVData in Backtrade

我正在嘗試一個簡單的例子,它從我的 csv 打印日期時間和收盤價。 它正確打印日期,但僅打印23:59:59的時間。 你能幫我檢查一下我做錯了什么嗎?

這是我的代碼:

import datetime
import backtrader as bt
import backtrader.feeds as btfeeds

class PrintClose(bt.Strategy):

    def __init__(self):
        self.dataclose = self.datas[0].close

    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.datetime(0).strftime('%Y-%m-%d %H:%M:%S%z')
        print(f'{dt} {txt}')  # Print date and close

    def next(self):
        self.log(self.dataclose[0])


if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(PrintClose)
    datapath = './RELIANCE_formatted.csv'

    data = btfeeds.GenericCSVData(
        dataname=datapath,
        dtformat=('%Y-%m-%d %H:%M:%S%z'),
        timestamp=0,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1
    )

    cerebro.adddata(data)
    cerebro.run()

輸出 :

2016-07-04 23:59:59 489.1
2016-07-04 23:59:59 491.45
2016-07-04 23:59:59 489.8
2016-07-04 23:59:59 488.75
2016-07-04 23:59:59 488.75
2016-07-04 23:59:59 489.15
2016-07-04 23:59:59 488.55
2016-07-05 23:59:59 486.95
2016-07-05 23:59:59 486.9

預期輸出:

2016-07-04 09:15:00+05:30 489.1
2016-07-04 10:15:00+05:30 491.45
2016-07-04 11:15:00+05:30 489.8
2016-07-04 12:15:00+05:30 488.75
2016-07-04 13:15:00+05:30 488.75
2016-07-04 14:15:00+05:30 489.15
2016-07-04 15:15:00+05:30 488.55
2016-07-05 09:15:00+05:30 486.95
2016-07-05 10:15:00+05:30 486.9

這是我的 csv

date,open,high,low,close,volume
2016-07-04 09:15:00+05:30,483.4,490.35,483.4,489.1,950630
2016-07-04 10:15:00+05:30,489.1,492.05,488.55,491.45,603618
2016-07-04 11:15:00+05:30,491.7,491.95,489.4,489.8,514331
2016-07-04 12:15:00+05:30,489.8,490.65,488.15,488.75,374728
2016-07-04 13:15:00+05:30,488.85,489.55,488.25,488.75,31432
2016-07-04 14:15:00+05:30,488.75,490.3,487.45,489.15,511010
2016-07-04 15:15:00+05:30,489.1,489.25,487.95,488.55,323005
2016-07-05 09:15:00+05:30,488.55,490.1,486.5,486.95,441230
2016-07-05 10:15:00+05:30,486.9,488.05,485.55,486.9,320247

在@run-out 的幫助下,我終於讓它工作了,以查看時間范圍和壓縮。 然后改變dtformat。 這是解決方案。

data = btfeeds.GenericCSVData(
    dataname=datapath,
    datetime=0,
    open=1,
    high=2,
    low=3,
    close=4,
    volume=5,
    openinterest=-1,
    dtformat=('%Y-%m-%d %H:%M:%S+05:30'),
    timeframe=bt.TimeFrame.Minutes, 
    compression=60,
)

你需要告訴 Backtrader 時間范圍和壓縮,否則它不知道它正在使用什么間隔。

 data = btfeeds.GenericCSVData(
        dataname=datapath,
        dtformat=('%Y-%m-%d %H:%M:%S%Z'),
        # timestamp=0, I don't think you need this. 
        timeframe=bt.TimeFrame.Minutes, 
        compression=60,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1
    )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM