Moving Average Algorithm Examples: Crash Course in Forecasting

Ananthakrishnan Harikumar
AI Skunks
Published in
2 min readMar 31, 2023

Moving Average on historical_stock_prices

Loading the Dataset

import pandas as pd

# Load the temperature data
df = pd.read_csv('historical_stock_prices.csv')

Data Exploration

df.head()

Filter data for a specific company and time period

company = 'AAPL'
start_date = '2010-01-01'
end_date = '2020-12-31'
mask = (df['ticker'] == company) & (df['date'] >= start_date) & (df['date'] <= end_date)
data = df.loc[mask]
data

Calculate the Moving Average

window_size = 5 
data['Moving_Average'] = data['adj_close'].rolling(window_size).mean()

Print the data with Moving Average

print(data[['date', 'adj_close', 'Moving_Average']].tail())

Moving Average on COVID-19 World Vaccination Progress

Loading the Dataset

import pandas as pd

# Load the vaccination data
df = pd.read_csv('country_vaccinations.csv')

Data Exploration

df.head()

Filter data for a specific country and time period

country = 'United States' # Change this value to select a different country
start_date = '2021-01-01'
end_date = '2022-12-31'
mask = (df['country'] == country) & (df['date'] >= start_date) & (df['date'] <= end_date)
data = df.loc[mask]
data

Calculate the Moving Average

window_size = 7 # Change this value to adjust the window size
data['Moving_Average'] = data['people_vaccinated'].rolling(window_size).mean()

Print the data with Moving Average

print(data[['date', 'people_vaccinated', 'Moving_Average']].tail())

--

--

Ananthakrishnan Harikumar
AI Skunks
0 Followers
Writer for

A common man who believes in love and compassion more than religion and boundaries.