如何绘制股票数据的滚动均值?

时间:2016-02-11 00:02:01

标签: python pandas matplotlib

我能够使用以下代码绘制数据:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

url = "http://real-chart.finance.yahoo.com/table.csv?s=YHOO&a=03&b=12&c=2006&d=01&e=9&f=2016&g=d&ignore=.csv"

df = pd.read_csv(url)
df.index = df["Date"]
df.sort_index(inplace=True)

df['Adj Close'].plot()
plt.show()

但现在我想计算数据的滚动平均值并绘制出来。这就是我尝试过的:

pd.rolling_mean(df.resample("1D", fill_method="ffill"), window=3, min_periods=1)
plt.plot()

但这给了我错误:

Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex

我想要做的就是绘制数据的滚动均值。为什么会这样?

2 个答案:

答案 0 :(得分:3)

为什么不使用datareader

import pandas.io.data as web

aapl = web.DataReader("aapl", 'yahoo', '2010-1-1')['Adj Close']
aapl.plot(title='AAPL Adj Close');pd.rolling_mean(aapl, 50).plot();pd.rolling_mean(aapl, 200).plot()

enter image description here

为了更好地控制绘图:

aapl = web.DataReader("aapl", 'yahoo', '2010-1-1')['Adj Close']
aapl.name = 'Adj Close'
aapl_50ma = pd.rolling_mean(aapl, 50)
aapl_50ma.name = '50 day MA'
aapl_200ma = pd.rolling_mean(aapl, 200)
aapl_200ma.name = '200 day MA'
aapl.plot(title='AAPL', legend=True);aapl_50ma.plot(legend=True);aapl_200ma.plot(legend=True)

enter image description here

答案 1 :(得分:1)

Pandas无法正确解析您的日期,因为在加载CSV时默认情况下并非如此。 parse_dates要么需要True,要解析索引,要么需要解析列号列表。它将它们作为字符串加载。此外,read_csv允许自动设置索引。以下内容适用:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

url = "http://real-chart.finance.yahoo.com/table.csv?s=YHOO&a=03&b=12&c=2006&d=01&e=9&f=2016&g=d&ignore=.csv"

df = pd.read_csv(url, parse_dates=True, index_col=0)
#df.index = df["Date"]
df.sort_index(inplace=True)

df['Adj Close'].plot()
plt.show()

然后

rm = pd.rolling_mean(df.resample("1D", fill_method="ffill"), window=3, min_periods=1)
rm['Adj Close'].plot()

然而,后一段代码正在绘制给我一个奇怪的错误,我需要研究。请注意,在奇数情况下,在jupyter / ipython中具有内联绘图的笔记本this may give an error if you don't use the matplotlib/pylab magic before importing matplotlib