为什么我使用pandas Series.asfreq获得is_monotonic断言错误

时间:2012-07-11 00:09:49

标签: python pandas

我有一个Python函数historical_data,它从雅虎财经中提取每日历史价格和股息数据,并将其输出到大熊猫DataFrame

>>> nlsn = y.historical_data('NLSN')
>>> nlsn
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 366 entries, 2012-07-10 00:00:00 to 2011-01-27 00:00:00
Data columns:
Open         366  non-null values
High         366  non-null values
Low          366  non-null values
Close        366  non-null values
Volume       366  non-null values
Adj Close    366  non-null values
Dividends    366  non-null values
dtypes: float64(6), int64(1)
>>> nlsn['Adj Close']
Date
2012-07-10    26.77
2012-07-09    26.77
2012-07-06    26.64
2012-07-05    26.56
2012-07-03    26.57
...
2011-02-01    25.75
2011-01-31    26.07
2011-01-28    25.00
2011-01-27    25.40
Name: Adj Close, Length: 366

我只想持续存储每日数据(相对于必须每天,每月,每周等存储)。但是,以下每日每月转换似乎不起作用:

>>> nlsn['Adj Close'].asfreq('M', method='bfill')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/michael/Projects/envs/fintools32/lib/python3.2/site-packages/pandas/core/generic.py", line 156, in asfreq
    return asfreq(self, freq, method=method, how=how)
  File "/home/michael/Projects/envs/fintools32/lib/python3.2/site-packages/pandas/tseries/resample.py", line 329, in asfreq
    return obj.reindex(dti, method=method)
  File "/home/michael/Projects/envs/fintools32/lib/python3.2/site-packages/pandas/core/series.py", line 2053, in reindex
    level=level, limit=limit)
  File "/home/michael/Projects/envs/fintools32/lib/python3.2/site-packages/pandas/core/index.py", line 791, in reindex
    limit=limit)
  File "/home/michael/Projects/envs/fintools32/lib/python3.2/site-packages/pandas/core/index.py", line 719, in get_indexer
    assert(self.is_monotonic)
AssertionError

将这些股票价格汇总为每月的正确方法是什么?

我尝试了什么

我尝试了所有不同的method参数(ffill,pad,bfill),所有这些参数似乎都会引发相同的断言错误。

我尝试检查源代码index.py,但似乎有一个策略模式,其中有问题的类将is_monotonic委托给其_engine属性,而我不能找到实际分配_engine属性的位置。

1 个答案:

答案 0 :(得分:2)

尝试nlsn['Adj Close'][::-1].asfreq('M', method='ffill')

如果你能让你的函数返回递增的DatetimeIndex,那么你可以在这里跳过额外的排序。