# 美股盈餘驚喜廣度擇時（槓桿 ETF）

回測期間 2016-05-02 〜 2026-11-24 · 資料截至 2026-11-25

[到 FinLab Studio 重現這支策略](https://studio.finlab.finance/chat?lang=zh\&research_context=%7B%22v%22%3A1%2C%22source_url%22%3A%22https%3A%2F%2Ffinlab.finance%2Fstrategies%2Fus-earnings-surprise-strategy%22%2C%22task%22%3A%22%E9%87%8D%E8%B7%91%E3%80%8C%E7%BE%8E%E8%82%A1%E7%9B%88%E9%A4%98%E9%A9%9A%E5%96%9C%E5%BB%A3%E5%BA%A6%E6%93%87%E6%99%82%EF%BC%88%E6%A7%93%E6%A1%BF+ETF%EF%BC%89%E3%80%8D%E7%9A%84%E5%9B%9E%E6%B8%AC%E3%80%82%E9%80%99%E9%A0%81%E7%9A%84%E7%AD%96%E7%95%A5%E7%A8%8B%E5%BC%8F%EF%BC%88%E7%94%A8+requests+%E8%AE%80%E5%8F%96%EF%BC%89%EF%BC%9Ahttps%3A%2F%2Ffinlab.finance%2Fblog%2Fus-earnings-surprise-strategy%2Fstrategy.py%22%2C%22intent%22%3A%22backtest%22%2C%22market%22%3A%22us%22%2C%22period%22%3A%7B%22start%22%3A%222016-01-01%22%2C%22end%22%3A%222026-11-24%22%7D%2C%22published%22%3A%7B%22annual_return%22%3A0.3064%2C%22start%22%3A%222016-05-02%22%2C%22end%22%3A%222026-11-24%22%7D%7D) [完整研究與三項驗證](https://finlab.finance/blog/us-earnings-surprise-strategy)

近 20 個交易日內，流動性前 500 檔美股中 EPS 超出分析師預估 5% 以上且當日上漲的事件數超過 1%，同時 QQQ 趨勢向上時視為多頭：多頭月份在最強的防禦型 ETF 之外加上 TQQQ、TECL（約各 25%、防禦 50%），空頭月份只持有 IEF、GLD、SHY 中最強的一檔；月換股、8% 停損。2016 年 5 月至 2026 年 10 月回測年化報酬 32.2%、日夏普 1.49、最大回撤 -21.1%；同視窗 QQQ 含息年化 20.7%、日夏普 0.96、最大回撤 -35.1%。鄰近參數、前後兩段、每邊 0.1% 交易成本三項驗證皆通過。

**投資警語：本文僅供教學參考，不構成投資建議。過去績效不代表未來表現，投資有風險。**

## 回測績效

* 年化報酬率

  30.6%

* 夏普比率（日資料）

  1.43

* 最大回撤

  -21.1%

* 總報酬率

  1583%

回測不計手續費與交易稅（finlab 套件 sim() 的美股預設成本），夏普比率用日報酬計算、未扣無風險利率。策略淨值自資料可得日（2016-05-02）起算。

## 淨值曲線（對數座標）

美股盈餘驚喜廣度擇時（槓桿 ETF） vs QQQ 買進持有（含息）

美股盈餘驚喜廣度擇時（槓桿 ETF）QQQ 買進持有（含息）

## 與 QQQ 買進持有（含息）對照

| 對象                 | 年化報酬率 | 夏普比率（日資料） | 最大回撤   | 回測期間                    |
| ------------------ | ----- | --------- | ------ | ----------------------- |
| 美股盈餘驚喜廣度擇時（槓桿 ETF） | 30.6% | 1.43      | -21.1% | 2016-05-02 〜 2026-11-24 |
| QQQ 買進持有（含息）       | 19.3% | 0.90      | -35.1% | 2016-05-02 〜 2026-11-24 |

## 完整策略程式碼

安裝 finlab 套件後即可直接執行重現（finlab.login() 會自動引導登入，不需手動填 token）。想用 AI 輔助安裝與跑第一次回測，可以走[安裝教學](https://finlab.finance/setup)。

展開程式碼（strategy.py）

```
"""US earnings-surprise drift (PEAD) breadth strategy (FinLab).

Count how many liquid US stocks beat analyst EPS estimates by more than 5%
with a positive same-day price reaction over the last 20 trading days. The
strongest defensive asset (IEF / GLD / SHY) is always held. When that count
exceeds 1% of the liquid universe AND QQQ is in an uptrend, the two leveraged
growth ETFs (TQQQ / TECL) are added next to it and the simulator normalizes
the book (half defensive, a quarter in each leveraged ETF). Monthly rebalance,
8% intramonth stop-loss.

Complete the AI-assisted setup flow at https://finlab.finance/en/setup before running this file.

    python strategy.py              # backtest
    python strategy.py --validate   # robustness checks from the article
"""

import os
import sys

import finlab
import pandas as pd
from finlab import data
from finlab.backtest import sim
from finlab.dataframe import FinlabDataFrame

RISK_ASSETS = ["TQQQ", "TECL"]
DEFENSIVE_ASSETS = ["IEF", "GLD", "SHY"]


def recent_extreme_moves(close):
    # Each column is independent; bound the rolling calculation's temporary tables.
    columns_per_block = 512
    blocks = []
    for start in range(0, len(close.columns), columns_per_block):
        prices = close.iloc[:, start:start + columns_per_block]
        # fill_method=None: pandas 2 forward-fills gaps by default, pandas 3 does not.
        bad = prices.pct_change(fill_method=None).abs() >= 0.50
        blocks.append(bad.rolling(252, min_periods=1).max().shift(1).fillna(False) > 0)
    return FinlabDataFrame(pd.concat(blocks, axis=1))


def surprise_breadth():
    """Share of the liquid universe with a >5% EPS beat and a positive same-day
    reaction over the last 20 trading days. The stock tables are large, so each
    is released once later steps no longer need it; only this daily series is
    returned."""
    data.set_market("us")
    raw_close = data.get("us_price:close")  # volume is not split-adjusted, so
    volume = data.get("us_price:volume")    # dollar volume uses the unadjusted close

    # Liquid universe: top 500 by 60-day average dollar volume, price above $5,
    # excluding names with a recent extreme (>50%) daily move.
    dollar_volume = (raw_close * volume).rolling(60, min_periods=20).mean()
    del volume
    universe = dollar_volume.is_largest(500) & (dollar_volume > 8_000_000) & (raw_close > 5)
    del raw_close, dollar_volume
    data.free_memory()

    close = data.get("us_price:adj_close")
    had_extreme_move = recent_extreme_moves(close)
    universe = universe & ~had_extreme_move
    del had_extreme_move
    # Positive same-day price reaction, kept as true/false so the price table can go.
    up_day = (close / close.shift(1) - 1) > 0
    del close
    data.free_memory()

    # Earnings surprise in % of the estimate (values exist on announcement days).
    eps_actual = data.get("us_earnings_surprises:eps_actual")
    eps_estimated = data.get("us_earnings_surprises:eps_estimated")
    surprise = (eps_actual - eps_estimated) / eps_estimated.abs()
    del eps_actual, eps_estimated
    data.free_memory()

    # Signal: breadth of positive surprise events over the last 20 trading days.
    positive_events = universe & (surprise > 0.05) & up_day
    del surprise, up_day
    # These are integer counts: sum stocks first, then roll the daily series.
    # This avoids a full-market float table without changing any event count.
    event_count = positive_events.sum(axis=1).rolling(20, min_periods=1).sum()
    del positive_events
    breadth = event_count / universe.sum(axis=1).replace(0, float("nan"))
    del universe
    data.free_memory()  # collect after the large inputs have been released
    return breadth


def build_position(breadth_threshold=0.01, trend_window=200, *, breadth=None):
    if breadth is None:
        breadth = surprise_breadth()
    # Market regime gate: QQQ above its 200-day average with positive 6-month momentum.
    fund_close = data.get("us_fund_price:adj_close")[["QQQ"] + RISK_ASSETS + DEFENSIVE_ASSETS]
    qqq_trend = fund_close["QQQ"] > fund_close["QQQ"].rolling(trend_window, min_periods=trend_window // 2).mean()
    qqq_momentum = fund_close["QQQ"] / fund_close["QQQ"].shift(126) - 1
    risk_on = (breadth > breadth_threshold) & (qqq_trend & (qqq_momentum > 0)).reindex(breadth.index)

    # Execution sleeve: the strongest defensive asset is always held; risk-on adds the
    # two strongest leveraged ETFs next to it (about 25% / 25% / 50% defensive).
    risk_score = FinlabDataFrame(fund_close[RISK_ASSETS].pct_change(126, fill_method=None))
    defensive_score = FinlabDataFrame(
        fund_close[DEFENSIVE_ASSETS].pct_change(63, fill_method=None)
        - fund_close[DEFENSIVE_ASSETS].pct_change(21, fill_method=None)
    )
    risk_on_daily = risk_on.reindex(fund_close.index, fill_value=False)

    risky_position = (risk_score.is_largest(2) & risk_on_daily).astype(float)
    risky_position = risky_position.div(risky_position.sum(axis=1), axis=0).fillna(0)
    defensive_position = defensive_score.is_largest(1).astype(float)

    position = (
        risky_position.reindex(fund_close.index).fillna(0)
        .join(defensive_position.reindex(fund_close.index).fillna(0), how="outer")
        .fillna(0)
        .T.groupby(level=0).max().T
    )
    return position.loc["2016-01-01":]


def run_backtest(position, fee_ratio=None):
    data.set_market("us_fund")
    # Studio finds this report name in the source and reads the module-level value.
    report = sim(
        position,
        resample="M",
        name="us_earnings_surprise_drift",
        upload=False,
        fee_ratio=fee_ratio,    # None = finlab's US default (0 commission, 0 tax)
        trade_at_price="close",
        position_limit=1,
        stop_loss=0.08,
        touched_exit=True,
    )
    return report


# ---------------------------------------------------------------------------
# Robustness checks behind the article's validation section:
#     python strategy.py --validate
# "Beats QQQ" means a higher daily Sharpe than buying and holding QQQ
# (dividend-adjusted) over exactly the same dates.
# ---------------------------------------------------------------------------
COST_PER_SIDE = 0.001  # 0.1% per buy and per sell, for spread and slippage


def daily_sharpe(equity):
    returns = equity.pct_change().dropna()
    return returns.mean() / returns.std() * 252 ** 0.5


def sharpe_vs_qqq(equity):
    qqq = data.get("us_fund_price:adj_close")["QQQ"].reindex(equity.index).ffill()
    return daily_sharpe(equity), daily_sharpe(qqq)


def validate():
    breadth = surprise_breadth()  # the parameters below only change the ETF stage

    # 1. Neighbouring parameters: the original value and one step either side.
    wins = 0
    for breadth_threshold in (0.0075, 0.01, 0.0125):
        for trend_window in (150, 200, 250):
            report = run_backtest(build_position(breadth_threshold, trend_window, breadth=breadth))
            strategy, qqq = sharpe_vs_qqq(report.creturn)
            wins += strategy > qqq
            print(f"breadth>{breadth_threshold:.4f} QQQ>{trend_window}d MA: Sharpe {strategy:.2f} vs QQQ {qqq:.2f}")
    print(f"{wins}/9 parameter sets beat QQQ")

    # 2. First half and second half of the backtest, each on its own.
    position = build_position(breadth=breadth)
    equity = run_backtest(position).creturn
    middle = equity.index[len(equity) // 2]
    for label, part in (("first half", equity.loc[:middle]), ("second half", equity.loc[middle:])):
        strategy, qqq = sharpe_vs_qqq(part)
        print(f"{label} {part.index[0].date()} to {part.index[-1].date()}: "
              f"Sharpe {strategy:.2f} vs QQQ {qqq:.2f}")

    # 3. Trading costs: finlab's US default is zero, so charge 0.1% per side.
    report = run_backtest(position, fee_ratio=COST_PER_SIDE)
    strategy, qqq = sharpe_vs_qqq(report.creturn)
    print(f"with 0.1% per side: CAGR {report.get_stats()['cagr']:.1%}, "
          f"Sharpe {strategy:.2f} vs QQQ {qqq:.2f}")


def build_report():
    return run_backtest(build_position())


def main():
    if not os.environ.get("FINLAB_ID_TOKEN"):
        finlab.login()  # standalone scripts still use browser login
    if "--validate" in sys.argv:
        validate()
        return
    report = build_report()
    print(report.get_stats())
    report.display()
    return report


if __name__ == "__main__":
    report = main()
```

[下載 strategy.py](https://finlab.finance/blog/us-earnings-surprise-strategy/strategy.py) [下載 data.csv（淨值曲線）](https://finlab.finance/blog/us-earnings-surprise-strategy/data.csv)

[到 FinLab Studio 重現這支策略](https://studio.finlab.finance/chat?lang=zh\&research_context=%7B%22v%22%3A1%2C%22source_url%22%3A%22https%3A%2F%2Ffinlab.finance%2Fstrategies%2Fus-earnings-surprise-strategy%22%2C%22task%22%3A%22%E9%87%8D%E8%B7%91%E3%80%8C%E7%BE%8E%E8%82%A1%E7%9B%88%E9%A4%98%E9%A9%9A%E5%96%9C%E5%BB%A3%E5%BA%A6%E6%93%87%E6%99%82%EF%BC%88%E6%A7%93%E6%A1%BF+ETF%EF%BC%89%E3%80%8D%E7%9A%84%E5%9B%9E%E6%B8%AC%E3%80%82%E9%80%99%E9%A0%81%E7%9A%84%E7%AD%96%E7%95%A5%E7%A8%8B%E5%BC%8F%EF%BC%88%E7%94%A8+requests+%E8%AE%80%E5%8F%96%EF%BC%89%EF%BC%9Ahttps%3A%2F%2Ffinlab.finance%2Fblog%2Fus-earnings-surprise-strategy%2Fstrategy.py%22%2C%22intent%22%3A%22backtest%22%2C%22market%22%3A%22us%22%2C%22period%22%3A%7B%22start%22%3A%222016-01-01%22%2C%22end%22%3A%222026-11-24%22%7D%2C%22published%22%3A%7B%22annual_return%22%3A0.3064%2C%22start%22%3A%222016-05-02%22%2C%22end%22%3A%222026-11-24%22%7D%7D)

在 Studio 裡用同一套真實資料調整條件、重跑回測。

本頁策略與回測結果僅供教學與研究用途，詳見[服務條款](https://finlab.finance/terms)。

來源：https://finlab.finance/strategies/us-earnings-surprise-strategy｜資料日期：2016-05-02/2026-11-24
