MODULE IV: PYTHON FOR FINANCIAL DATA ANALYSIS
The ultimate objective of computational financial literacy is the empirical modeling of asset returns, portfolio risk, market sensitivity, and risk-adjusted performance. Modern investment banking, wealth management, and quantitative hedge funds rely on computational econometrics to price securities and optimize capital allocation. Module IV explores the core quantitative frameworks of modern finance implemented in Python. Students master the mathematical formulations and computational execution of: Simple versus Continuous Logarithmic Rates of Return for single assets and multi-security portfolios; Investment Risk Measurement via Variance, Volatility, Covariance, and Correlation matrices; Decomposition of total portfolio risk into Systematic (Market) and Idiosyncratic (Diversifiable) components; Econometric Ordinary Least Squares (OLS) Linear Regression for computing empirical Alpha, Beta, and R-Squared; the Capital Asset Pricing Model (CAPM) for estimating equilibrium required returns and Security Market Line (SML) pricing; and institutional Risk-Adjusted Performance Attribution metrics (Sharpe Ratio, Treynor Ratio, and Jensen's Alpha).
UNIT 1: CALCULATING & COMPARING RATES OF RETURN IN PYTHON
The Rate of Return measures the percentage gain or loss generated on an investment relative to its initial cost over a specified temporal horizon. In quantitative finance, distinguishing between discrete percentage returns and continuous logarithmic returns is fundamental to mathematical model design.
1. Discrete Simple Returns vs Continuous Logarithmic Returns
Financial analysts process price time-series using two distinct return formulations:
| Return Framework | Mathematical Formulation | Properties & Computational Utility |
|---|---|---|
| Simple Return (Discrete) | R_t = (P_t - P_{t-1}) / P_{t-1} = (P_t / P_{t-1}) - 1 |
Cross-Sectional Additivity: The return of a multi-asset portfolio is exactly equal to the weighted sum of the simple returns of its constituent assets: R_p = sum(w_i * R_i). Essential for accounting and client wealth reporting. |
| Logarithmic Return (Continuous) | r_t = ln(P_t / P_{t-1}) = ln(P_t) - ln(P_{t-1}) |
Inter-Temporal Additivity: The cumulative return over N trading sessions is simply the arithmetic sum of the individual daily log returns: r_{0,N} = sum(r_t). Essential for derivative pricing, econometric regression, and algorithmic backtesting. |
• Suppose an equity asset priced at INR 100 increases by 50% on Day 1 to INR 150, and then drops back to INR 100 on Day 2 (a 33.33% decline).
— Simple Returns: Day 1 = +50.0%; Day 2 = -33.33%. Arithmetic mean = (+50% - 33.33%) / 2 = +8.33% (misleading positive distortion despite zero net capital gain).
— Log Returns: Day 1 = ln(150/100) = +0.4055; Day 2 = ln(100/150) = -0.4055. Arithmetic sum = 0.0000 (accurately reflecting capital preservation).
2. Calculating a Security's Rate of Return in Python
3. Geometric Mean vs Arithmetic Mean & Volatility Drag
In wealth compounding, the Geometric Mean Return is always strictly less than or equal to the Arithmetic Mean Return due to volatility drag. The mathematical approximation is defined as:
Geometric Mean Return ≈ Arithmetic Mean Return - (0.5 × Volatility^2)
4. Portfolio Drift vs Periodic Rebalancing in Python
Over time, asset classes with superior performance expand as a percentage of total portfolio wealth, while underperforming assets contract. This phenomenon, known as Portfolio Drift, alters the intended risk profile:
5. Calculating a Portfolio of Securities' Rate of Return
A commercial investment portfolio aggregates capital across multiple securities. The portfolio return is computed via vector dot product of asset weights and individual simple returns:
UNIT 2: MEASURING INVESTMENT RISK & PORTFOLIO DIVERSIFICATION
In financial economics, risk is defined as the dispersion or uncertainty of actual future returns around the expected mean return. While return is desired, risk is the penalty that investors must manage.
1. Variance, Volatility & Annualization Mechanics
Asset volatility is measured mathematically by the Standard Deviation of its return distribution:
• Sample Variance:
s^2 = sum((R_t - R_mean)^2) / (N - 1)
• Daily Volatility (Standard Deviation):
sigma_daily = sqrt(s^2)
• Annualized Volatility:
sigma_annual = sigma_daily * sqrt(252)
— The multiplier
sqrt(252) stems from the assumption that daily returns are independent and identically distributed (i.i.d.) random variables across 252 trading sessions per fiscal year.
2. Covariance Matrix & Pearson Correlation
Measuring the interaction between pairs of assets is the cornerstone of Modern Portfolio Theory:
• Covariance (Cov(X, Y)): Measures the directional co-movement of two assets. A positive covariance indicates assets tend to rise and fall together; a negative covariance indicates inverse movement.
• Correlation Coefficient (rho_{xy}): Standardizes covariance into a dimensionless metric bounded strictly between -1.0 and +1.0:
rho_{xy} = Cov(X, Y) / (sigma_x * sigma_y)
3. Portfolio Risk Calculation: The 2-Asset vs N-Asset Matrix Framework
The total risk of an N-asset portfolio is not a simple weighted average of individual volatilities; it incorporates all pairwise cross-covariances:
- For a 2-Asset Portfolio:
sigma_p^2 = (w_1^2 * sigma_1^2) + (w_2^2 * sigma_2^2) + (2 * w_1 * w_2 * Cov_{1,2}). - For an N-Asset Portfolio: Computed via quadratic matrix multiplication in NumPy:
np.dot(weights.T, np.dot(cov_matrix, weights)). - The Diversification Dividend: If correlation
rho < 1.0, the total portfolio risksigma_pis strictly less than the weighted average of individual asset risks, proving that diversification mathematically eliminates risk without sacrificing return.
4. Systematic vs Idiosyncratic (Diversifiable) Risk Decomposition
Total investment risk is bifurcated into two distinct economic categories:
1. Systematic Risk (Market / Non-Diversifiable): • Definition: Pervasive macroeconomic factors (interest rate shifts, GDP contractions, inflation spikes, geopolitical crises) affecting all market securities simultaneously.
• Diversification: Cannot be eliminated through diversification, regardless of how many stocks are added to the portfolio.
• Metric: Quantified by Beta (beta).
2. Idiosyncratic Risk (Specific / Diversifiable): • Definition: Microeconomic shocks unique to a specific firm or industry (patents, product recalls, labor disputes, corporate executive changes).
• Diversification: Can be completely diversified away. In an equally weighted portfolio, as the number of assets N exceeds 30 to 40 securities, idiosyncratic variance approaches zero.
5. Mathematical Convergence of Diversification
In an equally weighted portfolio where w_i = 1/N, total portfolio variance can be factored into two terms:
sigma_p^2 = (1/N) × Average_Asset_Variance + (1 - 1/N) × Average_Covariance
As N → ∞, the term (1/N) × Average_Variance → 0, meaning individual asset variance disappears completely, and the remaining risk of the portfolio is dictated exclusively by the average covariance between assets!
6. Historical Simulation vs Parametric Value at Risk (VaR) in Python
Value at Risk (VaR) answers the fundamental executive risk question: "What is the maximum monetary loss expected over a defined holding period at a specific statistical confidence level (e.g., 95% or 99%)?"
UNIT 3: REGRESSION ANALYSIS FOR FINANCIAL DATA IN PYTHON
Ordinary Least Squares (OLS) Linear Regression is the premier econometric workhorse used to quantify the relationship between an individual security's return (dependent variable Y) and the broader market benchmark return (independent variable X).
1. The Single-Index Market Model
The Single-Index Model represents the return of stock i as a linear function of market index return R_m:
R_{i,t} = alpha_i + (beta_i * R_{m,t}) + epsilon_{i,t}
•
beta_i (Beta): Slope coefficient measuring systematic sensitivity: Cov(R_i, R_m) / Var(R_m).
•
alpha_i (Alpha): Intercept coefficient measuring excess return unexplained by market movements: R_mean_i - (beta_i * R_mean_m).
•
epsilon_{i,t} (Residual Error): Random zero-mean idiosyncratic error term.
•
R^2 (R-Squared): Percentage of total asset variance explained by market index fluctuations.
2. Running Financial Regressions in Python
Python offers two primary libraries for econometric regression: scipy.stats.linregress for fast summary metrics and statsmodels.api.OLS for exhaustive econometric diagnostic tables:
3. Interpreting Beta Across Financial Sectors
beta = 1.0(Market Neutrality): The security moves in tandem with the broad market index (e.g., diversified large-cap mutual funds).beta > 1.0(Aggressive / High Beta): The asset amplifies market volatility. A beta of1.40implies that if NIFTY advances by 10%, the stock is expected to surge by 14%; conversely, a 10% market crash causes a 14% plunge. Typical of Banking, Technology, and Real Estate sectors.beta < 1.0(Defensive / Low Beta): The asset is less volatile than the market index. A beta of0.65provides capital stability during market downturns. Typical of Fast-Moving Consumer Goods (FMCG), Pharmaceuticals, and Public Utilities.beta < 0.0(Inverse Beta): The asset moves in the opposite direction of the market index. Typical of Gold ETFs, inverse volatility instruments, and long government bond hedges.
4. Multi-Factor Asset Pricing: The Fama-French 3-Factor Model
While the single-index CAPM model relies exclusively on market Beta, Eugene Fama and Kenneth French (1993) demonstrated that market beta alone fails to explain cross-sectional equity returns. The Fama-French Three-Factor Model expands CAPM by incorporating two additional fundamental risk factors:
- Market Risk Premium (
R_m - R_f): Traditional market sensitivity factor. - Size Premium (Small Minus Big -
SMB): Captures the historical outperformance of small-capitalization firms over large-capitalization corporations due to higher risk and growth potential. - Value Premium (High Minus Low -
HML): Captures the excess return of high book-to-market (value) stocks relative to low book-to-market (growth) stocks.
UNIT 4: CAPITAL ASSET PRICING MODEL (CAPM) & PERFORMANCE ATTRIBUTION
Formulated independently by William Sharpe (1964), John Lintner, and Jan Mossin, the Capital Asset Pricing Model (CAPM) establishes the theoretical relationship between the non-diversifiable systematic risk of an asset and its equilibrium expected rate of return.
1. The CAPM Formula & The Security Market Line (SML)
CAPM asserts that investors require no compensation for holding idiosyncratic risk (since it can be diversified away freely). Expected return depends exclusively on systematic risk:
R_f(Risk-Free Rate): Return on a default-free government instrument (e.g., 91-Day Reserve Bank of India Treasury Bill yield, typically ~6.5%).E(R_m)(Expected Market Return): Expected long-term return of the diversified market index (e.g., NIFTY 50 historical mean ~13.5%).[E(R_m) - R_f](Equity Market Risk Premium - ERP): The additional hurdle return demanded by rational investors for holding risky equity instead of risk-free cash (~7.0%).- Security Market Line (SML): The graphical line plotting Beta on the x-axis and Expected Return on the y-axis. Securities plotting above the SML generate higher returns than warranted by risk (undervalued / attractive buy); securities plotting below the SML are overpriced.
2. Computing CAPM Expected Return in Python
3. Risk-Adjusted Performance Attribution: Sharpe, Treynor & Jensen's Alpha
Institutional asset managers must prove that high returns are the product of superior investing acumen rather than excessive speculative risk taking:
1. Sharpe Ratio (Total Risk): S_p = (R_p - R_f) / sigma_p
• Evaluates excess return generated per unit of total volatility.
• Sharpe > 1.0 is Good; Sharpe > 2.0 is Exceptional.
2. Treynor Ratio (Market Risk): T_p = (R_p - R_f) / beta_p
• Evaluates excess return generated per unit of systematic risk (Beta).
• Ideal for evaluating well-diversified equity portfolios.
3. Jensen's Alpha (Manager Skill): alpha_J = R_p - [R_f + beta_p * (R_m - R_f)]
• Measures true abnormal return in excess of the CAPM equilibrium benchmark.
• Positive alpha confirms manager skill.