[Python] Some csv file can't import data into bt.feeds.PandasData?

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I solved some of the previous problems, but I encountered a new problem. Only the first of my multiple csv files could be imported into data and read, while the other files could not complete the process, they were almost the same. The following is the code that can be replicated after I simplified it

    import datetime
    from datetime import timedelta, datetime
    import ccxt
    import backtrader as bt
    import pandas as pd
    import os

    class TestStrategy(bt.Strategy):

    def __init__(self):#计算指标
    self.dataclose=self.datas[0].open
    print(len(self.datas[0]))
    def next(self):#调用指标和策略
    self.log('dataclose,%.2f'%self.dataclose[0])
    print('1')
    def log(self,text):
    dt=self.datas[0].datetime.date(0)
    print('%s %s'%(dt.isoformat(),text))
    print(1)

    if __name__=='__main__':
    cerebro = bt.Cerebro()
    since_time = datetime(year=2024, month=12, day=1)
    to_time = datetime(year=2025, month=4, day=1)
    since_time_1 = datetime(year=2024, month=12, day=12, hour=17, minute=30, second=0)

    file_path = "E:/PycharmProjects/PythonProject/backtrader/data/2025-12-12 17:30:00.csv"#efficient one
    file_path_1 = "E:/PycharmProjects/PythonProject/backtrader/data/2025-01-16 22:00:00.csv" #others can't
    df = pd.read_csv(file_path, parse_dates=['datetime']) # 将 datetime 列解析为日期时间类型
    df.index = pd.to_datetime(df.datetime)
    df['openintrest'] = 0
    # 对dataframe的数据列进行一个整合
    df = df[['open', 'high', 'low', 'close', 'volume', 'openintrest']]
    print(df)
    data = bt.feeds.PandasData(
    dataname=df,
    fromdate=since_time,
    todate=since_time_1,
    )

    cerebro.adddata(data)
    cerebro.addstrategy(TestStrategy)
    cerebro.run()


    Attached is a screenshot of the first few lines of the two csv filesenter image description here

    enter image description here

    enter image description here

    Continue reading...

Compartilhe esta Página