Python Central HubSign in

Data Analytics with Python / Phase 10: Data Analytics Projects

Stock Market Analysis (Finance)

Analyze stock price time series - returns, moving averages, volatility, and simple comparisons.

Goal

Given daily stock prices, compute:

  • Daily returns
  • Rolling averages
  • Volatility
  • Compare multiple stocks

Analysis pipeline

diagram Stock analysis pipeline mermaid
From raw daily prices to a smoothed trend with a volatility measure.

Dataset columns

  • date, close (and optionally open/high/low/volume)

Step 1: Load and parse

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

Step 2: Daily returns

Python
df["return"] = df["close"].pct_change()
print(df[["date", "close", "return"]].head(10))

Step 3: Moving averages

Python
df["ma20"] = df["close"].rolling(20).mean()
df["ma50"] = df["close"].rolling(50).mean()

Step 4: Plot

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

Step 5: Volatility (rolling std)

Python
df["volatility_20"] = df["return"].rolling(20).std()

Visualize it

sketch Close price with moving averages p5.js
The raw close price (blue) vs its smoother 20-day (amber) and 50-day (green) averages.

Deliverable

Summarize:

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

Check your understanding

quizCheck yourself
  1. What does df["close"].pct_change() compute?

    Show answer

    A — The percentage change from the previous day's close, the daily return — It is a vectorized comparison of today to yesterday, with no loop needed.

  2. Why sort_values("date") before computing returns and rolling windows?

    Show answer

    A — Both depend on rows being in chronological order — pct_change and rolling use the previous rows, so unordered data gives wrong results.

  3. How is volatility_20 defined in the project?

    Show answer

    A — The 20-day rolling standard deviation of daily returns — Volatility is measured as the spread of returns, using rolling(20).std() on return, not on price.

  4. What does ma50 (rolling(50).mean()) reveal compared with ma20?

    Show answer

    A — A smoother, slower-moving long-term trend — A longer window averages more days, so it reacts more slowly and smooths more.

🧪 Try It Yourself

Exercise 1 – Daily returns

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Moving average

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Rolling volatility

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did