Skip to content
Advertisement

How to plot simple moving averages with stock data

I am trying to plot simple moving averages (SMA) using Apple’s stock price. I have lines below:

JavaScript

But the plotting isn’t successful.

enter image description here

What did I do wrong, and how I can correct it?

enter image description here

Advertisement

Answer

From the code you posted, it seems as though you didn’t set the index of the dataframe after loading the data from the csv file. pd.read_csv does not by default assume the first column is the index.

If you had tried data.head() you would have noticed that Pandas adds a default index:

JavaScript

Thus, none of the subsequent df.loc methods found any data that matched the dates you provide as strings.

The following worked for me.

I replaced the line

JavaScript

with

JavaScript

and this is the output I get:

enter image description here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement