【问题标题】:How to calculate the most common time for max value per day of week in pandas如何计算熊猫一周中每天最大值的最常见时间
【发布时间】:2020-12-14 09:41:00
【问题描述】:

使用 python 中的 yahoo Finance 包,我可以下载相关数据以显示 OCHL。我的目标是找出一天中股票平均最高的时间。

这是下载数据的代码:

import yfinance as yf
import pandas as pd

df = yf.download(
        tickers = "APPL",
        period = "60d",
        interval = "5m",
        auto_adjust = True,
        group_by = 'ticker',
        prepost = True,
    )

maxTimes = df.groupby([df.index.month, df.index.day, df.index.day_name()])['High'].idxmax()

这给了我这样的东西:

Datetime  Datetime  Datetime 
6         2         Tuesday     2020-06-02 19:45:00-04:00
          3         Wednesday   2020-06-03 15:50:00-04:00
          4         Thursday    2020-06-04 10:30:00-04:00
          5         Friday      2020-06-05 11:30:00-04:00
...
8         3         Monday      2020-08-03 14:40:00-04:00
          4         Tuesday     2020-08-04 18:10:00-04:00
          5         Wednesday   2020-08-05 11:10:00-04:00
          6         Thursday    2020-08-06 16:20:00-04:00
          7         Friday      2020-08-07 15:50:00-04:00
Name: High, dtype: datetime64[ns, America/New_York]

认为我创建的 maxTimes 对象应该给我一天中最高点发生的时间,但是我需要的是:

Monday    12:00
Tuesday   13:25
Wednesday 09:35
Thurs     16:10
Fri       12:05

有谁能帮我确定如何让我的数据看起来像这样?

【问题讨论】:

    标签: python pandas stock yfinance


    【解决方案1】:

    这应该可行:

    import yfinance as yf
    import pandas as pd
    
    df = yf.download(
            tickers = "AAPL",
            period = "60d",
            interval = "5m",
            auto_adjust = True,
            group_by = 'ticker',
            prepost = True,
        )
    
    maxTimes = df.groupby([df.index.month, df.index.day, df.index.day_name()])['High'].idxmax()
    
    # Drop date
    maxTimes = maxTimes.apply(lambda x: x.time())
    
    # Drop unused sub-indexes
    maxTimes = maxTimes.droplevel(level=[0,1])
    
    # To seconds
    maxTimes = maxTimes.apply(lambda t: (t.hour * 60 + t.minute) * 60 + t.second)
    
    # Get average
    maxTimes =  maxTimes.groupby(maxTimes.index).mean()
    
    # Back to time
    maxTimes = pd.to_datetime(maxTimes, unit='s').apply(lambda x: x.time())
    
    print (maxTimes)
    
    '''
    Output:
    
    Datetime
    Friday       11:59:32.727272
    Monday              14:15:00
    Thursday            13:21:40
    Tuesday             10:35:00
    Wednesday           11:53:45
    Name: High, dtype: object
    
    '''
    

    【讨论】:

    • 您是英雄!我唯一的问题是原始项目中的时区是东部(UTC -4) - 你知道输出在哪个时区吗?
    • 和源数据一样,所以是UTC-4。
    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多