BLOG

Behind the numbers.

Code examples, market analysis, and data quality deep-dives.

Is MSTR a Leveraged Bitcoin Proxy? Rolling Beta Analysis in Python
Is Micron's Memory Cycle Recovering? Inventory and Margin Forecasting in Python
Which Sectors Work When Bonds Rally? Rate-Sensitive Rotation in Python
Do One-Month Price Extremes Reverse? Signal Evaluation in Python
Do Low-Volatility S&P 500 Stocks Reduce Drawdowns? Factor Test in Python
Is AI Capex Paying Back Fast Enough? Revenue Hurdle Forecasting in Python
Could Shorter AI Asset Lives Hit Earnings? Depreciation Stress Test in Python
How Much AI Capex Risk Can a Portfolio Remove? Constrained Optimization in Python
Is the AI Capex Trade Crowded? Rolling Volatility and Sector Rotation in Python
Did the AI Boom Come From Existing S&P 500 Members? Point-in-Time Momentum Test in Python
Is AI Revenue Circular? Customer-Vendor Capex Loop Analysis in Python
Is the AI Trade Connected to Private Credit? Rolling Correlation Network in Python
Is Apollo More Balance-Sheet Sensitive Than Peers? Leverage Screen in Python
Are AI Earnings Supported by Cash Flow? Accrual and Capex Screen in Python
Can Defensive Stocks Hedge AI Drawdowns? Basket Regime Test in Python
How Fast Does the Market Price In Fed Decisions? FOMC Event Study in Python
How Much Are Options Sellers Overpaid? The Variance Risk Premium in Python
Which Companies Have the Worst Earnings Quality? Sloan Accrual Screen with Geographic Revenue Data in Python
Does the Oil-to-Gold Ratio Signal Recessions? XLE/GLD Backtest in Python
Is AI Spending Crowding Out Free Cash Flow? Capex Sustainability Across the Mag 7 in Python
Does a Long Energy / Short Bonds Portfolio Capture Inflation Surprises? Factor Construction in Python
Can a Hidden Markov Model Detect Oil Market Regimes? HMM Analysis in Python
Do Grain Prices Predict Food Inflation? Granger Causality Test in Python
Does the Corporate Credit Spread Predict Stock Market Crashes? BAA-AAA Spread Analysis in Python
Do Oil Stocks Hedge Inflation? Rolling Beta Analysis in Python
Which Stocks Are Most Rate-Sensitive? Equity Duration via Bond Beta in Python
Which Companies Have the Highest Accrual Ratios? Earnings Quality Screening in Python
Is Alpha Persistent or Decaying? Rolling Sharpe Ratio Analysis in Python
Are Markets Trending or Mean-Reverting? Hurst Exponent Analysis in Python
Is Consumer Discretionary vs Staples a Leading Indicator? XLY/XLP Ratio Analysis in Python
Does Heavy Capex Predict Future Stock Returns? Capital Expenditure Analysis in Python
How to Estimate Cost of Equity Using CAPM in Python
Is Volatility Predictable? Testing for Volatility Clustering in Python
Which Industrials Are Overleveraged? Net Debt to EBITDA Screening in Python
GM Before and After Bankruptcy: Why Entity Resolution Matters for Financial Data
What Is Adjusted Beta? Merrill Lynch Beta Shrinkage in Python
How Good Is a Stock Pick? Information Ratio and Tracking Error in Python
Do Stock Returns Follow a Normal Distribution? Testing for Fat Tails in Python
Which Large Caps Have the Highest Free Cash Flow Yield? FCF Screening in Python
Which Sectors Won Over 5 Years? Sector Rotation Analysis in Python
How to Forecast Stock Volatility with GARCH Models in Python
Are Stock Prices Mean-Reverting? Augmented Dickey-Fuller Test in Python
How to Calculate CAPM Alpha and Beta with Regression in Python
How to Compare Sector Sharpe Ratios and Sortino Ratios in Python
DELL: Why Stitching Historical Price Data Together Is Wrong
How to Analyze Drawdown and Recovery for Bank Stocks in Python
How to Screen SaaS Stocks by Revenue Growth and Cash Flow in Python
How to Screen REITs by Dividend Yield and Valuation in Python
How Correlated Are the Magnificent 7? Intra-Group Correlation in Python
AAPL vs XOM: Do Individual Stocks Have Seasonal Patterns?
How to Rank Large-Cap Stocks by Momentum in Python
How to Build a Multi-Endpoint Financial Dashboard in Python
How to Compare Volatility Across Energy Stocks in Python
How to Screen Healthcare Stocks by Valuation in Python
How to Build a Sector Correlation Matrix for Portfolio Diversification in Python
How to Find Oversold and Overbought Stocks Using Z-Scores in Python
How to Measure Earnings Quality: Cash Flow vs Net Income in Python
How to Build a Multi-Factor Stock Screen in Python (Value + Momentum + Quality)
How to Build a Simple DCF Model for Any Stock in Python
How to Screen Tech Stocks by Revenue Growth in Python
How to Screen Stocks by Balance Sheet Health in Python
Is "Sell in May" Real? SPY Monthly Seasonality Over 10 Years
How to Compare Sector Performance YTD Using Python
How to Track S&P 500 Additions and Removals Over Time in Python
How to Screen Dividend Stocks by Yield and Quality in Python
How to Calculate Max Drawdown and Recovery Time for Any Stock in Python
How to Compare Profitability Across Mega-Cap Tech Stocks in Python
Why Ticker Symbols Are Unreliable: The Recycling Problem Every Quant Should Know
How to Calculate and Compare Stock Volatility in Python
How to Screen Blue-Chip Stocks by P/E Ratio in Python
How to Track Companies Through Ticker Changes, Bankruptcies, and Renames in Python
S&P 500 Turnover: How Much the Index Has Changed Since 2010
How to Calculate Stock Beta and Correlation in Python
← All articles

How to Calculate and Compare Stock Volatility in Python

What’s the question?

When evaluating a stock for a portfolio, the first risk metric to examine is volatility — a statistical measure of how much a stock’s price fluctuates over a given period. A stock with high volatility experiences large daily price swings, while a low-volatility stock moves in a narrower range. But a single annualized number only tells part of the story. Volatility changes over time, and the recent risk regime may differ substantially from the trailing average. How do you measure both the overall and current volatility for a set of stocks, and how do those numbers compare across sectors?

The approach

Annualized volatility is calculated as the standard deviation of daily returns, multiplied by the square root of 252 (the approximate number of trading days in a year). This scaling converts a daily measure into an annual one, making it comparable across different time horizons.

To capture the current risk environment, we also compute 30-day rolling volatility — the same calculation applied to a sliding 30-day window of returns. This reveals whether a stock is currently in a calm or turbulent period relative to its full-year average.

Four stocks are selected across different sectors: AAPL (technology), TSLA (consumer discretionary / high-growth), JNJ (healthcare / defensive), and JPM (financials). As a final step, the maximum drawdown — the largest peak-to-trough decline in price — is computed for the most volatile stock in the group.

import xfinlink as xfl
import pandas as pd
import numpy as np

xfl.set_api_key("your_key")  # free at https://xfinlink.com/signup

# Pull 1 year of daily prices for 4 stocks across different sectors
tickers = ["AAPL", "TSLA", "JNJ", "JPM"]
df = xfl.prices(tickers, period="1y", fields=["close", "return_daily"])

# Calculate annualized volatility per ticker
vol = (
    df.groupby("ticker")["return_daily"]
    .std()
    .mul(np.sqrt(252))  # annualize daily std dev
    .sort_values(ascending=False)
    .rename("annualized_vol")
)
print("=== Annualized Volatility (1Y) ===")
print(vol.round(4).to_string())
print()

# Calculate 30-day rolling volatility for each ticker
df["rolling_vol_30d"] = (
    df.groupby("ticker")["return_daily"]
    .transform(lambda x: x.rolling(30).std() * np.sqrt(252))
)

# Show the most recent 30-day rolling vol for each
latest = (
    df.sort_values("date")
    .groupby("ticker")
    .tail(1)[["ticker", "date", "rolling_vol_30d"]]
    .sort_values("rolling_vol_30d", ascending=False)
)
print("=== Latest 30-Day Rolling Volatility ===")
print(latest.to_string(index=False))
print()

# Find the max drawdown date range for the most volatile stock
most_volatile = vol.idxmax()
mv_prices = df[df["ticker"] == most_volatile].sort_values("date")
mv_prices["cummax"] = mv_prices["close"].cummax()
mv_prices["drawdown"] = mv_prices["close"] / mv_prices["cummax"] - 1
worst_dd = mv_prices.loc[mv_prices["drawdown"].idxmin()]
print(f"=== {most_volatile} Max Drawdown (1Y) ===")
print(f"Date: {worst_dd['date'].strftime('%Y-%m-%d')}")
print(f"Drawdown: {worst_dd['drawdown']:.2%}")

Output:

=== Annualized Volatility (1Y) ===
ticker
TSLA    0.4723
AAPL    0.2323
JPM     0.2121
JNJ     0.1682

=== Latest 30-Day Rolling Volatility ===
ticker       date  rolling_vol_30d
  TSLA 2026-05-07         0.436583
  AAPL 2026-05-07         0.250997
   JPM 2026-05-07         0.244608
   JNJ 2026-05-07         0.158343

=== TSLA Max Drawdown (1Y) ===
Date: 2026-04-08
Drawdown: -29.93%

What this tells us

TSLA’s annualized volatility of 47% is more than double JNJ’s 17%, which reflects the fundamental difference in business model uncertainty between a high-growth electric vehicle manufacturer and a diversified healthcare conglomerate. AAPL and JPM occupy the middle ground near 23% and 21%, respectively.

The rolling volatility reveals a notable shift in the current regime. JPM’s recent 30-day volatility (24.5%) has climbed close to AAPL’s (25.1%), despite having lower full-year volatility. This convergence suggests that financials are pricing in elevated macroeconomic uncertainty in the near term.

TSLA’s maximum drawdown of approximately 30% on April 8 aligns with the broader tariff-driven market selloff during that period. A drawdown of this magnitude, while severe, is consistent with the stock’s high volatility profile.

So what?

Annualized volatility provides a single summary of a stock’s risk over a full period, but rolling volatility is the more actionable measure for portfolio management. A stock’s risk profile can shift substantially within a year, and position sizing decisions should reflect the current regime rather than an annual average. When two stocks with historically different risk profiles begin converging in their rolling volatility — as JPM and AAPL do here — it signals a change in the market’s assessment of relative risk that may warrant rebalancing.

Built with xfinlink — free financial data API for Python. pip install xfinlink
← All articles