The screen says the strategy returned 18.4% this year. The benchmark returned 11.2%. The difference looks like alpha until you discover that the portfolio was mostly invested in high-momentum technology stocks during a strong technology rally.
That distinction matters. A portfolio can outperform because it took a deliberate risk factor, because it selected securities intelligently, or because it simply held more of the market’s winning exposures. Without attribution, the first two cases are easy to mistake for the third.
Performance attribution provides the missing decomposition. It separates results into market movement, sector allocation, security selection, and residual factor exposure so that you can answer a more useful question than “did the strategy make money?”
This article builds a practical attribution system for a US-equity strategy. It covers Brinson sector attribution, Fama–French factor exposure, the statistical assumptions behind each method, and a Python implementation that combines them into one reporting pipeline.
1. Why a Profit-and-Loss Statement Is Not Attribution
A portfolio return tells you what happened. It does not tell you why it happened.
Suppose the strategy returned 18.4% while the benchmark returned 11.2%. The arithmetic excess return is 7.2 percentage points, but that figure does not identify the source of performance. The excess could come from overweighting a strong sector, selecting securities that beat their sector, taking a concentrated factor bet, or some combination of those effects.
A useful attribution report should separate at least four sources of return:
| Return source | Question it answers | Typical implementation |
|---|---|---|
| Market exposure | How much came from holding the market? | Market beta or benchmark interaction |
| Sector allocation | How much came from overweighting or underweighting sectors? | Brinson allocation |
| Security selection | How much came from choosing securities within sectors? | Brinson selection |
| Factor exposure | How much came from systematic style or factor bets? | Fama–French regression |
| Residual alpha | How much remains after modeling systematic exposures? | Regression intercept or unexplained return |
These methods answer different questions, so they should not be treated as interchangeable.
Brinson attribution partitions a portfolio’s excess return by sector and security-selection decisions. Fama–French regression measures exposure to market, size, and value factors. Combining the two gives a more complete picture: Brinson describes the portfolio’s allocation decisions, while factor analysis describes the systematic risks embedded in the resulting holdings.
1.1 A Small Attribution Example
The following figures are illustrative rather than a historical backtest result.
| Metric | Portfolio | Benchmark |
|---|---|---|
| Total return | 18.4% | 11.2% |
| Excess return | — | 7.2% |
| Market beta | 0.72 | 1.00 |
| Regression R² | 61% | — |
| Factor-model alpha | 4.6% annualised | — |
| Residual volatility | 6.1% annualised | — |
A Brinson decomposition might produce:
| Attribution component | Contribution |
|---|---|
| Sector allocation | +2.1% |
| Security selection | +3.9% |
| Allocation-selection interaction | +1.2% |
| Total active return | +7.2% |
The factor model might then show that the portfolio’s market beta was below one, while its positive alpha remained meaningful after accounting for size and value exposures.
That combination suggests a specific narrative: the strategy generated some security-selection skill, but part of its apparent outperformance also reflected sector positioning and a factor profile that differed from the benchmark.
2. The Data Model
A reliable attribution engine needs more than portfolio returns. It needs the portfolio’s actual holdings, a benchmark, sector classifications, and factor time series aligned to the same dates.
2.1 Required Inputs
Use the following input structure:
data/
├── portfolio_weights.csv
├── portfolio_returns.csv
├── benchmark_weights.csv
├── benchmark_returns.csv
├── sector_map.csv
└── factors.csv
A practical portfolio holdings file should contain:
| date | symbol | weight | sector | market_value |
|---|---|---|---|---|
| 2024-01-31 | AAPL | 0.08 | Information Technology | 8,000,000 |
| 2024-01-31 | MSFT | 0.07 | Information Technology | 7,000,000 |
| 2024-01-31 | JPM | 0.05 | Financials | 5,000,000 |
The benchmark file should use the same conventions. Weight fields should sum to one, or the code should normalize them explicitly before calculating attribution.
2.2 Alignment Is a Modeling Decision
Attribution is highly sensitive to date alignment. A monthly backtest can use month-end holdings and daily total returns, or it can use beginning-of-period holdings with monthly returns. Both are valid, but they answer different questions.
For a monthly strategy, a practical convention is:
- Form the portfolio at the previous month-end.
- Hold those weights through the next month.
- Calculate monthly portfolio and benchmark returns.
- Attribute the realized return using the holdings and sector map observed at the start of the period.
Do not mix end-of-month weights with beginning-of-month returns without explaining the lookahead or timing assumption.
2.3 Data Availability and Boundaries
For historical US-equity backtests, daily or monthly OHLCV data is usually sufficient for a first attribution implementation. TickDB’s /v1/market/kline endpoint can provide cleaned and aligned historical OHLCV for US equities. The trades endpoint does not provide US-equity tick data, and depth support for US equities is limited to L1. Neither limitation prevents a portfolio-level Brinson or factor analysis.
The attribution engine should treat vendor data as an input, not as an assumption. Validate timestamps, duplicate rows, missing symbols, and unexplained weight changes before calculating performance.
3. Brinson Attribution: Decomposing Portfolio Decisions
Brinson attribution begins with the difference between portfolio and benchmark weights.
For sector (i):
[
w_{p,i} = \text{portfolio weight in sector } i
]
[
w_{b,i} = \text{benchmark weight in sector } i
]
The allocation effect compares the portfolio’s sector weight with the benchmark weight and applies the benchmark’s sector return:
[
A_i = (w_{p,i} - w_{b,i})R_{b,i}
]
The selection effect asks whether securities within a sector outperformed the benchmark sector:
[
S_i = w_{p,i}(R_{p,i} - R_{b,i})
]
The interaction effect captures the additional effect of combining an active sector weight with active security selection:
[
I_i = (w_{p,i} - w_{b,i})(R_{p,i} - R_{b,i})
]
The total active return is then:
[
R_p - R_b = \sum_i(A_i + S_i + I_i)
]
This is the Brinson-Fachler-style decomposition used here. Different textbooks use slightly different allocation formulas. The important property is that the attribution components must reconcile to the portfolio’s realized excess return.
3.1 Security-Level Selection
The sector-level formula is useful for reporting, but security-level attribution gives a better explanation of which positions contributed to selection.
For each portfolio security (j):
[
S_j = w_{p,j}(R_{p,j} - R_{b,j})
]
where (R_{b,j}) is the benchmark return of the security or the corresponding benchmark sleeve.
The engine below aggregates these security-level effects into sector selection. It also records the largest positive and negative contributors for debugging.
3.2 Why Allocation and Selection Are Not Independent
Suppose the portfolio underweights a sector and selects securities that outperform within that sector. The allocation and selection effects can interact. A regression-free attribution table can make this interaction look like a source of skill even when the portfolio’s position size reduced the economic impact of the selection.
Always publish the interaction term rather than silently folding it into selection.
4. Fama–French Factor Attribution
Brinson analysis does not directly identify market, size, or value exposure. For that, use a time-series factor regression.
A standard Fama–French specification is:
[
R_{p,t} - R_{f,t}
\alpha + \beta_M(MKT_t - R_{f,t})
- \beta_S(SMB_t)
- \beta_V(HML_t)
- \epsilon_t
]
The interpretation is straightforward:
- (\beta_M) measures market exposure.
- (\beta_S) measures size exposure.
- (\beta_V) measures value exposure.
- (\alpha) estimates return unexplained by the included factors.
- (R^2) measures how much of the return variation the factors explain.
For a multi-period report, use factor returns over the same frequency as the portfolio returns. If the portfolio is evaluated monthly, use monthly factor observations rather than mixing daily factors into a monthly return series.
4.1 Factor Exposure Is Not Alpha
A portfolio can have a high market beta and generate a positive total return without producing genuine alpha. If the benchmark itself rose because of a strong factor environment, part of the return is simply exposure.
A factor attribution table should therefore include both:
- factor contribution to total return; and
- residual performance after factor adjustment.
One common approximation for factor contribution is:
[
C_{f,t} = \beta_{f,t-1}(F_t - R_{f,t})
]
The lagged beta avoids using information from the future when estimating the exposure used to explain a realized return.
4.2 Choosing the Factor Set
The original three-factor model is interpretable, but it may be insufficient for a strategy whose behavior is driven by momentum, quality, or low volatility.
A practical progression is:
| Model | Use case | Risk |
|---|---|---|
| Market + size + value | General baseline | May misclassify style exposure |
| Momentum extension | Trend and growth strategies | Requires consistent factor definitions |
| Quality or profitability extension | Fundamental and quality strategies | More data and classification assumptions |
| Custom factors | Research or portfolio-specific risk | Harder to compare and audit |
Do not add factors merely because they improve (R^2). A higher (R^2) can reflect overfitting, especially with a short sample.
4.3 Statistical Reliability
Factor regression should report more than coefficients. Include:
- the number of observations;
- the estimation frequency;
- the factor-return source;
- (R^2) and adjusted (R^2);
- standard errors;
- confidence intervals;
- residual autocorrelation diagnostics;
- the regression period.
For example, a monthly regression over 36 observations has much less statistical power than a daily regression over 1,260 observations. The coefficient may look precise while still being economically unstable.
5. Reference Architecture
A production attribution system should separate data acquisition, normalization, attribution, and reporting.
┌──────────────────────┐
│ Data acquisition │
│ Holdings, prices, │
│ benchmark, factors │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Validation │
│ Dates, symbols, │
│ weights, duplicates │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Return engine │
│ Portfolio / benchmark│
│ sector and factor │
│ aggregation │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Attribution engine │
│ Brinson effects │
│ factor exposures │
│ residual alpha │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Reporting │
│ HTML, CSV, dashboard,│
│ research notes │
└──────────────────────┘
The reporting layer should be deterministic. Given the same input files, configuration, and code version, it should produce the same attribution table.
6. Production-Grade Python Implementation
The following implementation assumes that the input data already exists as local CSV files. It uses pandas and numpy for calculations and statsmodels for the factor regression.
Install the dependencies:
pip install pandas numpy statsmodels
6.1 Input Configuration
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class AttributionConfig:
data_dir: Path
portfolio_weights_file: str = "portfolio_weights.csv"
portfolio_returns_file: str = "portfolio_returns.csv"
benchmark_weights_file: str = "benchmark_weights.csv"
benchmark_returns_file: str = "benchmark_returns.csv"
sector_map_file: str = "sector_map.csv"
factors_file: str = "factors.csv"
min_factor_observations: int = 24
6.2 Validation and Data Loading
import numpy as np
import pandas as pd
REQUIRED_WEIGHT_COLUMNS = {"date", "symbol", "weight"}
REQUIRED_RETURN_COLUMNS = {"date", "symbol", "return"}
REQUIRED_FACTOR_COLUMNS = {"date", "market", "size", "value"}
def _read_dates(series: pd.Series) -> pd.Series:
return pd.to_datetime(series, errors="raise").dt.to_period("M").dt.to_timestamp()
def load_inputs(config: AttributionConfig) -> dict[str, pd.DataFrame]:
root = config.data_dir
frames = {
"portfolio_weights": pd.read_csv(root / config.portfolio_weights_file),
"portfolio_returns": pd.read_csv(root / config.portfolio_returns_file),
"benchmark_weights": pd.read_csv(root / config.benchmark_weights_file),
"benchmark_returns": pd.read_csv(root / config.benchmark_returns_file),
"sector_map": pd.read_csv(root / config.sector_map_file),
"factors": pd.read_csv(root / config.factors_file),
}
for name, frame in frames.items():
if "date" not in frame.columns:
raise ValueError(f"{name} is missing required column: date")
frame["date"] = _read_dates(frame["date"])
frames[name] = frame
for name in ("portfolio_weights", "benchmark_weights"):
missing = REQUIRED_WEIGHT_COLUMNS - set(frames[name].columns)
if missing:
raise ValueError(f"{name} is missing columns: {sorted(missing)}")
for name in ("portfolio_returns", "benchmark_returns"):
missing = REQUIRED_RETURN_COLUMNS - set(frames[name].columns)
if missing:
raise ValueError(f"{name} is missing columns: {sorted(missing)}")
missing_factors = REQUIRED_FACTOR_COLUMNS - set(frames["factors"].columns)
if missing_factors:
raise ValueError(f"factors is missing columns: {sorted(missing_factors)}")
for name in ("portfolio_weights", "benchmark_weights"):
if frames[name].duplicated(["date", "symbol"]).any():
raise ValueError(f"{name} contains duplicate date/symbol rows")
for name in ("portfolio_returns", "benchmark_returns"):
if frames[name].duplicated(["date", "symbol"]).any():
raise ValueError(f"{name} contains duplicate date/symbol rows")
if frames["sector_map"].duplicated(["symbol"]).any():
raise ValueError("sector_map contains duplicate symbols")
return frames
def normalize_weights(frame: pd.DataFrame) -> pd.DataFrame:
result = frame.copy()
result["weight"] = pd.to_numeric(result["weight"], errors="raise")
if (result["weight"] < 0).any():
raise ValueError("This implementation does not support short positions")
totals = result.groupby("date")["weight"].sum()
invalid = totals[(totals <= 0) | (totals.isna())]
if not invalid.empty:
raise ValueError(f"Invalid total portfolio weights: {invalid.to_dict()}")
result["weight"] = result["weight"] / result["date"].map(totals)
return result
Short positions require an explicit multi-asset or derivative-aware implementation. Silently allowing negative weights would make the attribution equations ambiguous.
6.3 Brinson Attribution
def calculate_brinson(
portfolio_weights: pd.DataFrame,
benchmark_weights: pd.DataFrame,
portfolio_returns: pd.DataFrame,
benchmark_returns: pd.DataFrame,
sector_map: pd.DataFrame,
) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Calculate sector-level Brinson-Fachler attribution.
Returns:
sector_table: sector-level allocation, selection, interaction, and total.
security_table: security-level selection contributions.
"""
portfolio_weights = normalize_weights(portfolio_weights)
benchmark_weights = normalize_weights(benchmark_weights)
sector_map = sector_map[["symbol", "sector"]].copy()
if sector_map["sector"].isna().any():
raise ValueError("sector_map contains missing sector labels")
portfolio_weights = portfolio_weights.merge(
sector_map, on="symbol", how="left", validate="many_to_one"
)
benchmark_weights = benchmark_weights.merge(
sector_map, on="symbol", how="left", validate="many_to_one"
)
for name, frame in (
("portfolio_weights", portfolio_weights),
("benchmark_weights", benchmark_weights),
):
if frame["sector"].isna().any():
missing = sorted(
frame.loc[frame["sector"].isna(), "symbol"].unique().tolist()
)
raise ValueError(f"{name} contains symbols without sector labels: {missing}")
portfolio_returns = portfolio_returns.merge(
sector_map, on="symbol", how="left", validate="many_to_one"
)
benchmark_returns = benchmark_returns.merge(
sector_map, on="symbol", how="left", validate="many_to_one"
)
if portfolio_returns["sector"].isna().any():
raise ValueError("portfolio returns contain symbols without sector labels")
# Align portfolio and benchmark returns by date and symbol.
returns = portfolio_returns.merge(
benchmark_returns[["date", "symbol", "return"]],
on=["date", "symbol"],
how="inner",
suffixes=("_portfolio", "_benchmark"),
)
if returns.empty:
raise ValueError("No overlapping portfolio and benchmark returns")
weights = portfolio_weights.merge(
benchmark_weights[["date", "symbol", "weight"]],
on=["date", "symbol"],
how="left",
suffixes=("_portfolio", "_benchmark"),
)
weights["weight_benchmark"] = weights["weight_benchmark"].fillna(0.0)
returns = returns.merge(
weights[["date", "symbol", "weight_portfolio", "weight_benchmark"]],
on=["date", "symbol"],
how="left",
)
returns["weight_portfolio"] = returns["weight_portfolio"].fillna(0.0)
returns["weight_benchmark"] = returns["weight_benchmark"].fillna(0.0)
# Security-level selection contribution.
returns["selection_effect"] = returns["weight_portfolio"] * (
returns["return_portfolio"] - returns["return_benchmark"]
)
security_table = (
returns.groupby(["date", "symbol", "sector"], as_index=False)
.agg(
selection_effect=("selection_effect", "sum"),
portfolio_return=("return_portfolio", "sum"),
benchmark_return=("return_benchmark", "sum"),
portfolio_weight=("weight_portfolio", "sum"),
benchmark_weight=("weight_benchmark", "sum"),
)
)
sector_returns = (
returns.groupby(["date", "sector"], as_index=False)
.agg(
portfolio_return=("return_portfolio", "sum"),
benchmark_return=("return_benchmark", "sum"),
portfolio_weight=("weight_portfolio", "sum"),
benchmark_weight=("weight_benchmark", "sum"),
)
)
sector_returns["allocation_effect"] = (
sector_returns["portfolio_weight"] - sector_returns["benchmark_weight"]
) * sector_returns["benchmark_return"]
sector_returns["selection_effect"] = (
sector_returns["portfolio_weight"]
* (sector_returns["portfolio_return"] - sector_returns["benchmark_return"])
)
sector_returns["interaction_effect"] = (
sector_returns["portfolio_weight"] - sector_returns["benchmark_weight"]
) * (
sector_returns["portfolio_return"] - sector_returns["benchmark_return"]
)
sector_returns["total_active_return"] = (
sector_returns["allocation_effect"]
+ sector_returns["selection_effect"]
+ sector_returns["interaction_effect"]
)
return sector_returns, security_table
The implementation above assumes that the returns file contains asset-level period returns and that benchmark returns are available for the same symbols. If the benchmark is represented by index-level returns instead, use a benchmark sleeve model rather than manufacturing benchmark security returns.
6.4 Factor Regression
import statsmodels.api as sm
def calculate_factor_attribution(
portfolio_returns: pd.DataFrame,
factors: pd.DataFrame,
min_observations: int = 24,
) -> dict[str, object]:
"""Estimate a monthly Fama-French three-factor regression."""
portfolio_series = (
portfolio_returns.groupby("date", as_index=True)["return"]
.sum()
.sort_index()
)
factor_data = factors.set_index("date").sort_index()
merged = pd.concat(
[portfolio_series.rename("portfolio_return"), factor_data],
axis=1,
join="inner",
).dropna()
if len(merged) < min_observations:
raise ValueError(
f"Only {len(merged)} observations available; "
f"at least {min_observations} are required"
)
if not np.isfinite(merged.to_numpy()).all():
raise ValueError("Factor regression contains non-finite values")
excess_portfolio = merged["portfolio_return"]
excess_market = merged["market"]
excess_size = merged["size"]
excess_value = merged["value"]
x = sm.add_constant(
pd.concat(
[excess_market, excess_size, excess_value],
axis=1,
)
)
x.columns = ["const", "market", "size", "value"]
model = sm.OLS(excess_portfolio, x).fit(cov_type="HAC", cov_kwds={"maxlags": 3})
return {
"model": model,
"observations": len(merged),
"alpha": float(model.params["const"]),
"market_beta": float(model.params["market"]),
"size_beta": float(model.params["size"]),
"value_beta": float(model.params["value"]),
"r_squared": float(model.rsquared),
"adjusted_r_squared": float(model.rsquared_adj),
"residual_volatility": float(np.std(model.resid, ddof=1)),
}
The HAC covariance estimator is useful when monthly observations contain autocorrelation or heteroskedasticity. It does not repair a short sample, but it avoids assuming that every monthly error is independent.
6.5 Reporting
def build_report(
sector_table: pd.DataFrame,
security_table: pd.DataFrame,
factor_result: dict[str, object],
) -> dict[str, object]:
sector_summary = (
sector_table.groupby("sector", as_index=False)
.agg(
allocation_effect=("allocation_effect", "sum"),
selection_effect=("selection_effect", "sum"),
interaction_effect=("interaction_effect", "sum"),
total_active_return=("total_active_return", "sum"),
)
.sort_values("total_active_return", ascending=False)
)
top_positive = (
security_table.sort_values("selection_effect", ascending=False)
.head(10)[["date", "symbol", "sector", "selection_effect"]]
)
top_negative = (
security_table.sort_values("selection_effect", ascending=True)
.head(10)[["date", "symbol", "sector", "selection_effect"]]
)
return {
"sector_attribution": sector_summary,
"top_positive_contributors": top_positive,
"top_negative_contributors": top_negative,
"factor_attribution": {
"observations": factor_result["observations"],
"alpha": factor_result["alpha"],
"market_beta": factor_result["market_beta"],
"size_beta": factor_result["size_beta"],
"value_beta": factor_result["value_beta"],
"r_squared": factor_result["r_squared"],
"adjusted_r_squared": factor_result["adjusted_r_squared"],
"residual_volatility": factor_result["residual_volatility"],
},
}
6.6 Run the Pipeline
def run_attribution(config: AttributionConfig) -> dict[str, object]:
frames = load_inputs(config)
sector_table, security_table = calculate_brinson(
frames["portfolio_weights"],
frames["benchmark_weights"],
frames["portfolio_returns"],
frames["benchmark_returns"],
frames["sector_map"],
)
factor_result = calculate_factor_attribution(
frames["portfolio_returns"],
frames["factors"],
min_observations=config.min_factor_observations,
)
report = build_report(sector_table, security_table, factor_result)
output_dir = config.data_dir / "attribution_output"
output_dir.mkdir(parents=True, exist_ok=True)
report["sector_attribution"].to_csv(
output_dir / "sector_attribution.csv", index=False
)
report["top_positive_contributors"].to_csv(
output_dir / "top_positive_contributors.csv", index=False
)
report["top_negative_contributors"].to_csv(
output_dir / "top_negative_contributors.csv", index=False
)
return report
if __name__ == "__main__":
config = AttributionConfig(data_dir=Path("data"))
result = run_attribution(config)
print("Sector attribution:")
print(result["sector_attribution"].to_string(index=False))
print("\nFactor attribution:")
for key, value in result["factor_attribution"].items():
print(f"{key}: {value}")
This pipeline should become part of the backtest report rather than a separate analyst notebook. A strategy that is rebalanced, rejected, or deployed differently should retain a reproducible link to its attribution output.
7. Data Acquisition with Resilient Market-Data Calls
The attribution engine above assumes that data preparation has already happened. In a live research environment, the acquisition layer should still handle authentication, timeouts, rate limits, and transient failures.
For historical US-equity OHLCV data, TickDB’s REST API can supply the market-return component. The API key must come from an environment variable rather than source code.
import os
import time
from typing import Any
import requests
API_KEY = os.environ.get("TICKDB_API_KEY")
BASE_URL = "https://api.tickdb.ai/v1"
class TickDBRateLimitError(RuntimeError):
"""Raised when the API rate limit remains active."""
class TickDBClient:
def __init__(
self,
api_key: str | None,
base_url: str = BASE_URL,
timeout: tuple[float, float] = (3.05, 10.0),
max_retries: int = 5,
) -> None:
self.api_key = api_key
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self.max_retries = max_retries
self.session = requests.Session()
def _request(self, method: str, path: str, **kwargs: Any) -> Any:
if not self.api_key:
raise RuntimeError(
"TICKDB_API_KEY is not set. Export the API key before running the client."
)
headers = kwargs.pop("headers", {})
headers["X-API-Key"] = self.api_key
delay = 1.0
for attempt in range(self.max_retries):
try:
response = self.session.request(
method,
f"{self.base_url}{path}",
headers=headers,
timeout=self.timeout,
**kwargs,
)
except requests.Timeout:
if attempt == self.max_retries - 1:
raise
time.sleep(delay)
delay = min(delay * 2, 30.0)
continue
except requests.RequestException:
if attempt == self.max_retries - 1:
raise
time.sleep(delay)
delay = min(delay * 2, 30.0)
continue
try:
payload = response.json()
except ValueError as exc:
if attempt == self.max_retries - 1:
raise RuntimeError("TickDB returned a non-JSON response") from exc
time.sleep(delay)
delay = min(delay * 2, 30.0)
continue
code = payload.get("code", 0) if isinstance(payload, dict) else 0
if response.status_code == 429 or code == 3001:
retry_after = int(response.headers.get("Retry-After", delay))
if attempt == self.max_retries - 1:
raise TickDBRateLimitError(
f"Rate limit remained active after {self.max_retries} attempts"
)
time.sleep(max(retry_after, 0))
delay = min(delay * 2, 30.0)
continue
if code in (1001, 1002):
raise ValueError("Invalid or missing TickDB API key")
if code == 2002:
raise KeyError("Symbol not found; verify it through /v1/symbols/available")
if response.ok and code == 0:
return payload.get("data")
if attempt == self.max_retries - 1:
raise RuntimeError(
f"TickDB request failed: HTTP {response.status_code}, "
f"code={code}, message={payload.get('message', 'unknown error')}"
)
time.sleep(delay)
delay = min(delay * 2, 30.0)
raise RuntimeError("TickDB request exhausted retries")
def get_kline(
self,
symbol: str,
interval: str = "1d",
limit: int = 500,
) -> Any:
return self._request(
"GET",
"/market/kline",
params={"symbol": symbol, "interval": interval, "limit": limit},
)
client = TickDBClient(API_KEY)
# Example:
# history = client.get_kline("AAPL.US", interval="1d", limit=500)
The retry policy uses exponential backoff, but it should not blindly retry permanent errors such as an invalid API key or an unknown symbol. The endpoint must match the use case: use /v1/market/kline for completed historical periods and /v1/market/kline/latest for a current candle.
8. Interpreting the Report Correctly
8.1 Check Reconciliation First
Before interpreting any attribution result, verify that the components add up.
For every period:
[
\text{Portfolio return}
\text{Benchmark return}
\approx
\text{Allocation}
+
\text{Selection}
+
\text{Interaction}
]
A discrepancy usually indicates one of the following:
- return and weight dates are misaligned;
- weights are normalized in one file but not the other;
- transaction costs are included in one return series only;
- the benchmark contains securities absent from the portfolio return file;
- a position was treated as a short position when the engine assumes long-only exposure;
- dividends, corporate actions, or currency conversions were applied inconsistently.
Do not publish an attribution table that fails this reconciliation check.
8.2 Separate Skill from Exposure
The following interpretation is usually more useful than simply labeling performance as “alpha”:
| Observation | Interpretation |
|---|---|
| Positive selection, low factor alpha | Security selection may be useful, but benchmark-relative returns are modest after factor adjustment |
| Positive factor alpha, weak selection | Performance may depend on systematic exposures rather than discretionary selection |
| High allocation contribution, low selection | Sector positioning likely explains most active return |
| Low R² and high residual volatility | Factor models explain little of the behavior; inspect event risk and hidden exposures |
| High market beta | The strategy resembles a leveraged or directional equity portfolio more than a market-neutral strategy |
8.3 Use the Results to Change the Strategy
Attribution is not only a reporting exercise. It can guide research and implementation.
If most active return comes from sector allocation, add sector exposure limits and benchmark-relative position constraints. If factor alpha is consistently positive, decide whether the factor exposure is intentional and economically scalable. If selection is unstable, investigate turnover, liquidity, and transaction costs. If the factor model has low explanatory power, add only defensible factors or treat the strategy as event-driven and control tail risk directly.
The attribution report should therefore feed back into the backtest configuration, not sit in a separate presentation deck.
9. Backtest and Reporting Limitations
An attribution result is only as reliable as its inputs. At minimum, disclose:
| Field | Required disclosure |
|---|---|
| Backtest period | Start and end dates |
| Frequency | Daily, weekly, or monthly |
| Sample size | Number of periods and number of securities |
| Benchmark | Exact benchmark and total-return or price-return definition |
| Costs | Commission, spread, slippage, and market-impact assumptions |
| Position construction | Rebalance schedule, liquidity filters, and leverage rules |
| Factor source | Definition, frequency, and treatment of risk-free rate |
| Attribution method | Brinson variant, interaction treatment, and residual convention |
| Limitations | Lookahead, survivorship, data gaps, and short-sample uncertainty |
For a live-capable strategy, run at least an out-of-sample period and compare the attribution with a rolling-window analysis. A stable strategy should not depend on one sector, one factor, or one extraordinary stock.
A suitable limitations statement is:
Backtest limitations: The attribution results are based on historical simulation and do not guarantee future performance. Slippage and market impact are approximated, factor definitions may change, and limited observations can make regression estimates unstable. Extended out-of-sample validation is required before live deployment.
10. Closing and Next Steps
The screen shows 18.4%. The question is whether the portfolio earned it through deliberate security selection, through exposure to sectors and factors, or through both.
A disciplined attribution process preserves that distinction. Brinson analysis explains sector allocation and security selection. Factor regression measures market, size, and value exposure and estimates residual alpha. Reconciliation, stability tests, and cost-aware reporting determine whether the result reflects a repeatable strategy or a temporary portfolio configuration.
Next Steps
If you are an investor looking for deeper market insight, subscribe to the TickDB newsletter for weekly supply-chain and microstructure analysis.
If you want to run this attribution pipeline yourself:
- Sign up at tickdb.ai and request a free API key.
- Set the
TICKDB_API_KEYenvironment variable. - Prepare the holdings, benchmark, sector, and factor CSV files.
- Run the Python pipeline and review the reconciliation checks.
If you need long-horizon historical OHLCV data for multi-cycle strategy research, contact [email protected] for institutional data options.
If you use AI coding assistants, search for and install the tickdb-market-data SKILL in your AI tool’s marketplace.
This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results.