Python for Stock Market Data Analysis: A Beginner's Walkthrough
Learn stock market data analysis in Python with pandas: load price data, calculate returns, moving averages, volatility and drawdown, find crossovers and plot charts.
Python, together with the pandas library, is the most popular toolkit for analysing financial data. In this walkthrough, you will load daily stock prices, calculate common metrics and draw a chart. It assumes basic Python knowledge.
Setting up
Install the libraries with pip:
pip install pandas matplotlib
You need a CSV file of daily prices with columns date, open, high, low, close and volume. Use data from a source whose terms allow it, and make sure prices are adjusted for splits and bonuses.
Loading and inspecting the data
import pandas as pd
df = pd.read_csv("prices.csv", parse_dates=["date"])
df = df.sort_values("date").set_index("date")
print(df.head())
print(df.isna().sum()) # check for missing values
Sorting by date and checking for missing values should always be your first step.
Calculating daily returns
df["return"] = df["close"].pct_change()
# Cumulative return: compound the daily returns
df["cum_return"] = (1 + df["return"]).cumprod() - 1
pct_change() computes the percentage change from the previous row, which is the previous trading day.
Moving averages
df["sma_20"] = df["close"].rolling(20).mean()
df["sma_50"] = df["close"].rolling(50).mean()
A rolling mean smooths out daily noise. The first 19 and 49 rows will be empty because there is not yet enough history.
Finding moving-average crossovers
df["above"] = (df["sma_20"] > df["sma_50"]).astype(int)
df["cross"] = df["above"].diff()
bullish = df[df["cross"] == 1] # 20-day crosses above 50-day
bearish = df[df["cross"] == -1] # 20-day crosses below 50-day
print(bullish.index)
This is a classic technical signal. It is useful for learning, but on its own it is not a reliable trading strategy.
Volatility and drawdown
daily_vol = df["return"].std()
annual_vol = daily_vol * (252 ** 0.5)
running_peak = df["close"].cummax()
drawdown = df["close"] / running_peak - 1
max_drawdown = drawdown.min()
print(f"Annualised volatility: {annual_vol:.1%}")
print(f"Maximum drawdown: {max_drawdown:.1%}")
Annualised volatility uses roughly 252 trading days per year. Maximum drawdown shows the worst peak-to-trough fall in the period.
Plotting the chart
import matplotlib.pyplot as plt
ax = df[["close", "sma_20", "sma_50"]].plot(figsize=(10, 5))
ax.set_title("Close price with 20- and 50-day moving averages")
ax.set_ylabel("Price (INR)")
plt.tight_layout()
plt.show()
Comparing several stocks
prices = pd.read_csv("multi.csv", parse_dates=["date"])
wide = prices.pivot(index="date", columns="symbol", values="close")
returns = wide.pct_change()
print(returns.corr().round(2)) # correlation matrix
Pivoting to a wide table with one column per symbol makes it easy to compare returns and calculate correlations.
Next steps
- Wrap the steps into functions so you can analyse any stock.
- Add more indicators, such as RSI.
- Build a small dashboard to present results.
Before trusting any result, read about the common pitfalls in market data. And if you enjoy this kind of work, the Data Analyst Internship at Bluestock could be a good fit.
This walkthrough is for learning data analysis and is not investment advice.
Bluestock Fintech 55 mins ago