我想将1分钟的olhc日内股票数据(存在于Pandas数据框中)转换为更高时间范围的olhc数据,如5分钟、10分钟、15分钟的olhc数据

2024-05-17 17:36:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一分钟的日内股票olhc烛光数据(在熊猫数据框中)。 我想将1分钟olhc日内股票数据(显示在熊猫数据框中)转换为更高时间范围的olhc数据,如5分钟、10分钟、15分钟olhc数据

     open     low    high   close  volume Adj_Close
2020-07-24 13:12:00  191.00  190.95  191.00  190.95   21131    190.95
2020-07-24 13:11:00  190.80  190.80  190.95  190.85   88030    190.85
2020-07-24 13:10:00  191.25  190.80  191.25  190.80  163046    190.80
2020-07-24 13:09:00  191.15  191.15  191.20  191.20   71910    191.20
2020-07-24 13:08:00  191.10  191.05  191.20  191.10  100514    191.10
...                     ...     ...     ...     ...     ...       ...
2020-07-23 12:51:00  194.90  194.75  194.90  194.75   44430    194.75
2020-07-23 12:50:00  194.85  194.75  194.85  194.85  116263    194.85
2020-07-23 12:49:00  194.85  194.85  194.95  194.95   34569    194.95
2020-07-23 12:48:00  194.70  194.70  194.85  194.85  154293    194.85
2020-07-23 12:47:00  194.95  194.80  194.95  194.80  145786    194.80

Tags: 数据close时间openlow股票highvolume
2条回答

您的问题缺少关于应该使用什么作为聚合函数的信息。在我的回答中,我假设您想取volume和其他列的平均值。
您可以使用df.resample。您需要有一个带有日期时间索引的数据帧。这意味着使用datetime对象而不是多级字符串作为数据帧的索引。对于timeseries数据,这通常是一个好主意。
一旦有了datetime索引,您只需调用dataframe的resample方法并说明您希望如何聚合数据

def resample_stock_data(df, timedelta):
    """Resample stock data to a timedelta.
    
    Args:
        df (pd.DataFrame): DataFrame of stock data to resample
        timedelta: DateOffset, TimeDelta or str to resample to.
    Returns:
        pd.DataFrame: Resampled dataframe"""
        
    # Create a datetime index
    df = df.reset_index()
    df = df.set_index(pd.to_datetime(df['level_0'] + ' ' + df['level_1']))
    df = df.drop(['level_0', 'level_1'], axis=1)
    # Resample data
    olhc = df.drop('volume', axis=1)
    olhc = olhc.resample(timedelta).mean()
    volume = df['volume']
    volume = volume.resample(timedelta).sum()
    resampled = pd.concat([olhc, volume], axis=1)
    return resampled

resampled_05m = resample_stock_data(df, '5min')
resampled_10m = resample_stock_data(df, '10min')
resampled_15m = resample_stock_data(df, '15min')

agg()函数允许您为特定于列的聚合传入函数字典。我们将创建两个字典:一个用于聚合逻辑,另一个用于重命名列:

def resample_stock_data(df, timedelta):
    # make a copy
    df = df.copy()

    # convert index to datetime
    df.index = pd.to_datetime(df.index)

    # sort the index (evidently required by resample())
    df = df.sort_index()

    aggregation_dict = {
        'volume': 'mean', 
         'open': 'sum', 
         'high': 'sum',
         'low': 'sum',
         'close': 'sum',
         'Adj_Close': 'sum'
    }

    rename_dict = {
        'open': 'first',
        'high': 'max_price',
        'low': 'min_price',
        'close': 'last_price',
        'volume': 'vol (shares)',
        'Adj_Close': 'last',
    }


    return (df
      .resample(timedelta)
      .agg(aggregation_dict)
      .rename(columns=rename_dict)
    )

相关问题 更多 >