How to Calculate Split-Adjusted Stock Returns in Python
A return computed on the raw close breaks the day a stock splits or issues bonus shares: the price drops and the formula reports a loss. The prices endpoint gives you adjusted_close and the adjustment_factor for exactly this reason.
import httpx
API = "https://bharatstockapi.com"
HEADERS = {"X-API-Key": "bsk_live_..."} # your key from the dashboard
import pandas as pd
r = httpx.get(f"{API}/v1/stocks/RELIANCE/prices", headers=HEADERS,
params={"from": "2024-01-01", "page_size": 1000})
r.raise_for_status()
df = pd.DataFrame(r.json()["data"])
df["trade_date"] = pd.to_datetime(df["trade_date"])
s = df.sort_values("trade_date").set_index("trade_date")["adjusted_close"]
total_return = s.iloc[-1] / s.iloc[0] - 1
years = (s.index[-1] - s.index[0]).days / 365.25
cagr = (s.iloc[-1] / s.iloc[0]) ** (1 / years) - 1
print(f"total {total_return:.1%}, CAGR {cagr:.1%}")Check your inputs
- Sort ascending before taking first and last. The API returns newest first.
- Dividends are not in
adjusted_close. Pull them from corporate actions if you need total return. - Free keys only see the last year of prices, so a multi-year CAGR needs a paid plan.
Background: what CAGR means.