How to build a moving average of stock data?

I was able to display the data using the code below:

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() 

But now I want to calculate the moving average of the data and the graph. This is what I tried:

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

But this gives me an error:

 Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex 

All I want to do is draw a moving average of the data. Why is this happening?

+5
source share
2 answers

Pandas does not correctly process your dates, since by default it does not execute when CSV files are uploaded. parse_dates must either be True to parse the index, or a list of column numbers for parsing. Instead, they load them as strings. In addition, read_csv allows read_csv to automatically set the index. The following will work:

 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() 

And then

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

However, this last bit of code is currently displaying and giving me an odd error that I need to study. Please note that in odd cases on jupyter / ipython laptops with integrated graphics, this can lead to an error if you do not use the matplotlib / pylab matte mask before importing matplotlib .

+1
source

Why don't you just use a 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

To get more control over the graphics:

 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

+3
source

Source: https://habr.com/ru/post/1242743/


All Articles