Two-panel chart, January 2018 to November 2026: growth of 10,000 US dollars in a portfolio of ASML, Alphabet, Lumentum and S&P Global under three monthly rules (equal weight, a 200-day trend filter and the top two stocks by 12-month return) on a log scale, with each portfolio's fall from its previous peak below
|

How to backtest multiple stocks in Python as one portfolio

Backtesting multiple stocks in Python takes one loop that holds them all at once, and the most useful thing it can print is which stock made the money. The code below runs ASML, Alphabet (GOOGL), Lumentum (LITE) and S&P Global (SPGI) as one portfolio from January 2018 to 23 November 2026, on daily prices from Market Data, under three monthly rules. Equal weight turned $10,000 into $87,314. A 200-day trend filter ended at $49,401, with a worst fall of 33.5% against equal weight’s 41.1%. Holding the two stocks with the best 12-month run ended at $98,224. Backtest results are hypothetical, based on past data only, and are not an indication of future results.

Lumentum made 52% of the equal-weight gain and 68% of the momentum gain. Four stocks went in and one of them did about half the work, and a table of portfolio returns won’t tell you that. So the loop below also books the dollar gain of every holding.

Two-panel chart, January 2018 to November 2026: growth of 10,000 US dollars in a portfolio of ASML, Alphabet, Lumentum and S&P Global under three monthly rules (equal weight, a 200-day trend filter and the top two stocks by 12-month return) on a log scale, with each portfolio's fall from its previous peak below

Step 1: get daily prices for several stocks in one DataFrame

Three of the four have their own posts here: the ASML deep dive, how Lumentum makes money and Alphabet’s growth drivers. S&P Global is the calm one, the least volatile of the four over this window at 27.6% a year. The fifth ticker, BIL, is the State Street SPDR Bloomberg 1-3 Month T-Bill ETF, which holds Treasury bills maturing in one to three months. It’s where the trend filter parks a stock’s slot when it steps out.

Install the client with pip install marketdata-sdk-py. Market Data serves Apple without a token, which helps right up to the moment you want a portfolio. For these tickers, create a Market Data account (affiliate link) and set MARKETDATA_TOKEN. Its pricing page gives the free plan one year of daily history and the Starter plan five, so going back to 2016 takes the Trader plan or higher. The self-service plans come with a 30-day free trial. Market Data provides this site’s data access.

import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from marketdata import MarketDataClient  # pip install marketdata-sdk-py

# Market Data serves AAPL without a token; every ticker here needs one. Set yours first:
#   export MARKETDATA_TOKEN=YOUR_TOKEN
client = MarketDataClient(token=os.environ.get("MARKETDATA_TOKEN"))
STOCKS = ["ASML", "GOOGL", "LITE", "SPGI"]
CASH = "BIL"
FETCH_FROM, START, END = "2016-11-01", "2018-01-01", "2026-11-23"


def daily_closes(ticker, start=FETCH_FROM, end=END, **adjust):
    """Daily closes from Market Data, adjusted for splits and dividends unless told otherwise."""
    df = client.stocks.candles(ticker, resolution="D", from_date=start, to_date=end,
                               output_format="dataframe", **adjust)
    if not isinstance(df, pd.DataFrame):
        raise RuntimeError(df)
    close = df["c"].rename(ticker)
    close.index = close.index.tz_localize(None).normalize()
    return close


prices = pd.concat([daily_closes(t) for t in STOCKS + [CASH]], axis=1).dropna()
print(f"{len(prices)} days x {prices.shape[1]} tickers, {prices.index[0]:%Y-%m-%d} to {prices.index[-1]:%Y-%m-%d}")
print(prices.iloc[[0, -1]].round(2).to_string())
2529 days x 5 tickers, 2016-11-01 to 2026-11-23
               ASML   GOOGL    LITE    SPGI    BIL
t                                                 
2016-11-01    94.53   39.89   35.80  104.87  72.58
2026-11-23  1383.78  282.10  544.38  451.96  91.60

The prices start in November 2016 although the backtest starts in January 2018, because the 200-day average and the 12-month return each need about a year of history before the first trade. pd.concat lines the five tickers up on one date index, and dropna() keeps only the days on which all five have a close. Here the first full row is the first day requested. That’s the line to watch. In “What can go wrong”, one extra ticker makes it throw away almost four years.

Step 2: check the adjusted prices against the filings

A portfolio backtest inherits every split, dividend and spin-off in every stock it holds, so check them before trusting a return. The method is the one from the portfolio rebalancing post: divide the raw close by the adjusted close, and the ratio steps at each split or distribution. The size of the step gives the cash per share. The SEC’s XBRL API then supplies the dividends each company says it declared in its 10-K.

import requests

# The SEC asks every automated request to identify itself. Set your own contact first:
#   export SEC_USER_AGENT="Your Name you@example.com"
HEADERS = {"User-Agent": os.environ["SEC_USER_AGENT"]}
CIKS = {"GOOGL": 1652044, "LITE": 1633978, "SPGI": 64040}


def adjustment_events(ticker):
    """Cash per share implied by each step in the raw/adjusted close ratio (splits show up as ratios < 0.5)."""
    raw = daily_closes(ticker, adjust_splits=False, adjustdividends=False)
    factor = raw / prices[ticker]
    step = (factor / factor.shift()).dropna()
    step = step[(step - 1).abs() > 1e-4]
    cash = raw.shift()[step.index] * (1 / step - 1)
    return cash[step > 0.5], step[step < 0.5]


def declared_dividends(cik):
    """Dividends declared per share in each fiscal year, from the company's 10-K XBRL."""
    url = f"https://data.sec.gov/api/xbrl/companyfacts/CIK{cik:010d}.json"
    facts = requests.get(url, headers=HEADERS, timeout=30).json()
    units = facts["facts"]["us-gaap"].get("CommonStockDividendsPerShareDeclared", {}).get("units", {})
    df = pd.DataFrame(units.get("USD/shares", []), columns=["start", "end", "val", "form", "fp"])
    df = df[(df["form"] == "10-K") & (df["fp"] == "FY")]
    df = df[(pd.to_datetime(df["end"]) - pd.to_datetime(df["start"])).dt.days > 350]
    df = df.drop_duplicates("end", keep="last")
    return pd.Series(df["val"].values, index=pd.to_datetime(df["end"]).dt.year)


events = {t: adjustment_events(t) for t in STOCKS}
rows = []
for t, cik in CIKS.items():
    cash, splits = events[t]
    by_year = cash.groupby(cash.index.year).sum()
    filed = declared_dividends(cik)
    for year in (2023, 2024, 2025):
        rows.append({"ticker": t, "year": year, "in_prices": by_year.get(year, 0.0), "10-K": filed.get(year, 0.0)})
check = pd.DataFrame(rows)
print(check.round(2).to_string(index=False))
print("splits:", {t: [f"{d:%Y-%m-%d} {1 / r:.0f}-for-1" for d, r in s.items()] for t, (c, s) in events.items() if len(s)})

spgi_cash = events["SPGI"][0]
big = spgi_cash[spgi_cash > 5]
mbgl = daily_closes("MBGL", start="2026-07-01", end="2026-07-01", adjust_splits=False, adjustdividends=False)
print(f"SPGI {big.index[0]:%Y-%m-%d}: {big.iloc[0]:.2f} per share | MBGL first close: {mbgl.iloc[0]:.2f}")

# Chart: SPGI's adjusted close as a share of its raw close, one step per distribution
spgi_raw = daily_closes("SPGI", start="2023-01-01", adjust_splits=False, adjustdividends=False)
ratio = prices.loc["2023-01-01":, "SPGI"] / spgi_raw
fig, ax = plt.subplots(figsize=(10, 4.2))
ax.step(ratio.index, ratio, where="post", color="#2a78d6", lw=1.4)
ax.annotate(f"1 Jul 2026: Mobility Global spin-off, {big.iloc[0]:.2f} per share", (big.index[0], ratio[big.index[0]]),
            xytext=(-260, -12), textcoords="offset points", fontsize=9, color="#52514e",
            arrowprops={"arrowstyle": "->", "color": "#52514e"})
ax.yaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1.0, decimals=0))
ax.set_ylabel("Adjusted close / raw close")
ax.set_title("S&P Global (SPGI): how far the adjusted price sits below the traded price, 2023 to Nov 2026", loc="left")
ax.spines[["top", "right"]].set_visible(False)
ax.grid(axis="y", color="#e6e6e3", lw=0.8)
fig.text(0.01, -0.02, "Data: Market Data (marketdata.app). Small steps: quarterly dividends. Code: pythonandfinancehub.com",
         fontsize=8, color="#52514e")
plt.savefig("spgi-adjustment-steps.png", dpi=150, bbox_inches="tight")
ticker  year  in_prices  10-K
 GOOGL  2023       0.00  0.00
 GOOGL  2024       0.60  0.60
 GOOGL  2025       0.83  0.83
  LITE  2023       0.00  0.00
  LITE  2024       0.00  0.00
  LITE  2025       0.00  0.00
  SPGI  2023       3.61  3.60
  SPGI  2024       3.65  3.64
  SPGI  2025       3.85  3.84
splits: {'GOOGL': ['2022-07-18 20-for-1']}
SPGI 2026-07-01: 21.36 per share | MBGL first close: 21.19

Alphabet’s rows match its 10-K for 2025, and the 20-for-1 split lands on 18 July 2022, the first trading day after the split Alphabet’s 10-K for 2022 says it executed on 15 July. S&P Global’s 10-K for 2025 lists $0.96 a quarter in 2025 and $0.91 in 2024, and the prices carry each year to within a cent, about as close as backing cash out of a ratio of rounded closes gets. Lumentum shows nothing, which fits the line in its 10-K for fiscal 2026 that it doesn’t expect to pay cash dividends in the foreseeable future. ASML files an annual report on Form 20-F instead of a 10-K, so it sits this check out.

The last line is the one I didn’t expect. On 1 July 2026 S&P Global handed its shareholders one share of Mobility Global for every SPGI share, according to its 8-K on the separation. The adjusted series books that as $21.36 a share of cash, close to Mobility Global’s first close of $21.19. So any backtest on these prices behaves as if it sold the new Mobility Global shares on day one and bought more SPGI with the money. That’s a sensible default and also a trade nobody made. A holder who kept the Mobility Global shares has had a different return since July.

Step chart of S&P Global's adjusted close as a share of its raw close from January 2023 to November 2026: small steps at each quarterly dividend and one large step on 1 July 2026, when the Mobility Global spin-off was booked as 21.36 US dollars a share

Step 3: write one backtest loop for several stocks

def month_ends(index):
    """Last trading day of each calendar month in the index."""
    return pd.DatetimeIndex(index.to_series().resample("ME").last().dropna())


def backtest(prices, rule, start=START, lag=1, cost=0.001, capital=10_000):
    """Hold rule(decision_day) weights, trading `lag` days after each month-end; track dollar P&L per ticker."""
    days = prices.loc[start:].index
    decisions = month_ends(prices.index)
    trade_on = {prices.index[prices.index.get_loc(d) + lag]: d
                for d in decisions if prices.index.get_loc(d) + lag < len(prices)}
    trade_on[days[0]] = decisions[decisions < days[0]][-1]  # first allocation: last month-end before the start
    shares = pd.Series(0.0, index=prices.columns)
    pnl = pd.Series(0.0, index=prices.columns)
    cash, paid, prev, values = capital, 0.0, None, []
    for day in days:
        row = prices.loc[day]
        if prev is not None:
            pnl += shares * (row - prev)
        total = cash + (shares * row).sum()
        if day in trade_on:
            target = rule(trade_on[day]).reindex(prices.columns, fill_value=0.0) * total
            fee = (target - shares * row).abs().sum() * cost  # cost on every dollar bought or sold
            paid += fee
            shares = target * (total - fee) / total / row
            cash = 0.0
        values.append(cash + (shares * row).sum())
        prev = row
    return pd.Series(values, index=days), pnl, paid


def stats(value):
    """Ending value, compound annual growth, volatility and worst fall from a peak."""
    r = value.pct_change().dropna()
    years = (value.index[-1] - value.index[0]).days / 365.25
    return {"end_value": value.iloc[-1], "cagr": (value.iloc[-1] / value.iloc[0]) ** (1 / years) - 1,
            "volatility": r.std() * np.sqrt(252), "max_drawdown": -(value / value.cummax() - 1).min()}

backtest takes the price table and a rule, a function that gets a decision day and returns target weights. The decision days are the last trading day of each month. With lag=1 the trade happens at the next day’s close, so a rule that reads the month-end close never trades at it. Every trade pays cost on each dollar bought or sold, 0.1% here, which is my assumption for commission and spread.

Each day the loop adds every holding’s price change times its share count to that holding’s running total, pnl. Gains by holding minus trading costs add up to the portfolio’s gain, so Step 5 can split the result by stock without any attribution maths. stats returns compound annual growth, annualised volatility and the worst fall from a previous peak.

Step 4: run three rules on the same four stocks

Equal weight puts 25% in each stock and resets it every month. The trend filter gives each stock its 25% while its month-end close sits above its 200-day average and moves that slot into BIL when it doesn’t. Momentum top 2 puts 50% each into the two stocks with the best return from twelve months to one month before the decision day. Each rule is a few lines because the loop does the rest. Swap in your own the same way.

sma200 = prices[STOCKS].rolling(200).mean()


def equal_weight(day):
    """25% in each stock, every month."""
    return pd.Series(1 / len(STOCKS), index=STOCKS)


def trend_filter(day):
    """Each stock keeps its 25% while its close is above its 200-day average; otherwise that slot goes to BIL."""
    w = (prices.loc[day, STOCKS] > sma200.loc[day]).astype(float) / len(STOCKS)
    w[CASH] = 1 - w.sum()
    return w


def momentum_top2(day):
    """50% each in the two stocks with the best return from 12 months to 1 month before `day`."""
    i = prices.index.get_loc(day)
    past = prices[STOCKS].iloc[i - 21] / prices[STOCKS].iloc[i - 252] - 1
    return pd.Series(0.5, index=past.nlargest(2).index)


RULES = {"equal weight": equal_weight, "trend filter": trend_filter, "momentum top 2": momentum_top2}
runs = {name: backtest(prices, rule) for name, rule in RULES.items()}
table = {name: stats(value) for name, (value, pnl, paid) in runs.items()}
for t in STOCKS:
    alone = prices.loc[START:, t]
    table[f"{t} alone"] = stats(alone / alone.iloc[0] * 10_000)
results = pd.DataFrame(table).T
print(results.round(3).to_string())
print({name: round(paid) for name, (value, pnl, paid) in runs.items()})
                 end_value   cagr  volatility  max_drawdown
equal weight     87313.614  0.276       0.304         0.411
trend filter     49400.726  0.197       0.240         0.335
momentum top 2   98223.663  0.293       0.378         0.463
ASML alone       84730.579  0.272       0.416         0.569
GOOGL alone      53071.506  0.207       0.314         0.443
LITE alone      108550.349  0.308       0.610         0.669
SPGI alone       30560.634  0.134       0.276         0.398
{'equal weight': 240, 'trend filter': 706, 'momentum top 2': 1182}

Backtest results are hypothetical, based on past data only, and are not an indication of future results.

Equal weight compounded at 27.6% a year with volatility of 30.4% and a worst fall of 41.1%. Momentum compounded at 29.3% and paid for it with 37.8% volatility and a 46.3% fall, which is what holding two stocks instead of four looks like. The trend filter had the shallowest worst fall, 33.5%, and ended at $49,401, a bit over half of what equal weight ended with.

The single-stock rows put that in context. Lumentum alone ended at $108,550, above all three rules, with 61.0% volatility and a 66.9% worst fall. S&P Global alone ended at $30,561. Every rule landed between the best stock and the worst one, and the next step shows why.

Step 5: find out which stock made the money

contrib = pd.DataFrame({name: pnl for name, (value, pnl, paid) in runs.items()}).T
contrib["costs"] = [-paid for value, pnl, paid in runs.values()]
contrib["total gain"] = contrib.sum(axis=1)
print(contrib.round(0).astype(int).to_string())
share_lite = contrib["LITE"] / contrib["total gain"]
print("Lumentum's share of each gain:", share_lite.round(3).to_dict())

decisions = month_ends(prices.index)
decisions = decisions[(decisions >= decisions[decisions < START][-1]) & (decisions < prices.index[-1])]
held = pd.DataFrame({d: trend_filter(d)[STOCKS] > 0 for d in decisions}).T
top2 = pd.DataFrame({d: momentum_top2(d).reindex(STOCKS, fill_value=0) > 0 for d in decisions}).T
print(f"months held, of {len(held)}: trend filter {held.sum().to_dict()} | momentum top 2 {top2.sum().to_dict()}")
streak = int(top2["LITE"][::-1].cumprod().sum())
lite_run = prices["LITE"].iloc[-1] / prices.loc[decisions[-streak], "LITE"]
print(f"momentum top 2 has held LITE at the last {streak} decisions, since {decisions[-streak]:%Y-%m-%d}; "
      f"LITE's adjusted close rose {lite_run:.1f}x from then to {prices.index[-1]:%Y-%m-%d}")
print("trend filter switches in or out:", (held.astype(int).diff().abs().sum()).astype(int).to_dict())
print(f"latest decision {decisions[-1]:%Y-%m-%d}: trend filter holds {list(held.columns[held.iloc[-1]])}, "
      f"momentum holds {list(top2.columns[top2.iloc[-1]])}")

# Chart: dollar gain by stock under each rule
colours = {"ASML": "#2a78d6", "GOOGL": "#1baf7a", "LITE": "#eb6834", "SPGI": "#6a3d9a", "BIL": "#a3a29e"}
fig, ax = plt.subplots(figsize=(10, 3.8))
for i, name in enumerate(RULES):
    left_pos = left_neg = 0.0
    for t, colour in colours.items():
        v = contrib.loc[name, t]
        ax.barh(i, v, left=left_pos if v >= 0 else left_neg, color=colour, label=t if i == 0 else None)
        if v >= 0:
            left_pos += v
        else:
            left_neg += v
ax.set_yticks(range(len(RULES)), list(RULES))
ax.invert_yaxis()
ax.axvline(0, color="#52514e", lw=0.8)
ax.xaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter("${x:,.0f}"))
ax.set_xlabel("Gain on $10,000 by holding, Jan 2018 to Nov 2026, before trading costs")
ax.set_title("Which stock made the money: dollar gain by holding under three rules", loc="left")
ax.set_xlim(contrib[list(colours)].clip(upper=0).sum(axis=1).min() * 1.3,
            contrib[list(colours)].clip(lower=0).sum(axis=1).max() * 1.04)
ax.legend(ncol=5, fontsize=9, loc="center right", frameon=False)
ax.spines[["top", "right"]].set_visible(False)
fig.text(0.01, -0.04, "Data: Market Data (marketdata.app). Hypothetical backtest, past data only. "
         "Code: pythonandfinancehub.com", fontsize=8, color="#52514e")
plt.savefig("four-stocks-gain-by-holding.png", dpi=150, bbox_inches="tight")

# Chart: when the trend filter held each stock
fig, ax = plt.subplots(figsize=(10, 2.8))
ax.imshow(held.T.astype(int).values, aspect="auto", cmap=plt.matplotlib.colors.ListedColormap(["#f1f0ec", "#2a78d6"]),
          extent=(plt.matplotlib.dates.date2num(held.index[0]), plt.matplotlib.dates.date2num(prices.index[-1]),
                  len(STOCKS) - 0.5, -0.5), interpolation="nearest")
ax.xaxis_date()
ax.set_yticks(range(len(STOCKS)), STOCKS)
ax.set_title("Trend filter: months each stock was held (blue) or swapped for T-bills (grey)", loc="left")
fig.text(0.01, -0.06, "Rule: hold the stock while its month-end close is above its 200-day average. Data: Market Data "
         "(marketdata.app). Hypothetical backtest. Code: pythonandfinancehub.com", fontsize=8, color="#52514e")
plt.savefig("four-stocks-trend-filter.png", dpi=150, bbox_inches="tight")

# Chart at the top: growth of $10,000 and the fall from each peak under the three rules
fig, (top, bottom) = plt.subplots(2, 1, figsize=(10, 7), sharex=True, height_ratios=[2, 1])
for (name, (value, pnl, paid)), colour in zip(runs.items(), ["#2a78d6", "#1baf7a", "#eb6834"]):
    top.plot(value.index, value, color=colour, lw=1.6, label=name)
    bottom.plot(value.index, value / value.cummax() - 1, color=colour, lw=1.1)
top.set_yscale("log")
top.set_yticks([10_000, 20_000, 50_000, 100_000])
top.yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter("${x:,.0f}"))
top.yaxis.set_minor_formatter(plt.matplotlib.ticker.NullFormatter())
top.set_ylabel("Value of $10,000 (log scale)")
top.set_title("ASML, Alphabet, Lumentum and S&P Global as one portfolio, three monthly rules, Jan 2018 to Nov 2026",
              loc="left", fontsize=11)
top.legend(loc="upper left", fontsize=9)
bottom.set_ylabel("Fall from previous peak")
bottom.yaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1.0))
for ax in (top, bottom):
    ax.spines[["top", "right"]].set_visible(False)
    ax.grid(axis="y", color="#e6e6e3", lw=0.8)
fig.text(0.01, 0.005, "Data: Market Data (marketdata.app), closes adjusted for splits and dividends. Hypothetical "
         "backtest, past data only. Code: pythonandfinancehub.com", fontsize=8, color="#52514e")
plt.tight_layout(rect=(0, 0.02, 1, 1))
plt.savefig("four-stocks-backtest.png", dpi=150, bbox_inches="tight")
                 ASML  GOOGL   LITE  SPGI   BIL  costs  total gain
equal weight    18473  12304  40125  6652     0   -240       77314
trend filter    12651   6626  21416 -2069  1483   -706       39401
momentum top 2  14391  10564  60109  4341     0  -1182       88224
Lumentum's share of each gain: {'equal weight': 0.519, 'trend filter': 0.544, 'momentum top 2': 0.681}
months held, of 107: trend filter {'ASML': 79, 'GOOGL': 82, 'LITE': 64, 'SPGI': 74} | momentum top 2 {'ASML': 65, 'GOOGL': 54, 'LITE': 46, 'SPGI': 49}
momentum top 2 has held LITE at the last 25 decisions, since 2024-10-31; LITE's adjusted close rose 8.5x from then to 2026-11-23
trend filter switches in or out: {'ASML': 11, 'GOOGL': 15, 'LITE': 21, 'SPGI': 20}
latest decision 2026-10-30: trend filter holds ['LITE', 'SPGI'], momentum holds ['ASML', 'LITE']

Backtest results are hypothetical, based on past data only, and are not an indication of future results.

Lumentum made 52% of the equal-weight gain, 54% of the trend filter’s and 68% of momentum’s. The momentum number is the odd one. The rule held Lumentum in only 46 of 107 months, fewer than any other stock, and still got two thirds of its gain from it. The timing explains it. The rule has picked Lumentum at each of the last 25 month-ends, starting with 31 October 2024, and Lumentum’s adjusted close rose 8.5-fold from that day to 23 November 2026. One stock’s run, caught once, makes a rule look clever. Whether the rule is clever takes more stocks and more runs than this.

Horizontal stacked bars of the dollar gain on 10,000 US dollars from each holding, January 2018 to November 2026, under equal weight, the trend filter and momentum top 2: Lumentum is the largest piece in all three, and S&P Global is a loss under the trend filter

The trend filter lost $2,069 on S&P Global, the only losing holding in the table. It switched S&P Global in or out 20 times. Each exit follows a month-end close below the 200-day average and each re-entry a month-end close back above it, so a stock that drifts sideways around its average gets sold low and bought back higher, again and again. BIL earned $1,483 for the filter while it sat in bills. Trading costs came to $240 for equal weight, $706 for the trend filter and $1,182 for momentum.

Grid of months from January 2018 to November 2026 showing, for ASML, Alphabet, Lumentum and S&P Global, when the 200-day trend filter held each stock and when it held Treasury bills instead

What can go wrong when you backtest multiple stocks

# 1. A stock with a shorter history: Palantir listed in September 2020
with_pltr = pd.concat([prices, daily_closes("PLTR")], axis=1)
print(f"with PLTR: first full row {with_pltr.dropna().index[0]:%Y-%m-%d}, "
      f"{len(with_pltr) - len(with_pltr.dropna())} of {len(with_pltr)} days dropped for every ticker")

# 2. Trading at the same close that produced the signal
same_close = {name: stats(backtest(prices, rule, lag=0)[0])["end_value"] for name, rule in RULES.items()}
print("traded at the signal's own close:", {k: round(v) for k, v in same_close.items()})

# 3. The same equal-weight rule without the best performer
others = [t for t in STOCKS if t != "LITE"]
no_lite = stats(backtest(prices, lambda day: pd.Series(1 / len(others), index=others))[0])
print("equal weight without LITE:", {k: round(float(v), 3) for k, v in no_lite.items()})

# Every number quoted in the text, in one place: rerun with a new END and compare
r = results
figures = {
    "n_days": len(prices.loc[START:]),
    "start": 10_000,
    "cost": 0.001,
    "w_equal": 1 / len(STOCKS),
    "w_mom": 0.5,
    "end_equal": float(r.loc["equal weight", "end_value"]),
    "end_trend": float(r.loc["trend filter", "end_value"]),
    "end_mom": float(r.loc["momentum top 2", "end_value"]),
    "cagr_equal": float(r.loc["equal weight", "cagr"]),
    "cagr_trend": float(r.loc["trend filter", "cagr"]),
    "cagr_mom": float(r.loc["momentum top 2", "cagr"]),
    "vol_equal": float(r.loc["equal weight", "volatility"]),
    "vol_trend": float(r.loc["trend filter", "volatility"]),
    "vol_mom": float(r.loc["momentum top 2", "volatility"]),
    "dd_equal": float(r.loc["equal weight", "max_drawdown"]),
    "dd_trend": float(r.loc["trend filter", "max_drawdown"]),
    "dd_mom": float(r.loc["momentum top 2", "max_drawdown"]),
    "vol_spgi": float(r.loc["SPGI alone", "volatility"]),
    "end_lite": float(r.loc["LITE alone", "end_value"]),
    "end_spgi": float(r.loc["SPGI alone", "end_value"]),
    "dd_lite": float(r.loc["LITE alone", "max_drawdown"]),
    "vol_lite": float(r.loc["LITE alone", "volatility"]),
    "gain_equal": float(contrib.loc["equal weight", "total gain"]),
    "gain_trend": float(contrib.loc["trend filter", "total gain"]),
    "lite_gain_equal": float(contrib.loc["equal weight", "LITE"]),
    "lite_share_equal": float(share_lite["equal weight"]),
    "lite_share_trend": float(share_lite["trend filter"]),
    "lite_share_mom": float(share_lite["momentum top 2"]),
    "spgi_loss_trend": float(-contrib.loc["trend filter", "SPGI"]),
    "bil_gain_trend": float(contrib.loc["trend filter", "BIL"]),
    "costs_equal": float(runs["equal weight"][2]),
    "costs_trend": float(runs["trend filter"][2]),
    "costs_mom": float(runs["momentum top 2"][2]),
    "n_months": len(held),
    "held_lite": int(held["LITE"].sum()),
    "held_spgi": int(held["SPGI"].sum()),
    "held_googl": int(held["GOOGL"].sum()),
    "held_asml": int(held["ASML"].sum()),
    "mom_lite": int(top2["LITE"].sum()),
    "mom_lite_streak": streak,
    "lite_run": float(lite_run),
    "flips_spgi": int(held["SPGI"].astype(int).diff().abs().sum()),
    "spgi_spin": float(big.iloc[0]),
    "mbgl_close": float(mbgl.iloc[0]),
    "spgi_div_2025": float(check.query("ticker == 'SPGI' and year == 2025")["10-K"].iloc[0]),
    "googl_div_2025": float(check.query("ticker == 'GOOGL' and year == 2025")["10-K"].iloc[0]),
    "pltr_dropped": int(len(with_pltr) - len(with_pltr.dropna())),
    "same_close_trend": float(same_close["trend filter"]),
    "same_close_gap_trend": float(same_close["trend filter"] - r.loc["trend filter", "end_value"]),
    "same_close_gap_equal": float(r.loc["equal weight", "end_value"] - same_close["equal weight"]),
    "end_no_lite": float(no_lite["end_value"]),
    "cagr_no_lite": float(no_lite["cagr"]),
}
with PLTR: first full row 2020-09-30, 984 of 2529 days dropped for every ticker
traded at the signal's own close: {'equal weight': 86233, 'trend filter': 51598, 'momentum top 2': 97851}
equal weight without LITE: {'end_value': 60379.873, 'cagr': 0.224, 'volatility': 0.269, 'max_drawdown': 0.433}

A ticker with a shorter history. Add Palantir, whose prices here start on 30 September 2020, and dropna() removes 984 days for every ticker. The backtest now starts in late 2020 and nothing warns you. Print the first date after every merge, or keep the gaps and have the rule spread its weights over the stocks that have a price and enough history on the decision day.

Trading at the close that produced the signal. With lag=0 the trend filter ends at $51,598, $2,197 more than with lag=1, because it trades at the very close that told it to. Equal weight, which has no signal to peek at, ends $1,081 lower from the one-day shift alone. So here the bias is about the size of the noise from moving every trade by a day, which is why you won’t catch it by looking at the results. Keep lag=1. Backtest results are hypothetical, based on past data only, and are not an indication of future results.

Hindsight in the stock list. I picked these four in November 2026, knowing how they’d done. Drop Lumentum and equal weight ends at $60,380, compounding at 22.4% a year. A fair test of a rule across several stocks picks the list the way someone could have picked it at the start, including the companies that were later delisted or taken over. Backtest results are hypothetical, based on past data only, and are not an indication of future results.

Adjusted prices get rewritten. Each new dividend or spin-off rescales the whole adjusted history, so the price levels in Step 1 will shift on a rerun and the returns should barely move. Step 2’s check catches the cases where the adjustment itself is the story, like the Mobility Global distribution.

Costs and taxes. The 0.1% cost is an assumption. Momentum paid the most because it swaps whole 50% positions, and in a taxable account every monthly sale of a winner can realise a gain that a backtest never charges.

What to watch

The figures end on 23 November 2026. Change END and rerun; the figures dict at the end of the last block holds every number quoted here, so a diff shows what moved. S&P Global’s 10-K for 2026 should show the $0.97 quarterly dividend its board approved in January 2026, per the 10-K for 2025, and Step 2 should find each payment plus the July distribution. At the 30 October 2026 decision, Lumentum was in both the trend filter and the momentum top 2, so the next few month-ends decide how much of the coming results it drives.

On the code side, resample("ME") needs a recent pandas; the old "M" alias is gone in pandas 3.0. After an SDK upgrade, rerun Step 2 against the candles endpoint documentation, which lists the adjustment defaults.

For a single portfolio with rebalancing bands, the Python portfolio backtesting post goes deeper. The backtesting library comparison runs one stock through backtesting.py, backtrader and vectorbt, the moving averages tutorial builds the 200-day average, and the SEC EDGAR API tutorial explains the XBRL calls in Step 2.

My longer company research is published on the newsletter Sector Playbook, which is available by email subscription.

Sources

Market Data, stock candles endpoint (adjustment parameters and defaults), authentication and pricing. Alphabet Inc., Form 10-K for 2022 (20-for-one stock split) and Form 10-K for 2025 (dividends). S&P Global Inc., Form 10-K for 2025 (quarterly dividends, January 2026 dividend) and Form 8-K of 2 July 2026 (Mobility Global separation). Lumentum Holdings Inc., Form 10-K for fiscal 2026 (dividend policy). ASML Holding N.V., annual report on Form 20-F for 2025. State Street SPDR Bloomberg 1-3 Month T-Bill ETF (BIL). pandas 3.0.0 release notes (removed offset aliases).

*Time: 25 minutes. Python 3.12.14, marketdata 1.3.0, matplotlib 3.11.2, numpy 2.5.4, pandas 3.1.0, requests 2.34.2. API key: a Market Data token (affiliate link) for every ticker here; history back to 2016 needs the Trader plan or higher, with a 30-day free trial (Apple works without a token). The SEC asks only for a contact in the User-Agent. Market Data provides this site’s data access. Tested 24 November 2026.*

Disclaimer

Disclosure: I have no position in SPGI. Of the other companies discussed, I hold long GOOGL shares. I have no position in ASML, LITE, BIL, MBGL, PLTR or AAPL. I also hold diversified funds (IWDA, QQQ, SPY, VWRL) that may include some of these companies. Positions checked on 24 November 2026.

Affiliate disclosure: some links in this post are affiliate links. If you buy through one, I may earn a commission at no extra cost to you. It does not change what I write about the product.

This article is general information about a listed company, written for educational purposes. It is not investment advice and not a personal recommendation to buy, sell or hold any security, and it does not take into account anyone’s financial situation or objectives. I am not a registered investment adviser or a licensed financial services provider. Figures come from company filings and the other sources linked in the text, as of the dates given, and may have changed since. I may hold positions in the securities discussed; see the disclosure above. Investment decisions call for independent research or the advice of a licensed professional.

This is my own research, done with the help of AI tools.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.