【问题标题】:How to Convert Tick by Tick Data to OHLC Candlestick Data with Python?如何使用 Python 将 Tick by Tick 数据转换为 OHLC 烛台数据?
【发布时间】:2021-07-16 18:39:53
【问题描述】:

我如何通过分时数据重新采样我的分时以获取烛台 OHLC 数据。

这是我的数据在 pandas DataFrame 中的样子。

    Timestamp       Price
0  1626459705  278.989978
1  1626459695  279.437975
2  1626459486  279.866868
3  1626459317  280.225627
4  1626459149  280.469473
5  1626458918  280.845010
6  1626458886  282.348605
7  1626458866  281.976074
8  1626458380  280.420801
9  1626458056  280.838577

如何通过使用 pandas 重新采样来获得 1 分钟内的 OHLC 烛台数据?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    以下是另一种解决方案:

    df = df.assign(Timestamp = pd.to_datetime(df['Timestamp'],unit='s')).set_index('Timestamp')
    df.resample('10min')['Price'].ohlc()
    

    【讨论】:

    • 10min 也像@Ben.T 的回答一样用于重采样。
    • 谢谢。为什么你的脚本和@Ben.T 的结果不同?它们提供不同的 OHLC 数据。
    • 在我的测试中它们是相同的。
    • Ben.T 的答案中的sort_index 可能也会导致您的现实生活数据集出现差异,但在提供的示例中,我们的答案期待给出相同的结果。
    • 是的!这也是一种简单的方法@Ben.T
    【解决方案2】:

    一种方法是将时间戳列转换为带有to_datetimeset_index 的日期时间列。然后选择价格列,resample 使用您想要的频率,agg 使用不同的 first-max-min-last。

    nb_minutes = 10 # change to 1 for your real case
    res = (
        df.set_index(pd.to_datetime(df['Timestamp'], unit='s'))
          .sort_index() # to ensure the chronological order
          ['Price'].resample(f'{nb_minutes}T') 
          .agg( {'open':'first', 'high':max, 'low':min, 'close':'last'} )
          .unstack(level=0) # to make it a dataframe
    )
    print(res)
                               open        high         low       close
    Timestamp                                                          
    2021-07-16 17:50:00  280.838577  280.838577  280.420801  280.420801
    2021-07-16 18:00:00  281.976074  282.348605  280.845010  280.845010
    2021-07-16 18:10:00  280.469473  280.469473  279.866868  279.866868
    2021-07-16 18:20:00  279.437975  279.437975  278.989978  278.989978
    

    【讨论】:

    • 谢谢。为什么你的脚本和@rhug123 的结果不同?它们提供不同的 OHLC 数据。
    • @TechyGuy 正如 rhug123 在 cmets 中所说,使用您的样本数据,两种方法的结果相同!
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 2013-01-01
    • 2013-08-06
    • 1970-01-01
    相关资源
    最近更新 更多