Two-panel chart, January 2018 to October 2026: growth of 10,000 US dollars in Alphabet (GOOGL) stock alone, in a 60/40 mix of GOOGL and the BIL Treasury bill fund never rebalanced, and in the same mix rebalanced yearly (log scale), with each one's fall from its previous peak below
| |

Python portfolio backtesting: how to rebalance a portfolio in Python

Updated 12 November 2026.

This Python portfolio backtesting code puts $10,000 into a mix of 60% Alphabet (GOOGL) stock and 40% in a Treasury bill fund in January 2018 and runs it through four rebalancing rules, next to buy-and-hold versions of the same mix and of Alphabet alone, on daily prices from Market Data. Rebalanced once a year, the mix fell 26.9% at its worst, in the 2022 sell-off. Left alone, the same mix fell 35.3%, and Alphabet on its own fell 44.3%. The bill for that shallower hole came at the end. By 30 October 2026 the yearly mix was worth $33,712, $2,877 less than the $36,590 of the mix nobody touched. Backtest results are hypothetical, based on past data only, and are not an indication of future results.

Every rebalanced version in this test made the same deal, a smaller fall in 2022 for less money at the end, so the real question for any rebalancing rule is how much of one it buys with the other.

Two-panel chart, January 2018 to October 2026: growth of 10,000 US dollars in Alphabet (GOOGL) stock alone, in a 60/40 mix of GOOGL and the BIL Treasury bill fund never rebalanced, and in the same mix rebalanced yearly (log scale), with each one's fall from its previous peak below

What changed since March 2025

The March 2025 version built a PortfolioBacktest class around five large tech stocks. This one runs Alphabet against a Treasury bill fund and checks the prices against Alphabet’s filings before any backtest runs.

The old code had also stopped running. It set the rebalancing frequency with the pandas aliases "Q", "M" and "Y", which pandas 3.0 removed in favour of "QE", "ME" and "YE". The crash was the polite failure. Under it sat a silent bug. The code rebalanced only when a period-end label from resample was also a trading day, so weekend quarter-ends passed without a trade and the weekly option never traded.

The Sharpe ratio now measures returns above the bill fund; the old one assumed cash earns nothing, and the bill fund here grew 25.0%. Every rebalance now pays a trading cost, and a drift band joins the calendar rules.

Step 1: get daily prices for Alphabet and a Treasury bill fund

GOOGL is Alphabet’s Class A stock. The cash side is BIL, the State Street SPDR Bloomberg 1-3 Month T-Bill ETF, which tracks Treasury bills maturing in one to three months, about as close to cash as a ticker gets. Install the client with pip install marketdata-sdk-py. Market Data serves Apple without a token, which is generous right up until you want a second company. For GOOGL and BIL, create a Market Data account (affiliate link) and set MARKETDATA_TOKEN to its token. Market Data’s pricing page gives the free plan one year of daily history and the Starter plan five, so reaching back to 2018 takes the 30-day free trial or the Trader plan or higher.

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; GOOGL and BIL need one. Set yours first:
#   export MARKETDATA_TOKEN=YOUR_TOKEN
client = MarketDataClient(token=os.environ.get("MARKETDATA_TOKEN"))
START, END = "2018-01-01", "2026-10-30"


def daily_closes(ticker, start=START, 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("GOOGL"), daily_closes("BIL")], axis=1).dropna()
print(f"{len(prices)} trading days, {prices.index[0]:%Y-%m-%d} to {prices.index[-1]:%Y-%m-%d}")
print(prices.iloc[[0, -1]].round(2).to_string())
2220 trading days, 2018-01-02 to 2026-10-30
             GOOGL    BIL
t                        
2018-01-02   53.15  73.09
2026-10-30  279.84  91.39

That’s 2,220 trading days for each ticker. The daily candles endpoint adjusts closes for splits and dividends by default, which a backtest needs, since a dividend paid out is still part of the return. It also means the first GOOGL close in the output, $53 on 2 January 2018, is a price nobody paid that day. Step 2 prints the raw close next to it.

Step 2: check the prices against Alphabet’s filings

Adjusted prices are only as good as the corporate actions behind them, and a candle row doesn’t say which ones were applied. So the code fetches the raw closes too and works backwards. The ratio of raw to adjusted close stays flat until a split or an ex-dividend date, then jumps, and the size of each jump gives the split ratio or the dividend per share.

raw = daily_closes("GOOGL", adjust_splits=False, adjustdividends=False)
factor = raw / prices["GOOGL"]          # how far each raw close sits from the adjusted one
step = factor / factor.shift()          # changes only on a split or an ex-dividend date
events = step[(step - 1).abs() > 1e-4]
split = events[events < 0.5]
dividends = raw.shift()[events.index] * (1 / events - 1)
dividends = dividends[events > 0.5]
print(f"split on {split.index[0]:%Y-%m-%d}: {1 / split.iloc[0]:.1f} new shares for each old one")
print(f"close before and after: {raw.shift()[split.index[0]]:,.2f} -> {raw[split.index[0]]:,.2f}")
print("dividend per share implied by the adjustment, on each ex-date:")
print(dividends.round(3).to_string())
print(f"first close, 2 Jan 2018: raw {raw.iloc[0]:,.2f} | adjusted {prices['GOOGL'].iloc[0]:.2f}")
split on 2022-07-18: 20.0 new shares for each old one
close before and after: 2,235.55 -> 109.03
dividend per share implied by the adjustment, on each ex-date:
t
2024-06-10    0.20
2024-09-09    0.20
2024-12-09    0.20
2025-03-10    0.20
2025-06-09    0.21
2025-09-08    0.21
2025-12-08    0.21
2026-03-09    0.21
2026-06-08    0.22
2026-09-04    0.22
first close, 2 Jan 2018: raw 1,073.21 | adjusted 53.15

Everything matches the filings, which is the boring result you want here. Alphabet’s 10-K for 2022 reports a 20-for-one stock split executed on 15 July 2022, so the first trading day on the new basis was Monday 18 July, the date the code finds. Its 10-K for 2024 says cash dividends were first paid in June 2024, and the 10-K for 2025 records the board raising the quarterly dividend 5% to $0.21 in April 2025. The 10-Q for the first quarter of 2026 reports another 5% increase to $0.22, with a record date of 8 June 2026, the same day as the ex-date in the output. The 10 dividends sit in the adjusted series, and the split leaves no trace in it at all. The last line of the output shows how big that rewrite is: a raw close on 2 January 2018 of $1,073, about twenty times the adjusted $53.

Step 3: write the backtest function

def rebalance_dates(index, freq):
    """Last trading day of each calendar period ('ME', 'QE' or 'YE'), excluding the final day of data."""
    last_days = index.to_series().resample(freq).last().dropna()
    return set(last_days) - {index[-1]}


def backtest(prices, weights, freq=None, band=None, cost=0.0, start=10_000):
    """Daily value and weights of a portfolio reset to `weights` on a calendar (`freq`) or past a drift `band`."""
    w = pd.Series(weights, dtype=float)
    px = prices[w.index]
    dates = rebalance_dates(px.index, freq) if freq else set()
    shares = w * start / px.iloc[0]
    rows = []
    for date, row in px.iterrows():
        holdings = shares * row
        total = holdings.sum()
        drift = (holdings / total - w).abs().max()
        trade = date in dates or (band is not None and drift > band)
        if trade:
            total -= (w * total - holdings).abs().sum() * cost  # cost on every dollar bought or sold
            shares = w * total / row
        rows.append({"value": total, **(holdings / holdings.sum()).to_dict(), "rebalanced": trade})
    return pd.DataFrame(rows, index=px.index)


def stats(run, cash):
    """Growth, risk and trade count of a backtest; Sharpe measured against the T-bill fund."""
    v = run["value"]
    r = v.pct_change().dropna()
    excess = r - cash.pct_change().dropna()
    years = (v.index[-1] - v.index[0]).days / 365.25
    return {
        "end_value": v.iloc[-1],
        "cagr": (v.iloc[-1] / v.iloc[0]) ** (1 / years) - 1,
        "volatility": r.std() * np.sqrt(252),
        "sharpe": excess.mean() / excess.std() * np.sqrt(252),
        "max_drawdown": -(v / v.cummax() - 1).min(),
        "rebalances": int(run["rebalanced"].sum()),
    }

The loop in backtest does the work. Each day it values the holdings at the close and asks two questions. Is today the last trading day of a rebalancing period? Has any holding drifted further from its target than the band allows? A yes to either resets the holdings to the target weights and charges cost on every dollar bought or sold. It records each day’s value after any trading cost and its weights before the trade, which Step 5 charts and prints. Nothing in it assumes two assets.

stats returns compound annual growth, annualised volatility, the worst fall from a previous peak, the number of rebalances and a Sharpe ratio: the average daily return above the bill fund’s, divided by the volatility of that difference and annualised.

How to rebalance a portfolio in Python: calendar dates or a drift band

Calendar rebalancing trades back to target on the last trading day of each month, quarter or year. Band rebalancing ignores the calendar and trades when a holding drifts a set distance from target, here 5 percentage points.

The calendar version is where the old code broke, in two ways at once:

try:
    prices.resample("Q").last()
except ValueError as err:
    print("pandas", pd.__version__, "->", str(err).split(".")[0])

labels = prices.resample("QE").last().index
labels = labels[labels < prices.index[-1]]
missed = labels[~labels.isin(prices.index)]
print(f"quarter-end labels: {len(labels)} | not a trading day: {len(missed)}")
print("for example:", ", ".join(f"{d:%a %d %b %Y}" for d in missed[:3]))
weeks = prices.resample("W").last().index
print(f"weekly labels: {len(weeks)} | on a trading day: {weeks.isin(prices.index).sum()}")
pandas 3.1.0 -> Invalid frequency: Q
quarter-end labels: 35 | not a trading day: 10
for example: Sat 31 Mar 2018, Sat 30 Jun 2018, Sun 30 Sep 2018
weekly labels: 461 | on a trading day: 0

The first line is the crash, and it’s the helpful one: pandas 3 refuses "Q" outright. The rest is the silent failure. resample("QE") labels each quarter with its calendar end date, whatever day of the week that is. Of the 35 quarter-ends in this window, 10 fell on a weekend, so a check like date in labels never fired and the portfolio drifted on into the next quarter. Weekly labels are all Sundays, so a weekly rule built that way never trades. Low turnover, at least. rebalance_dates in Step 3 sidesteps both by taking the last date that actually appears in each period.

Step 4: backtest the portfolio six ways

COST = 0.001  # 0.1% of every dollar traded, for commission and spread: an assumption
mix = {"GOOGL": 0.6, "BIL": 0.4}
runs = {
    "100% GOOGL": backtest(prices, {"GOOGL": 1.0}),
    "60/40, never rebalanced": backtest(prices, mix),
    "60/40, yearly": backtest(prices, mix, freq="YE", cost=COST),
    "60/40, quarterly": backtest(prices, mix, freq="QE", cost=COST),
    "60/40, monthly": backtest(prices, mix, freq="ME", cost=COST),
    "60/40, 5-point band": backtest(prices, mix, band=0.05, cost=COST),
}
results = pd.DataFrame({name: stats(run, prices["BIL"]) for name, run in runs.items()}).T
results["rebalances"] = results["rebalances"].astype(int)
print(results.round(3).to_string())
                         end_value   cagr  volatility  sharpe  max_drawdown  rebalances
100% GOOGL               52646.332  0.207       0.313   0.678         0.443           0
60/40, never rebalanced  36589.537  0.158       0.232   0.641         0.353           0
60/40, yearly            33712.107  0.148       0.190   0.688         0.269           8
60/40, quarterly         32339.202  0.142       0.189   0.665         0.286          35
60/40, monthly           32229.553  0.142       0.188   0.667         0.287         105
60/40, 5-point band      32917.302  0.145       0.189   0.675         0.286          17

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

Alphabet alone compounded at 20.7% a year with volatility of 31.3% and fell 44.3% from its peak. The yearly version compounded at 14.8% with volatility of 19.0% and a worst fall of 26.9%. Its Sharpe ratio, 0.69, was slightly higher than Alphabet’s 0.68, so per unit of risk the two came out about even. The quarterly, monthly and band versions landed within a percentage point of each other on growth and on the worst fall, and the band needed 17 rebalances to the monthly rule’s 105. About the same result for about a sixth of the trades.

The mix nobody touched is the odd one out. It fell 35.3%, against 26.9% to 28.7% for the rebalanced versions, because by 2022 it had stopped being a 60/40 portfolio. Nobody decided that. Alphabet’s gains decided it.

Step 5: look at the drawdowns and the drift

def worst_drawdowns(values, n=3):
    """Start, bottom, recovery date and depth of the n deepest falls from a previous peak."""
    peak = values.cummax()
    dd = values / peak - 1
    out = []
    for _, d in dd.groupby((dd == 0).cumsum()):
        if d.min() < 0:
            bottom = d.idxmin()
            back = values.loc[bottom:][values.loc[bottom:] >= peak[bottom]]
            out.append({"peak": d.index[0], "bottom": bottom,
                        "recovered": back.index[0] if len(back) else pd.NaT, "fall": -d.min()})
    return pd.DataFrame(out).nlargest(n, "fall").reset_index(drop=True)


for name in ["100% GOOGL", "60/40, yearly"]:
    print(name)
    print(worst_drawdowns(runs[name]["value"]).round({"fall": 3}).to_string())

untouched, yearly = runs["60/40, never rebalanced"], runs["60/40, yearly"]
print(f"GOOGL share of the untouched mix: {untouched['GOOGL'].iloc[-1]:.1%} on {prices.index[-1]:%Y-%m-%d}, "
      f"peak {untouched['GOOGL'].max():.1%} on {untouched['GOOGL'].idxmax():%Y-%m-%d}")
print("Alphabet's weight on each yearly rebalance day, before the trade:")
print(yearly.loc[yearly["rebalanced"], "GOOGL"].round(3).to_string())

# Chart: how far each portfolio's Alphabet weight drifted from 60%
fig, ax = plt.subplots(figsize=(10, 4.5))
for name, colour in [("60/40, never rebalanced", "#eb6834"), ("60/40, yearly", "#1baf7a"),
                     ("60/40, 5-point band", "#6a3d9a")]:
    ax.plot(runs[name].index, runs[name]["GOOGL"], color=colour, lw=1.3, label=name)
ax.axhline(0.6, color="#52514e", ls="--", lw=0.9)
ax.yaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1.0))
ax.set_ylabel("Alphabet's share of the portfolio")
ax.set_title("Alphabet (GOOGL) weight in a 60/40 mix with T-bills, Jan 2018 to Oct 2026", loc="left")
ax.legend(loc="upper left", fontsize=9)
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). Hypothetical backtest. Code: pythonandfinancehub.com",
         fontsize=8, color="#52514e")
plt.savefig("googl-weight-drift.png", dpi=150, bbox_inches="tight")

# Chart: growth of $10,000 and each portfolio's fall from its previous peak (the chart at the top)
fig, (top, bottom) = plt.subplots(2, 1, figsize=(10, 7), sharex=True, height_ratios=[2, 1])
show = {"100% GOOGL": "#2a78d6", "60/40, never rebalanced": "#eb6834", "60/40, yearly": "#1baf7a"}
for name, colour in show.items():
    v = runs[name]["value"]
    top.plot(v.index, v, color=colour, lw=1.6, label=name)
    bottom.plot(v.index, v / v.cummax() - 1, color=colour, lw=1.2)
top.set_yscale("log")
top.set_yticks([10_000, 20_000, 30_000, 50_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("Alphabet (GOOGL) alone vs a 60/40 mix with T-bills (BIL), Jan 2018 to Oct 2026", loc="left")
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. Code: pythonandfinancehub.com", fontsize=8, color="#52514e")
plt.tight_layout(rect=(0, 0.02, 1, 1))
plt.savefig("googl-chart.png", dpi=150, bbox_inches="tight")
100% GOOGL
        peak     bottom  recovered   fall
0 2021-11-18 2022-11-03 2024-01-25  0.443
1 2020-02-19 2020-03-23 2020-07-10  0.309
2 2026-05-13 2026-10-30        NaT  0.304
60/40, yearly
        peak     bottom  recovered   fall
0 2021-11-18 2022-11-03 2023-08-30  0.269
1 2020-02-19 2020-03-23 2020-07-10  0.194
2 2026-05-13 2026-10-30        NaT  0.194
GOOGL share of the untouched mix: 86.3% on 2026-10-30, peak 90.2% on 2026-05-13
Alphabet's weight on each yearly rebalance day, before the trade:
t
2018-12-31    0.589
2019-12-31    0.653
2020-12-31    0.662
2021-12-31    0.713
2022-12-30    0.474
2023-12-29    0.694
2024-12-31    0.660
2025-12-31    0.705

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

Both portfolios had their deepest fall from November 2021 to November 2022, and the yearly mix regained its old high in August 2023, about five months before Alphabet did. The third row is still open: its bottom date is the last day of data.

Line chart of Alphabet's weight in three 60/40 GOOGL and T-bill portfolios from January 2018 to October 2026: never rebalanced, drifting up to about 90%; rebalanced yearly, reset to 60% each December; and rebalanced on a 5-point band, staying close to 60% and trading whenever it strays more than 5 points

Drift does the damage. The stock ended the window at 5.3 times its first adjusted close while the bill fund grew 25.0%, so the stock’s share of the untouched mix kept climbing. It hit 90.2% on 13 May 2026 and was still 86.3% at the end of October.

The weights at the end of the output explain why the rebalanced versions ended lower. On 6 of its 8 rebalances the yearly rule found Alphabet above its target weight, sold stock and moved the money into bills. The other two, at the ends of 2018 and 2022 after declines, bought stock. A rule that trims the winner six times out of eight trails it for as long as it keeps winning, and that’s where the $2,877 from the opening went. Which frequency came out ahead depends on where the dates landed around a few large moves in one stock, so I wouldn’t read the ranking as a finding about frequency in general.

What can go wrong

bil_raw = daily_closes("BIL", adjust_splits=False, adjustdividends=False)
print(f"BIL raw close: {bil_raw.iloc[0]:.2f} -> {bil_raw.iloc[-1]:.2f} | adjusted: "
      f"{prices['BIL'].iloc[0]:.2f} -> {prices['BIL'].iloc[-1]:.2f}")
naive = backtest(raw.to_frame(), {"GOOGL": 1.0})["value"]
naive_dd = naive / naive.cummax() - 1
print(f"100% GOOGL on raw closes: worst fall {-naive_dd.min():.1%} on {naive_dd.idxmin():%Y-%m-%d}, "
      f"ends at ${naive.iloc[-1]:,.0f}")

fig, ax = plt.subplots(figsize=(10, 4.5))
ax.plot(runs["100% GOOGL"].index, runs["100% GOOGL"]["value"], color="#2a78d6", lw=1.4,
        label="adjusted closes (splits and dividends)")
ax.plot(naive.index, naive, color="#b2182b", lw=1.2, label="raw closes")
ax.axvline(split.index[0], color="#52514e", ls=":", lw=0.9)
ax.annotate("20-for-1 split, 18 Jul 2022", (split.index[0], naive.iloc[0] * 0.6), xytext=(6, 0),
            textcoords="offset points", fontsize=9, color="#52514e")
ax.set_yscale("log")
ax.yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter("${x:,.0f}"))
ax.set_ylabel("Value of $10,000 in GOOGL (log scale)")
ax.set_title("The same backtest on raw and on adjusted closes, Jan 2018 to Oct 2026", loc="left")
ax.legend(loc="lower left", fontsize=9)
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). Hypothetical backtest. Code: pythonandfinancehub.com",
         fontsize=8, color="#52514e")
plt.savefig("googl-raw-vs-adjusted.png", dpi=150, bbox_inches="tight")

# Every number quoted in the text, in one place: rerun with a new END and compare
r = results
figures = {
    "n_days": len(prices),
    "start": 10_000,
    "n_dividends": len(dividends),
    "cost": COST,
    "q_labels": len(labels),
    "q_missed": len(missed),
    "end_never": float(r.loc["60/40, never rebalanced", "end_value"]),
    "end_yearly": float(r.loc["60/40, yearly", "end_value"]),
    "cagr_goog": float(r.loc["100% GOOGL", "cagr"]),
    "cagr_yearly": float(r.loc["60/40, yearly", "cagr"]),
    "vol_goog": float(r.loc["100% GOOGL", "volatility"]),
    "vol_yearly": float(r.loc["60/40, yearly", "volatility"]),
    "sharpe_goog": float(r.loc["100% GOOGL", "sharpe"]),
    "sharpe_yearly": float(r.loc["60/40, yearly", "sharpe"]),
    "dd_goog": float(r.loc["100% GOOGL", "max_drawdown"]),
    "dd_never": float(r.loc["60/40, never rebalanced", "max_drawdown"]),
    "dd_yearly": float(r.loc["60/40, yearly", "max_drawdown"]),
    "dd_monthly": float(r.loc["60/40, monthly", "max_drawdown"]),
    "trades_yearly": int(r.loc["60/40, yearly", "rebalances"]),
    "trades_monthly": int(r.loc["60/40, monthly", "rebalances"]),
    "trades_band": int(r.loc["60/40, 5-point band", "rebalances"]),
    "share_end": float(untouched["GOOGL"].iloc[-1]),
    "share_peak": float(untouched["GOOGL"].max()),
    "naive_dd": float(-naive_dd.min()),
    "naive_end": float(naive.iloc[-1]),
    "bil_growth": float(prices["BIL"].iloc[-1] / prices["BIL"].iloc[0] - 1),
    "bil_raw_change": float(abs(bil_raw.iloc[-1] / bil_raw.iloc[0] - 1)),
    "goog_multiple": float(prices["GOOGL"].iloc[-1] / prices["GOOGL"].iloc[0]),
    "adj_first": float(prices["GOOGL"].iloc[0]),
    "raw_first": float(raw.iloc[0]),
    "sells_yearly": int((yearly.loc[yearly["rebalanced"], "GOOGL"] > 0.6).sum()),
    "gap_yearly": float(r.loc["60/40, never rebalanced", "end_value"] - r.loc["60/40, yearly", "end_value"]),
}
BIL raw close: 91.41 -> 91.70 | adjusted: 73.09 -> 91.39
100% GOOGL on raw closes: worst fall 97.2% on 2022-11-03, ends at $2,608

Raw closes. On unadjusted closes the split looks like a crash. The all-GOOGL portfolio falls 97.2% and ends at $2,608, because the code sees the price drop to a twentieth overnight and has no idea each share became twenty. A backtest that shows Alphabet losing nearly everything in 2022 is reporting a data problem. The bill fund fails the other way. It pays its income out monthly, so its raw price moved only 0.3% over the window and the interest disappears from the backtest. Adjusted closes, checked as in Step 2, fix both. Backtest results are hypothetical, based on past data only, and are not an indication of future results.

Log-scale chart of 10,000 US dollars invested in Alphabet (GOOGL) from January 2018 to October 2026, once on closes adjusted for splits and dividends and once on raw closes, where the raw series collapses at the 20-for-1 split on 18 July 2022

Adjusted prices get rescaled. Each new dividend or distribution rescales the whole adjusted history. The adjusted BIL close for 30 October 2026 sits below the raw one because BIL went ex-distribution on 2 November, before the script ran. Returns stay the same; the price levels in the output will shift slightly on a rerun.

Look-ahead bias. The function trades at the same close it uses to value the portfolio. A calendar rule only borrows that price for the fill; a strategy that reacts to the close also uses it to decide, which builds in information it couldn’t have had. Filling at the next day’s open removes both problems.

Hindsight in the stock choice. Alphabet was picked in 2026, with its record since 2018 already known. A backtest across many stocks also needs the companies that were delisted or taken over along the way, or its results lean towards the winners.

Costs and taxes. The 0.1% cost per dollar traded is an assumption, and in a taxable account each rebalance that sells a winner can realise a gain. The monthly rule traded 105 times to the yearly rule’s 8. Each one pays the assumed cost; whether it also owes tax depends on the gain it realises and the account.

What to watch

The figures end on 30 October 2026. Change END and rerun; the figures dict at the end of the last block holds every number quoted here, so it shows which ones moved. Two things will test them. Alphabet’s 10-K for 2026 will list the year’s dividends, and Step 2 should find each one; a dividend it misses or invents means the adjustment is wrong, and so is every backtest built on it. And the third drawdown in Step 5 is still open: the Alphabet-only row gets a recovery date only when Alphabet’s adjusted close gets back above its 13 May 2026 peak.

Two outside changes could break the code: a new default in the candles endpoint (the documentation lists them; rerun Step 2 after an SDK upgrade) and more removed pandas aliases, so pin the version you tested with.

The earlier parts of this series build the pieces that feed backtest: a simple portfolio with real-world data, the efficient frontier, risk management techniques and beta and dollar sensitivity. For company data from filings, the SEC EDGAR API tutorial pulls Alphabet’s financial statements with no API key.

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). Alphabet Inc., Form 10-K for 2022 (20-for-one stock split), Form 10-K for 2024 (first dividends, June 2024), Form 10-K for 2025 (dividend raised to $0.21) and Form 10-Q for the first quarter of 2026 (dividend raised to $0.22). State Street SPDR Bloomberg 1-3 Month T-Bill ETF (BIL) (index tracked, distribution frequency). pandas 3.0.0 release notes (removed offset aliases).

*Time: 20 minutes. Python 3.12.14, marketdata 1.3.0, matplotlib 3.11.2, numpy 2.5.4, pandas 3.1.0. API key: a Market Data token (affiliate link) for GOOGL and BIL; the history back to 2018 needs the 30-day free trial or the Trader plan or higher (Apple works without a token). Market Data provides this site’s data access. Tested 12 November 2026.*

Disclaimer

Disclosure: I hold long GOOGL shares. I have no position in the other companies discussed (BIL). I also hold diversified funds (IWDA, QQQ, SPY, VWRL) that may include some of these companies. Positions checked on 12 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.