3

我想将每日(ohlcv)重新采样/转换为每周(ohlcv)。熊猫可以做到这一点吗?

字典格式的样本数据如下(1周每日数据):

   {'High': {<Timestamp: 2007-03-02 00:00:00>: 1384.5,
  <Timestamp: 2007-03-05 00:00:00>: 1373.0,
  <Timestamp: 2007-03-06 00:00:00>: 1378.75,
  <Timestamp: 2007-03-07 00:00:00>: 1381.75,
  <Timestamp: 2007-03-08 00:00:00>: 1388.75},
 'Last': {<Timestamp: 2007-03-02 00:00:00>: 1365.0,
  <Timestamp: 2007-03-05 00:00:00>: 1351.5,
  <Timestamp: 2007-03-06 00:00:00>: 1374.5,
  <Timestamp: 2007-03-07 00:00:00>: 1372.0,
  <Timestamp: 2007-03-08 00:00:00>: 1384.5},
 'Low': {<Timestamp: 2007-03-02 00:00:00>: 1364.25,
  <Timestamp: 2007-03-05 00:00:00>: 1350.5,
  <Timestamp: 2007-03-06 00:00:00>: 1362.0,
  <Timestamp: 2007-03-07 00:00:00>: 1370.75,
  <Timestamp: 2007-03-08 00:00:00>: 1369.25},
 'Open': {<Timestamp: 2007-03-02 00:00:00>: 1378.5,
  <Timestamp: 2007-03-05 00:00:00>: 1356.75,
  <Timestamp: 2007-03-06 00:00:00>: 1365.25,
  <Timestamp: 2007-03-07 00:00:00>: 1374.0,
  <Timestamp: 2007-03-08 00:00:00>: 1370.0},
 'Volume': {<Timestamp: 2007-03-02 00:00:00>: 1706906,
  <Timestamp: 2007-03-05 00:00:00>: 1984041,
  <Timestamp: 2007-03-06 00:00:00>: 1397911,
  <Timestamp: 2007-03-07 00:00:00>: 1255484,
  <Timestamp: 2007-03-08 00:00:00>: 798237}}
4

3 回答 3

9

将数据放入 DataFrame 后,您可以执行以下操作:

 ohlc_dict = {
    'Open':'first',
    'High':'max',
    'Low':'min',
    'Close':'last',
    'Volume':'sum'
    }

DataFrame.resample('W-Fri', how=ohlc_dict)

这将为您提供周五结束的一周的 ohlc 数据。

于 2013-02-09T02:52:44.123 回答
2

示例改编自官方文档:

# Weekly means
In [1305]: ts.resample('W', how='mean')
Out[1305]: 
2011-01-01   -0.319569
2011-01-02   -0.337703
2011-01-03    0.117258
Freq: W

'W-SUN'您可以使用例如或将日期偏移到一周中的特定日期'W-MON'

链接到文档

于 2013-02-08T16:12:51.310 回答
2

在 pandas 版本之后0.18.0,该how参数在 function 中被弃用resample,因此建议的解决方案变为:

ohlc_dict = {
    'Open':'first',
    'High':'max',
    'Low':'min',
    'Close':'last',
    'Volume':'sum'
    }

df = df.resample('W').agg(ohlc_dict)
于 2020-02-28T04:04:55.067 回答