我如何将 m1 OHLC 数据转换为 m15 或 pandas 中的任何时间范围 OHLC?

How do i convert m1 OHLC data to m15 or any timeframe OHLC in pandas?

我正在尝试使用 pandas 重采样函数将 M1 OHLC 数据转换为 M15,但没有成功,这就是我得到的:

df = pd.read_csv("EURUSD.csv")
df = df.set_index("DatetimeIndex")
print("\tDone!")

df = df.resample('1H').agg({'Open': 'first', 
                            'High': 'max', 
                            'Low': 'min', 
                            'Close': 'last'})

我收到错误

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

我尝试删除 .set_index,但它给出了另一个错误,提示无法执行 RangeIndex

我的数据是这样的:

我强烈猜测问题出在索引的数据类型上。 CSV 文件不存储数据类型,pandas 在查找类型时必须进行一些猜测。

因为pandas无法确定第一列有日期时间值,所以它认为它是一个字符串;因此,当您将其设置为索引时,它会为您创建一个原始索引(因此错误中的 Index 类型,而不是 DatetimeIndex)您希望将其转换为正确的格式 while/after read_csv 调用并在将其设置为索引之前。

请参考this answer to find out about how to convert the format after reading the CSV file. If you wanna do the data conversion while reading the CSV (which is nicer and takes less time/memory) take a look at the docsparse_dates参数向下

P.S:提出更好问题的提示,您可以像这样共享部分数据以提供最小的可重现示例:

from io import StringIO
df = pandas.read_csv(StringIO("""A,B,C
                                 a,b,c
                                 d,,f"""))

很多时候,您可能会在开始 SO 之前尝试制作最小示例时找到问题的答案!