Stock Market Analysis (Finance)
Goal
Given daily stock prices, compute:
- Daily returns
- Rolling averages
- Volatility
- Compare multiple stocks
Dataset columns
datedate,closeclose(and optionally open/high/low/volume)
Step 1: Load and parse
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())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())Step 2: Daily returns
Returns
df["return"] = df["close"].pct_change()
print(df[["date", "close", "return"]].head(10))Returns
df["return"] = df["close"].pct_change()
print(df[["date", "close", "return"]].head(10))Step 3: Moving averages
Moving averages
df["ma20"] = df["close"].rolling(20).mean()
df["ma50"] = df["close"].rolling(50).mean()Moving averages
df["ma20"] = df["close"].rolling(20).mean()
df["ma50"] = df["close"].rolling(50).mean()Step 4: Plot
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()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()Step 5: Volatility (rolling std)
Volatility
df["volatility_20"] = df["return"].rolling(20).std()Volatility
df["volatility_20"] = df["return"].rolling(20).std()Deliverable
Summarize:
- Trend periods
- High-volatility periods and possible reasons
- Compare performance across stocks (optional)
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
