The Holy Grail of sector rotation quantification: How to capture excess returns using economic cycles and machine learning

量化研究團隊
2025-12-07 10 min read EN
The Holy Grail of sector rotation quantification: How to capture excess returns using economic cycles and machine learning

Preface: Alpha Hunting Grounds in the Economic Cycle

During my tenure at Two Sigma, there was a long-standing consensus within the strategy team: while pure market-neutral strategies (such as statistical arbitrage) could provide stable Sharpe ratios, to achieve truly massive absolute returns, one must bet on the market's "direction" and "structure". "Sector rotation" is precisely the most subtle bet on "structural direction". It is not about predicting whether the overall market rises or falls, but judging theWhich Industry Clusters Will Outperform the Broader Market and Which Will UnderperformThis is like identifying different currents in a tide—even if the overall market is bearish, there are sectors that rise against the trend. The aim of this article is to transform this art into a repeatable, verifiable scientific process.

Theoretical Foundation: From the Merrill Investment Clock to Quantitative Factors

Any serious discussion of sector rotation begins with understanding the economic cycle. The most famous framework is the 'Investment Clock' theory proposed by Merrill Lynch (now Bank of America Merrill Lynch) in 2004. It simplifies the economic cycle into four stages, divided by two dimensions: 'Economic Growth' and 'Inflation.'

  1. Recovery Period(Economic Growth↑, Inflation↓): Equities Rule, Cyclical Growth Stocks (such as Financials, Discretionary Consumer) Lead Gains.
  2. Overheating Period(Economic growth ↑, inflation ↑): Commodities reign supreme, inflation-hedging assets (e.g., energy, raw materials) and value stocks perform well.
  3. Stagflation Period(Economic growth ↓, inflation ↑): Cash is king, defensive sectors (e.g., consumer staples, healthcare) show relative resilience.
  4. Decline Period(Economic growth ↓, inflation ↓): Bonds dominate, but within equities, interest-rate-sensitive sectors (such as utilities, high-dividend stocks) begin to show appeal.

However, the challenge in practice lies in:1) Which stage are we in? 2) When does stage transition occur? 3) Is the market expectation already reflected in the price? This is where quantitative models come into play.

Quantitative Modeling Construction: State Identification and Signal Generation

We need to transform vague economic phases into tradable mathematical signals. A classic method is to construct aHidden Markov Model (HMM)to identify economic regimes. Suppose we have K hidden states (for example, K=4, corresponding to four phases of the investment clock), and the observed data is a vector of monthly economic indicators (such as ISM Manufacturing PMI, CPI year-over-year growth rate, 10-year Treasury yield, credit spreads, etc.).

: The goal of HMM is, given an observation sequence \( O = \{o_1, o_2, ..., o_T\} \), to estimate the most likely hidden state sequence \( S = \{s_1, s_2, ..., s_T\} \), where \( s_t \in \{1,2,3,4\} \). Its core parameters include:

  • Initial state distribution \( \pi \)
  • State transition matrix \( A \), where \( A_{ij} = P(s_{t+1}=j | s_t=i) \)
  • Observing probability distribution \( B \), typically assumed to be Gaussian distribution: \( o_t | s_t = i \sim N(\mu_i, \Sigma_i) \)

These parameters can be estimated from historical data via the Baum-Welch algorithm (a variant of the EM algorithm), and the most likely state path can be decoded using the Viterbi algorithm.


import numpy as np
import pandas as pd
from hmmlearn import hmm
import yfinance as yf
import pandas_datareader.data as web
import datetime

# 示例:獲取經濟數据(此處為簡化,使用模擬數据)
def fetch_economic_data(start_date, end_date):
    # 在實際應用中,這里會從FRED、Bloomberg等API獲取真實數据
    # 例如: gdp_growth, cpi, unemployment_rate, yield_curve等
    dates = pd.date_range(start_date, end_date, freq='M')
    n = len(dates)
    # 模擬增長指標(如PMI)
    np.random.seed(42)
    growth = np.cumsum(np.random.randn(n) * 0.5) + 55  # 圍繞50波動
    # 模擬通脹指標(如CPI同比)
    inflation = np.cumsum(np.random.randn(n) * 0.3) + 2.0 # 圍繞2%波動
    
    df = pd.DataFrame({'date': dates, 'growth': growth, 'inflation': inflation})
    df.set_index('date', inplace=True)
    return df

# 准備數据
start = datetime.datetime(2000, 1, 1)
end = datetime.datetime(2023, 12, 31)
economic_df = fetch_economic_data(start, end)
features = economic_df[['growth', 'inflation']].values

# 訓練高斯HMM模型,假設有4個隱藏狀態
model = hmm.GaussianHMM(n_components=4, covariance_type="full", n_iter=1000, random_state=42)
model.fit(features)

# 解碼最可能的狀態序列
hidden_states = model.predict(features)
economic_df['economic_state'] = hidden_states

# 查看每個狀態對應的經濟特征均值
print("各狀態下的經濟指標均值(增長,通脹):")
for i in range(model.n_components):
    print(f"狀態 {i}: {model.means_[i]}")
    # 可以根据means_的值,人工標注狀態:例如高增長低通脹->复蘇,高增長高通脹->過熱等

# 接下來,可以將這個狀態序列與板塊收益率進行關聯分析

Practical Case Study One: The Sector Rotation Lens During the 2008 Global Financial Crisis

Let us review a classic stress test. From the second half of 2007 to 2008, the U.S. economy rapidly slid from "overheating" toward a mixture of "recession" and "stagflation." A simple dual-indicator model (using ISM PMI to represent growth and CPI to represent inflation) could have issued a "stagflation" signal in Q4 2007.

Quantitative Strategy Implementation:When the model identifies a "stagflation" state, the strategy should: 1. Reduce overall equity positions (Beta exposure). 2. Among remaining equity positions, overweight consumer staples (XLP), healthcare (XLV), utilities (XLU). 3. Underweight or short financials (XLF), consumer discretionary (XLY), industrials (XLI).

Historical Validation: From the market peak in October 2007 to the low point in March 2009, the S&P 500 Index fell approximately 55%. However, different sectors displayed vastly different performance: - Consumer Staples (XLP): Maximum drawdown of approximately 35%, relatively defensive. - Financials (XLF): Maximum drawdown exceeding 80%, and led the decline. - A simple "long defensive, short cyclical" sector hedge portfolio could have generated substantial relative returns and certain absolute returns during this period.

The key is that the model needs to identify the deterioration of conditions before Lehman Brothers' collapse in September 2008. The introduction of leading indicators (such as inverted yield curve, consumer confidence index) is crucial.

From State to Alpha: Dynamic Factors and Machine Learning Prediction

Identifying economic state is only the first step. The next is predicting, under that state, Which factors will drive relative performance between sectorsDuring recovery periods, momentum factors and revenue growth factors may be effective; during stagflation periods, quality factors (high ROE, low leverage) and dividend factors may dominate.

We can construct aDynamic Factor Model:

\[ R_{i,t} - R_{f,t} = \alpha_i + \sum_{s=1}^{4} I(s_t = s) [\beta_{i,s}^{MKT} MKT_t + \beta_{i,s}^{VAL} VAL_t + ...] + \epsilon_{i,t} \]

Where \( I(s_t = s) \) is an indicator function that equals 1 when the economy is in state s, otherwise 0. This allows the same factor (such as value factor VAL) to have different exposure \( \beta_{i,s}^{VAL} \) and premiums for sector i across different economic states.

A more advanced approach is to use machine learning for end-to-end prediction. For example, use economic indicators, sector characteristics, and market sentiment data as features X_t to predict the relative return ranking of each sector in the next quarter Y_{t+1}. Can employ gradient boosting trees (such as LightGBM) or neural networks.


import lightgbm as lgb
from sklearn.model_selection import TimeSeriesSplit
from sklearn.preprocessing import StandardScaler

# 假設我們已有以下DataFrame:
# sector_returns: 各板塊未來N期的收益率(目標變量)
# feature_df: 包含經濟狀態、板塊估值、動量、宏觀指標等特征

def train_sector_rotation_model(feature_df, target_returns, n_splits=5):
    """
    訓練板塊輪動預測模型(以排名為預測目標)
    """
    tscv = TimeSeriesSplit(n_splits=n_splits)
    models = []
    scores = []
    
    # 將多分類問題轉化為每個板塊的“是否跑贏大盤”的二分類問題,或直接預測收益率排名
    # 這里示例為預測板塊收益率排名(1到11,假設有11個板塊)
    target_rank = target_returns.rank(axis=1, pct=True) # 轉化為橫截面排名百分比
    
    for train_index, val_index in tscv.split(feature_df):
        X_train, X_val = feature_df.iloc[train_index], feature_df.iloc[val_index]
        y_train, y_val = target_rank.iloc[train_index], target_rank.iloc[val_index]
        
        # 訓練一個多輸出回歸模型(預測每個板塊的排名得分)
        # 簡化處理:為每個板塊單獨訓練一個二分類模型(是否成為前3名)
        # 此處以其中一個板塊為例
        sector_name = 'XLK'  # 科技板塊
        y_train_binary = (y_train[sector_name] >= 0.7).astype(int) # 排名前30%定義為正樣本
        y_val_binary = (y_val[sector_name] >= 0.7).astype(int)
        
        train_data = lgb.Dataset(X_train, label=y_train_binary)
        val_data = lgb.Dataset(X_val, label=y_val_binary, reference=train_data)
        
        params = {
            'objective': 'binary',
            'metric': 'auc',
            'boosting_type': 'gbdt',
            'num_leaves': 31,
            'learning_rate': 0.05,
            'feature_fraction': 0.9,
            'verbosity': -1
        }
        
        model = lgb.train(params,
                         train_data,
                         valid_sets=[val_data],
                         num_boost_round=1000,
                         callbacks=[lgb.early_stopping(stopping_rounds=50)])
        models.append(model)
        # 評估...
    
    return models

# 模型訓練后,每月末生成對所有板塊的預測排名,做多排名最高的2-3個板塊,做空排名最低的2-3個板塊。

Practical Case Study Two: Rapid Sector Rotation Under the COVID-19 Pandemic in 2020

The market in 2020 provided a perfect example of a “compressed cycle.” During February-March, the market experienced: 1. Panic Downturn Period (February-March): All risk assets crash, liquidity is king. Defensive sectors (such as consumer staples) are relatively resilient, but the resilience of "stay-at-home economy" related sectors (such as technology, communication services) is already becoming apparent. 2. Policy-driven recovery period (from late March onwards)The Federal Reserve rolled out unlimited QE and fiscal stimulus, with economic expectations jumping from "deep recession" to "strong recovery." At this point, interest-rate-sensitive technology and growth stocks (XLK), non-essential consumer discretionary (XLY), and the hardest-hit energy (XLE) and financial (XLF) sectors began to rebound sharply, but with vastly different momentum.

Challenges and Opportunities in Quantitative Strategies:Traditional models based on monthly economic data may "break down" due to data lags. At this point,High-Frequency Alternative Databecame critical. Examples include: - Using truck traffic flow, OpenTable restaurant reservation data, and TSA security screening numbers to track real-time progress of economic reopening. - Using news sentiment analysis and option market implied volatility surfaces to capture inflection points in market panic sentiment. - An agile quantitative system could quickly switch allocation from "full defense" to "embrace growth and deep cyclical rebound" near the March 23rd market low through extreme values in sentiment indicators and policy signals.

This tests the model'sAdaptability and Data Freshness。

Risk Alert and Strategy Limitations

There is no holy grail strategy; sector rotation quantitative strategy faces multiple risks:

  1. Model Risk:Divisions of economic states are artificial, and historical patterns may fail. Overfitting is the nemesis of quantitative researchers.
  2. Data Mining Risk:In hundreds of macroeconomic indicators "turning over rocks," it is easy to find spurious statistical relationships. Must adhere to strict out-of-sample testing.
  3. Transaction costs and liquidity risk: Frequent sector rotation will incur observable trading costs (especially the bid-ask spreads and commissions for buying and selling ETFs). During periods of market stress, liquidity drought may prevent execution at ideal prices.
  4. Policy and Structural Rupture Risk:The Federal Reserve's unconventional policies after 2008 and the pandemic in 2020 could both lead to breakdowns in historical correlations. Models must include detection of "regime changes".
  5. Crowding Risk:When too many investors use similar rotation models, excess returns are quickly diluted or even cause reverse stampedes.

Disclaimer:All strategies, models, and code examples described in this article are for educational and research purposes only and do not constitute personalized financial guidance. Financial markets inherently contain risk, and past performance does not guarantee future results. Readers should seek independent professional financial advice based on their individual circumstances and bear full responsibility for any investment decisions.

Action Recommendations: Building Your Own Rotation Strategy Framework

For Investors Committed to Implementation, I Recommend Following This Five-Step Approach:

  1. Define Economic States (Keep it Simple): Early stages do not require complex HMM. You can start from two core indicators (such as U.S. unemployment rate changes representing growth, 10-year break-even inflation rate representing inflation expectations) defined by Z-score cross-sections into four quadrants.
  2. Historical Backtesting and Validation: Use at least 20 years of historical data (must include 1-2 complete economic cycles), test performance with equal-weighting overweight of the top three sectors in each state historically and underweight the worst three. Focus onOut-of-SamplePerformance.
  3. Introduce Leading Indicators and Alternative Data:After the foundational framework stabilizes, gradually add leading indicators (such as yield curves, consumer confidence indices) and high-frequency data (such as credit card spending, satellite imagery) to enhance signal timeliness.
  4. Strict Risk Management:Set maximum sector exposure caps, overall leverage limits, and incorporate volatility control modules (such as forced risk position reduction when market VIX exceeds thresholds).
  5. Continuous Iteration and Philosophical Thinking: Markets evolve. Regularly review whether strategy logic remains valid. Understanding the economic source of strategy excess returns—is it prediction of liquidity? Or pricing of growth momentum? This helps you make correct adjustments when strategies fail.

Finally, concluding with insights from two quantitative finance titans. Cliff Asness (AQR founder) in his paper《Value and Momentum Everywhereconfirmed that factor premiums are time-varying and related to macroeconomic environments. Meanwhile, Andrew Lo's (MIT professor) "Adaptive Markets Hypothesis" reminds us that the market ecosystem is evolving, and there is no one-and-for-all strategy—only continuous learning and adaptation enable long-term survival in the alpha-hunting field.

The quantitative journey of sector rotation is a fascinating expedition that fuses economic wisdom, statistical rigor, and computational science. Happy hunting.

The information contained in this report is for educational purposes only and should not be construed as investment advice. Historical backtest results are provided as statistical data and do not guarantee future performance.

Share this article

Subscription Plans

Find the research useful?

Compare publication subscriptions after exploring the previews.

Compare subscriptions

Related Posts

Volatility Targeting Strategy: A Dynamic Risk Regulator in Quantitative Trading—From Theory to Practical Implementation

Volatility Targeting Strategy: A Dynamic Risk Regulator in Quantitative Trading—From Theory to Practical Implementation

In rapidly changing financial markets, how to systematically manage risk is the key to long-term profitability. Volatility targeting strategy is precisely such a powerful risk management framework that dynamically adjusts portfolio risk exposure aimed at achieving stable risk levels. This article will deeply explore the mathematical principles behind it, analyze classic cases during the 2008 financial crisis and the 2020 pandemic crash, and provide practical Python implementation examples. We will reveal how to apply this technique commonly used by hedge funds to personal investment portfolios, pursuing returns while effectively taming market's wild volatility.

Quantitative Dissection of Seasonal Trading Strategies: Unveiling Statistical Truth and Practical Pitfalls in Month Effects and Holiday Effects

Quantitative Dissection of Seasonal Trading Strategies: Unveiling Statistical Truth and Practical Pitfalls in Month Effects and Holiday Effects

Over fifteen years of quantitative career on Wall Street, I have witnessed the rise and fall of countless strategies, and seasonal strategies, with their seemingly simple logic and tenacious vitality, have always been a fascinating corner of the quantitative toolkit. This article will, from the perspective of a seasoned quantitative trader, conduct a deep analysis of the statistical evidence, economic explanations, and microstructure causes behind "month effects" (such as the January effect and "Sell in May") and "holiday effects" (such as Christmas rallies and the periods around Thanksgiving). We will move beyond market rumors, employing rigorous backtesting frameworks, Python hands-on code, and real market cases (such as how the 2008 financial crisis distorted seasonal patterns), revealing how to convert these "calendar anomalies" into systematic strategies with risk-adjusted excess returns, while frankly discussing their data-snooping risks, structural decay, and stringent risk control requirements.

Time series analysis in quantitative trading practice: a complete guide from ARIMA forecasting to GARCH volatility modeling.

Time series analysis in quantitative trading practice: a complete guide from ARIMA forecasting to GARCH volatility modeling.

In the field of quantitative trading, price and volatility are more than numbers—they are complex time series containing market sentiment and risk. This article will take you deep into the discussion from classical ARIMA models to GARCH family models that capture volatility clustering. We will break down the mathematical principles behind them, share real-world application cases from Wall Street, and provide Python implementation examples. You will learn how to build a trading strategy framework combining mean and volatility forecasting, while understanding the limitations and risks of these powerful tools. This is not just a technical guide but the crystallization of experience from a senior quantitative trading professional.

Trading cost modeling: The invisible killer and winning key in quantitative strategies—an in-depth analysis from theoretical models to real-world tuning.

Trading cost modeling: The invisible killer and winning key in quantitative strategies—an in-depth analysis from theoretical models to real-world tuning.

In the quantitative trading arena, while the discovery of alpha is certainly thrilling, precise modeling and management of transaction costs often distinguishes paper profits from actual gains—a critical divide. This article will deeply dissect the core components of transaction costs—commissions, bid-ask spreads, and market impact costs—and reveal how the latter increases nonlinearly with order size. We will explore the classic Almgren-Chriss optimal execution model and through the 2010 "Flash Crash" and statistical arbitrage strategy case studies, demonstrate the catastrophic consequences of cost modeling errors. Finally, we provide a practical framework combining TWAP/VWAP, predictive models, and real-time monitoring with Python implementation examples, helping you transform theory into a solid shield protecting your strategy's Sharpe ratio.