Pd.series rolling function for the "Predicting stock market project"

Hi all!

I am working on the “Predicting Stock Prices project” https://app.dataquest.io/m/65/guided-project%3A-predicting-the-stock-market/3/generating-indicators and I need to create indicators that represent the average price from the past 5, 30 or 365 days for each row, in iterative way. I’d rather use the suggested rolling function than a for loop, but I am not sure how to specify the inputs, given that I want the mean from the “Close” column, but the windows are based on the “Date” column. Anyone who solved this task and would like to help?

Thanks in advance!

Hey there @izabelcvetkovic,

I only just recently completed this project myself! Though I did it on Jupyter Notebook. Here’s my code if you’d like to reference it. I tried to be pretty thorough with the comments and explanatory text in my project, so it should be easy to follow.

The way I handled the “rolling” was like so, for my choice of 6 new features:

# Calculating the means:
mean_5 = df_sorted['Close'].rolling(window=5).mean().shift()
mean_30 = df_sorted['Close'].rolling(window=30).mean().shift()
mean_100 = df_sorted['Close'].rolling(window=100).mean().shift()

# Calculating the standard deviations:
std_5 = df_sorted['Close'].rolling(window=5).std().shift()
std_30 = df_sorted['Close'].rolling(window=30).std().shift()
std_100 = df_sorted['Close'].rolling(window=100).std().shift()

Then I just assigned the variables generated above into new columns:

df_sorted['mean_5'] = mean_5
df_sorted['mean_30'] = mean_30
df_sorted['mean_100'] = mean_100
df_sorted['std_5'] = std_5
df_sorted['std_30'] = std_30
df_sorted['std_100'] = std_100

Also, to slightly correct your phrasing here:

The windows aren’t based on the Date column per se - the Date column is merely used to sort the Dataframe in the right order.

The window parameter in the rolling function then counts the specified number of values in the column before (and including) the current one!

2 Likes

Thanks for the extensive explanation! :slight_smile: