Data Science project 10
Stock Market Analysis Data Science Project
Build a complete stock market analysis workflow with reproducible Python code, traceable calculations, validation checks, and honest limitations.
Explore Data Science training in VizagView all project ideas
Analysis question
How are total return, annualised historical volatility, and maximum drawdown calculated from an ordered positive-price series?
Dataset
A reproducible synthetic business-day price series by default, with an optional local CSV loader for properly sourced Date and Close columns.
Requirements
- Python 3.10 or later
- A terminal or command prompt
python -m pip install numpy pandas- About 45-60 minutes to build and review
Method and data checks
Validate and sort prices, calculate daily percentage returns, build a running peak, derive drawdowns, and summarise three descriptive historical metrics.
- Dates parse successfully and duplicates are removed
- Close values must be positive
- Volatility uses the standard 252-session annualisation convention
- Maximum drawdown is calculated from prior running peaks
Complete Python code
Save the program as ds_stock_market_analysis.py. The dataset generator or loader, analysis functions, output, and reproducibility controls are included.
"""Historical-price analysis workflow with a synthetic default series."""
from __future__ import annotations
import argparse
import numpy as np
import pandas as pd
def make_demo_prices(days: int = 500, seed: int = 42) -> pd.DataFrame:
rng = np.random.default_rng(seed)
returns = rng.normal(0.00035, 0.014, days)
close = 100 * np.exp(np.cumsum(returns))
return pd.DataFrame({"date": pd.bdate_range("2024-01-01", periods=days), "close": close})
def load_prices(csv_path: str | None = None) -> pd.DataFrame:
data = make_demo_prices() if csv_path is None else pd.read_csv(csv_path)
names = {column.lower(): column for column in data.columns}
if not {"date", "close"}.issubset(names):
raise ValueError("CSV must contain Date and Close columns")
result = data.rename(columns={names["date"]: "date", names["close"]: "close"})[["date", "close"]]
result["date"] = pd.to_datetime(result["date"], errors="raise")
result["close"] = pd.to_numeric(result["close"], errors="raise")
if (result["close"] <= 0).any():
raise ValueError("Close prices must be positive")
return result.sort_values("date").drop_duplicates("date").reset_index(drop=True)
def analyse_prices(data: pd.DataFrame) -> dict[str, float]:
price = data.copy()
price["daily_return"] = price["close"].pct_change()
price["drawdown"] = price["close"] / price["close"].cummax() - 1
return {"total_return": float(price["close"].iloc[-1] / price["close"].iloc[0] - 1), "annualized_volatility": float(price["daily_return"].std() * np.sqrt(252)), "maximum_drawdown": float(price["drawdown"].min())}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--csv", help="Optional CSV with Date and Close columns")
args = parser.parse_args()
metrics = analyse_prices(load_prices(args.csv))
print({key: f"{value:.2%}" for key, value in metrics.items()})
print("Descriptive education only — not a forecast, trading signal, or investment advice.")
if __name__ == "__main__":
main()
Run the project
- Create and activate a virtual environment.
- Install dependencies with
python -m pip install numpy pandas. - Run
python ds_stock_market_analysis.py. - Reconcile row counts and totals before interpreting patterns.
- Read the limitations before substituting any real dataset.
Expected analytical output
Total return, annualised historical volatility, and maximum drawdown for the supplied series.
Interpretation and responsible-use limits
Education only. Synthetic or historical statistics are not a forecast, trading signal, investment recommendation, risk guarantee, or substitute for licensed financial advice.
Ways to extend the project
Add adjusted prices, dividend treatment, benchmark comparison, rolling windows, missing-session review, confidence intervals, and fully documented data provenance.
Continue learning Data Science
Try the next project, return to the Softenant project library, or explore the Data Science course in Vizag for guided data cleaning, analysis, visualisation, and portfolio feedback.