Performance Attribution logo

Performance Attribution

OrganizationPopular
HKUDS
performance-attribution

Performance attribution analysis — Brinson sector/stock-selection attribution, factor alpha/beta decomposition, market-timing evaluation, and benchmark comparison framework.

Overview

PublisherHKUDS
RepositoryVibe-Trading
Skill nameperformance-attribution
Stars
33.6K
Forks
5.5K
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by HKUDS on GitHub. Read the source before you install it.

Installation

Install the Performance Attribution AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/HKUDS/Vibe-Trading.git /tmp/Vibe-Trading
mkdir -p .claude/skills
cp -r /tmp/Vibe-Trading/agent/src/skills/performance-attribution .claude/skills/performance-attribution
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Performance Attribution in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Performance Attribution on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Performance Attribution is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Performance Attribution Analysis

Overview

Decompose portfolio excess returns into explainable sources: sector allocation, stock selection, factor exposure, timing contribution, and more. This helps explain why a strategy made or lost money, rather than only how much it made or lost.

Brinson Attribution Model

Do not retype these formulas into throwaway Python. They are implemented and tested in src/quantlib/attribution.py; import them.

Single-Period Brinson-Fachler Model

Let w_p,i = portfolio weight of sector i
    w_b,i = benchmark weight of sector i
    r_p,i = portfolio return of sector i
    r_b,i = benchmark return of sector i
    R_b   = total benchmark return

Allocation_i  = (w_p,i - w_b,i) × (r_b,i - R_b)
Selection_i   =  w_b,i          × (r_p,i - r_b,i)
Interaction_i = (w_p,i - w_b,i) × (r_p,i - r_b,i)

Total active return = Σ(Allocation_i) + Σ(Selection_i) + Σ(Interaction_i)

The decomposition itself has no residual term. The three effects sum to R_p - R_b identically, for any sector returns whatsoever, provided the portfolio and benchmark weights carry the same total. brinson_fachler enforces the weight-sum precondition and raises rather than returning a decomposition that does not tie out.

A residual is therefore never a property of the algebra — but it is a real and expected property of a reported attribution, because the inputs are a snapshot. Intra-period trading, cash drag, corporate actions and FX translation all move the actual portfolio return away from the one these weights and sector returns imply. So:

  • residual inside the decomposition, given the inputs → impossible; if you see one, the arithmetic or the weight convention is wrong;
  • residual between the decomposition and the reported fund return → normal; quantify it and attribute it to its source rather than absorbing it silently into selection. This is what the /attrib reconciliation gate asks for.
python
from src.quantlib.attribution import brinson_fachler

result = brinson_fachler(
    portfolio_weights={"Tech": 0.40, "Financials": 0.10, "Energy": 0.30, "Health": 0.20},
    benchmark_weights={"Tech": 0.25, "Financials": 0.30, "Energy": 0.25, "Health": 0.20},
    portfolio_returns={"Tech": 0.12, "Financials": 0.04, "Energy": -0.02, "Health": 0.07},
    benchmark_returns={"Tech": 0.10, "Financials": 0.05, "Energy": -0.01, "Health": 0.06},
)

result.portfolio_return   # 0.0600
result.benchmark_return   # 0.0495
result.active_return      # 0.0105
result.allocation         # 0.0045
result.selection          # 0.0015
result.interaction        # 0.0045
# 0.0045 + 0.0015 + 0.0045 == 0.0105 exactly (residual ~3e-18, machine epsilon)

for effect in result.sectors:
    print(effect.sector, effect.allocation, effect.selection, effect.interaction, effect.total)

A sector return may be omitted only where the matching weight is zero. A benchmark sector you did not own therefore shows zero selection and zero interaction, and the whole effect lands in allocation — you cannot demonstrate stock-picking skill in something you never held.

Example Brinson Attribution

Rendered from the call above, so every figure below is reproducible:

markdown
### Brinson Sector Attribution

| Sector | Portfolio Weight | Benchmark Weight | Portfolio Return | Benchmark Return | Allocation | Selection | Interaction |
|------|---------|---------|---------|---------|---------|---------|---------|
| Tech | 40% | 25% | 12% | 10% | +0.7575% | +0.50% | +0.30% |
| Financials | 10% | 30% | 4% | 5% | -0.0100% | -0.30% | +0.20% |
| Energy | 30% | 25% | -2% | -1% | -0.2975% | -0.25% | -0.05% |
| Health | 20% | 20% | 7% | 6% | +0.0000% | +0.20% | +0.00% |
| **Total** | 100% | 100% | 6.00% | 4.95% | **+0.45%** | **+0.15%** | **+0.45%** |

Active return 1.05% = allocation 0.45% + selection 0.15% + interaction 0.45%. No residual.

Multi-Period Attribution (Linked Brinson)

Single-period effects add, but returns compound, so simply summing each period's effects does not reproduce the compounded active return. Take the four-sector period above and two more like it (the exact three are the _three_periods fixture in tests/quantlib/test_attribution.py, so you can run them): summing the three active returns gives 2.8500%, while the compounded active return is 3.0318% — an 18.2bp error that grows with the horizon and the return level.

Use Carino logarithmic linking, implemented as carino_link. It is residual-free, and its per-period scaling factor depends only on that period's total portfolio and benchmark return — never on the effects being linked — so linking is deterministic and cannot be steered by how sectors were bucketed. (Menchero linking is also residual-free but distributes a correction term derived from the effects themselves; Carino needs less machinery for the same guarantee.)

k   = (ln(1 + R_P) - ln(1 + R_B)) / (R_P - R_B)        # over the whole horizon
k_t = (ln(1 + R_p,t) - ln(1 + R_b,t)) / (R_p,t - R_b,t)  # for period t

linked effect = Σ_t (k_t / k) × effect_{i,t}
python
from src.quantlib.attribution import brinson_fachler, carino_link

periods = [brinson_fachler(**month) for month in monthly_inputs]
linked = carino_link(periods)

linked.active_return   # compounded, not summed
linked.allocation, linked.selection, linked.interaction
linked.scaling_factors  # one k_t / k per period, exposed so a report can be audited

for sector in linked.sectors:
    print(sector.sector, sector.total)
# allocation + selection + interaction == linked.active_return exactly

Arithmetic linking is acceptable only when you explicitly report the residual. Since carino_link costs one function call and leaves none, prefer it.

Factor Attribution

Alpha-Beta Decomposition

R_p = α + β × R_m + ε

α (alpha): excess return, manager skill
β (beta): market exposure, systematic risk
ε (epsilon): residual, idiosyncratic risk

Regression method: OLS regression, with at least 60 data points
Multi-Factor Attribution (Fama-French Extension)
R_p - R_f = α + β_mkt × (R_m - R_f) + β_smb × SMB + β_hml × HML + β_mom × MOM + ε

| Factor | Meaning | China A-share Proxy |
|------|------|--------|
| MKT | Market | CSI 300 return |
| SMB | Small-cap premium | CSI 500 - CSI 300 |
| HML | Value premium | high-PB group - low-PB group |
| MOM | Momentum | top past-12M winners - bottom group |
Factor Exposure Analysis Template
markdown
### Factor Exposure Analysis

| Factor | Beta | t-stat | Significance | Interpretation |
|------|------|---------|--------|------|
| Market (MKT) | 0.85 | 12.3 | *** | Below 1, defensive profile |
| Small-cap (SMB) | 0.25 | 3.2 | ** | Small-cap tilt |
| Value (HML) | -0.15 | -1.8 | * | Growth tilt |
| Momentum (MOM) | 0.30 | 4.1 | *** | Significant momentum exposure |
| **Alpha** | **0.8% / month** | **2.5** | ** | **Significant alpha** |

R² = 0.72 → factors explain 72% of return variation
Alpha = 0.8% / month = 10% / year, significant

Market-Timing Evaluation

Treynor-Mazuy Model

R_p - R_f = α + β × (R_m - R_f) + γ × (R_m - R_f)² + ε

γ > 0 and significant → timing ability exists (adds risk in bull markets, cuts risk in bear markets)
γ ≤ 0 → no timing ability

Henriksson-Merton Model

R_p - R_f = α + β × (R_m - R_f) + γ × max(R_m - R_f, 0) + ε

γ > 0 → portfolio beta is higher in bull markets (successful timing)

Practical Timing Metrics

MetricCalculationMeaning
Bull capture ratioportfolio return in bull markets / benchmark return>100% = outperforming
Bear capture ratioportfolio return in bear markets / benchmark return<100% = better downside defense
Timing hit rateproportion of months where market direction was called correctly>55% = shows skill
Correlation between position changes and marketcorr(position_change, future_return)>0 = timing is correct

Benchmark Comparison Framework

Benchmark Selection

Strategy TypeRecommended BenchmarkChina A-share Code
China A-share large capCSI 300000300.SH
China A-share small capCSI 500 / CSI 1000000905.SH
China A-share broad marketCSI All Share000985.SH
Hong Kong equitiesHang Seng IndexHSI
US equitiesS&P 500SPX
CryptoBTCBTC-USDT
Multi-asset60/40 portfolioself-constructed

Risk-Adjusted Performance Metrics

MetricFormulaExcellentGoodAverage
Sharpe(R_p - R_f) / σ_p>1.51.0-1.50.5-1.0
Sortino(R_p - R_f) / σ_down>2.01.5-2.01.0-1.5
CalmarR_p / MaxDD>1.00.5-1.00.2-0.5
Information Ratio(R_p - R_b) / TE>1.00.5-1.00.2-0.5
Treynor(R_p - R_f) / βused comparatively

Rolling Analysis

Use rolling windows (such as 12 months) to analyze:
- Rolling Sharpe: strategy stability
- Rolling alpha: whether alpha persists
- Rolling beta: whether market exposure is stable
- Rolling information ratio: persistence of benchmark outperformance

Suggested windows: 252 days for daily data, 12-36 months for monthly data

Analysis Framework

Step 1: Aggregate Analysis

1. Cumulative return vs benchmark
2. Excess-return decomposition (annual / monthly)
3. Summary risk metrics (volatility / max drawdown / Sharpe)

Step 2: Attribution Decomposition

1. Brinson attribution (if sector information is available)
2. Factor attribution (alpha / beta / factor exposure)
3. Timing attribution (TM / HM models)

Step 3: Style Analysis

1. Large cap vs small cap exposure
2. Growth vs value exposure
3. Style drift detection (rolling style analysis)

Step 4: Conclusions and Recommendations

1. Main sources of excess return
2. Whether risk exposure is reasonable
3. Suggested improvement directions

Output Format

markdown
## Performance Attribution Report

### Performance Overview
| Metric | Strategy | Benchmark | Excess |
|------|------|------|------|
| Cumulative return | +85.2% | +32.1% | +53.1% |
| Annualized return | 12.5% | 5.8% | +6.7% |
| Annualized volatility | 18.2% | 20.5% | - |
| Sharpe | 0.69 | 0.28 | - |
| Information Ratio | 0.82 | - | - |

### Attribution Breakdown
| Source | Contribution (annualized) | Share |
|------|-----------|------|
| Sector allocation | +2.1% | 31% |
| Stock selection | +3.8% | 57% |
| Timing | +0.8% | 12% |

### Factor Exposure
[factor exposure table]

### Conclusion
Excess return mainly comes from stock selection (57% contribution), followed by sector allocation.
Alpha is significant (`t=2.5`), indicating real stock-picking ability.
Watch the risk of excessive small-cap exposure (`SMB beta=0.25`).

Notes

  1. Attribution ≠ prediction: attribution explains the past; it does not guarantee persistence in the future
  2. Benchmark selection affects attribution: switch the benchmark and alpha may disappear, so benchmark choice must be appropriate
  3. Data frequency: daily attribution is noisy, monthly attribution is more stable but has fewer samples; recommended workflow is daily computation with monthly reporting
  4. Survivorship bias: delisted stocks may be excluded in backtests, creating false alpha
  5. Multiple-testing problem: if you test 100 strategies, about 5 may appear significant by chance (p=0.05); use multiple-comparison correction
  6. Factor data requirement: factor attribution requires factor return data, which can be obtained from tushare or self-constructed
  7. Attribution in backtest reports: metrics.csv already provides basic metrics after a backtest; this skill adds deeper attribution analysis
  8. Brinson is implemented, not improvised: src/quantlib/attribution.py holds the tested single-period and Carino-linked decomposition. Import it. Hand-written attribution code that reports a single-period residual is a bug in that code, not a property of the model

Frequently asked questions

What does the Performance Attribution AI skill do?

Performance attribution analysis — Brinson sector/stock-selection attribution, factor alpha/beta decomposition, market-timing evaluation, and benchmark comparison framework.

Why use Performance Attribution on TypingMind?

Because you install it once and use it with any model. Performance Attribution is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Performance Attribution in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/HKUDS/Vibe-Trading/tree/main/agent/src/skills/performance-attribution. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Performance Attribution?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Performance Attribution?

As many as you like. As long as a model supports skills, you can use Performance Attribution with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Performance Attribution AI skill free?

Yes. It is published on GitHub by HKUDS under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇