gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:13:25 24 4
gpt4 key购买 nike

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

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

我只想绘制数据的滚动平均值。为什么会这样?

最佳答案

为什么不直接使用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

关于python - 如何绘制股票数据的滚动平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35328399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com