Diversified Stock Portfolio Using Clustering Analysis
S&P 500 portfolio construction using K-means clustering on risk/return features.
Overview
This project constructs diversified stock portfolios from the S&P 500 using unsupervised learning. Historical price data is used to compute risk and return features for each stock; K-means clustering groups stocks with similar behavior. Portfolio construction then selects top stocks by Sharpe ratio from each cluster to achieve diversification across clusters and validate performance via backtesting against the S&P 500 index.
Data & Features
Data sources: S&P 500 constituent list and historical stock prices (US equity data fetched via the pipeline). The first 70% of the history is used for model building; the remaining 30% is reserved for validation.
Features used for clustering (all derived from historical data):
Clustering Features
Correlation with S&P 500 index (price correlation).
Beta: sensitivity of stock returns to index returns.
Annualized return (from daily returns, 252-day year).
Annualized volatility (standard deviation of daily returns, annualized).
Sharpe ratio (annualized return / annualized volatility).
Daily change in price (open-to-close) and daily variation (high-to-low), annualized.
Features are scaled (z-score) before clustering. The optimal number of clusters is chosen using the within-cluster sum of squares (elbow method); we use K = 4.
Clustering
K-means is run on the normalized feature matrix with multiple random starts. Cluster membership ensures the portfolio spans different behavior groups rather than concentrating in one segment of the risk/return space.
Portfolio Construction
Two portfolio variants are built:
(1) Diversified by cluster: Within each cluster, stocks are ranked by Sharpe ratio; the top 5 from each of the 4 clusters form a 20-stock portfolio (equal weight per stock).
(2) Top-20 by Sharpe: The top 20 stocks by Sharpe ratio across the full universe, without cluster constraints.
Both are equal-weighted. The diversified-by-cluster portfolio reduces concentration in a single risk/return profile.
Validation & Backtesting
Validation uses the holdout period (last 30% of the data). Daily returns are computed for the portfolio (equal-weighted average of constituent returns) and for the S&P 500 index.
Cumulative returns are plotted for the cluster-based portfolio, the top-20 Sharpe portfolio, and the S&P 500 to compare risk-adjusted performance.