我有一个Python函数historical_data
,可从Yahoo Finance中提取每日历史价格和股息数据,并将其输出到熊猫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
参数(填充,填充,填充),所有这些似乎都引发了相同的断言错误。我尝试检查源代码
index.py
,但是似乎存在一种有效的策略模式,其中所涉及的类将is_monotonic
委托给其_engine
属性,而我找不到真正的_engine
属性在哪里已分配。 最佳答案
尝试nlsn['Adj Close'][::-1].asfreq('M', method='ffill')
并且,如果可以让您的函数返回升序DatetimeIndex,则可以跳过此处的额外排序。
关于python - 为什么我使用Pandas Series.asfreq收到is_monotonic断言错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11423790/