Skip to content

Stock Market Analysis (Finance)

Given daily stock prices, compute:

  • Daily returns
  • Rolling averages
  • Volatility
  • Compare multiple stocks
diagram Stock analysis pipeline mermaid
From raw daily prices to a smoothed trend with a volatility measure.
  • date, close (and optionally open/high/low/volume)
Load prices
import pandas as pd
 
df = pd.read_csv("data/stock.csv")
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df = df.sort_values("date")
print(df.head())
Returns
df["return"] = df["close"].pct_change()
print(df[["date", "close", "return"]].head(10))
Moving averages
df["ma20"] = df["close"].rolling(20).mean()
df["ma50"] = df["close"].rolling(50).mean()
Plot price + MA
import matplotlib.pyplot as plt
 
plt.figure(figsize=(10, 4))
plt.plot(df["date"], df["close"], label="close")
plt.plot(df["date"], df["ma20"], label="MA20")
plt.plot(df["date"], df["ma50"], label="MA50")
plt.title("Price and moving averages")
plt.legend()
plt.xticks(rotation=20)
plt.tight_layout()
plt.show()
Volatility
df["volatility_20"] = df["return"].rolling(20).std()
sketch Close price with moving averages p5.js
The raw close price (blue) vs its smoother 20-day (amber) and 50-day (green) averages.

Summarize:

  • Trend periods
  • High-volatility periods and possible reasons
  • Compare performance across stocks (optional)

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading