Agent skill

Asset Allocation and Optimizers

by HKUDS in HKUDS/Vibe-Trading

Explains portfolio theory and the built-in optimizers: mean-variance (MPT), Black-Litterman, risk budgeting and all-weather allocation, plus rebalancing rules and config output.

MITAuto-check passedBusiness, Finance & HR

Install Asset Allocation and Optimizers

skills CLI
$ npx skills add HKUDS/Vibe-Trading --skill asset-allocation -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install HKUDS/Vibe-Trading asset-allocation --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/HKUDS/Vibe-Trading.git skills-src && mkdir -p .claude/skills && cp -r skills-src/agent/src/skills/asset-allocation .claude/skills/asset-allocation && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
asset-allocation
GitHub stars
35k
Token cost
~2.9k tokens
SKILL.md length
902 words
Files
1
Skills in repo
89
Repo updated
First seen
Licence
MIT

At a glance

Explains portfolio theory and the built-in optimizers: mean-variance (MPT), Black-Litterman, risk budgeting and all-weather allocation, plus rebalancing rules and config output.

  • Works in 9 steps: Modern Portfolio Theory (MPT, Markowitz) → Black-Litterman Model → Risk Budgeting → …
  • Choosing between mean-variance, Black-Litterman and risk budgeting for a portfolio
  • SKILL.md covers Overview, Asset Allocation Theory, Guide to the 5 Optimizers and Rebalancing Strategy, plus 2 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

This skill walks through four allocation frameworks and how to use the optimizers that implement them, with the result written straight into config.json. For modern portfolio theory it states the minimum-variance problem, lists pros and cons and advises against raw use in favor of bounds, sector limits or a regularized version.

Black-Litterman is presented as a start from market equilibrium returns plus view matrices, with examples of absolute and relative views and guidance for the tau and omega parameters. Risk budgeting allocates by risk contribution, with equal-risk, equity-tilted and dynamic variants, and the all-weather approach spreads risk across economic environments. Rebalancing rules are covered as well.

When your agent uses it

  • Choosing between mean-variance, Black-Litterman and risk budgeting for a portfolio
  • Turning investor views into Black-Litterman inputs
  • Setting up an equal risk contribution portfolio
  • Deciding on rebalancing rules for a multi-asset allocation

Example prompts

  • “Build an equal risk contribution allocation across stocks, bonds and commodities and write it to config.json.”
  • “Express the view that China A-shares will outperform US equities by 5% as Black-Litterman inputs.”
  • “Why shouldn't I use raw mean-variance optimization, and which constraints should I add?”
  • “Set rebalancing rules for an all-weather portfolio.”

Requirements

  • The optimizers built into the Vibe-Trading project

Workflow steps

9 steps, taken from the step headings in SKILL.md.

  1. Modern Portfolio Theory (MPT, Markowitz)
  2. Black-Litterman Model
  3. Risk Budgeting
  4. All-Weather Strategy
  5. equal_volatility
  6. risk_parity
  7. mean_variance
  8. max_diversification
  9. turnover_aware

What it can do on your machine

Read from SKILL.md and the folder at commit 14cabaf. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are json, python and markdown).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Asset Allocation and Optimizers loads about 2.9k tokens when it runs. Until then it costs about 46 tokens; SKILL.md has 902 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~46
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from HKUDS/Vibe-Trading at commit 14cabaf, republished under its MIT licence (© HKUDS). 902 words, ~2,926 tokens.

Download SKILL.mdSave it as .claude/skills/asset-allocation/SKILL.md (or your agent's skills folder).
name
asset-allocation
description
Asset allocation theory and optimizer usage — MPT / Black-Litterman / risk budgeting / all-weather strategy, including guides for 5 optimizers and rebalancing rules.
category
asset-class

Asset Allocation and Portfolio Optimization

Overview

From asset allocation theory to practical implementation, this skill covers classical frameworks (MPT, BL, risk budgeting, all-weather) and the usage of the four optimizers built into this system. The output can be written directly into config.json.

Asset Allocation Theory

1. Modern Portfolio Theory (MPT, Markowitz)

Core idea: maximize expected return for a given level of risk (the efficient frontier).

Optimization problem:
min  w'Σw              (portfolio variance)
s.t. w'μ = target_return
     Σw = 1
     w ≥ 0              (no shorting)
AdvantagesDisadvantages
Mathematically rigorousExtremely sensitive to inputs (garbage in, garbage out)
Efficient frontier is visualizableConcentrated-allocation problem (often produces extreme weights)
Foundational frameworkAssumes normality and ignores fat tails

Practical advice: do not use raw MPT directly. Add constraints (upper/lower bounds, sector limits) or use a regularized version.

2. Black-Litterman Model

Core idea: start from market equilibrium and incorporate investor views.

Steps:
1. Reverse-imply market equilibrium returns: π = δΣw_mkt
2. Build the view matrices: P (selection matrix), Q (view returns), Ω (view uncertainty)
3. Blend the posterior: μ_BL = [(τΣ)^-1 + P'Ω^-1 P]^-1 [(τΣ)^-1 π + P'Ω^-1 Q]
4. Run Markowitz optimization using posterior μ_BL

Example views:

  • Absolute view: "China A-shares will return 10% over the next year" → P=[1,0,0], Q=[0.10]
  • Relative view: "China A-shares will outperform US equities by 5%" → P=[1,-1,0], Q=[0.05]

Parameter guidance:

  • τ (uncertainty scaling): 0.025-0.05
  • Ω: set according to view confidence, where higher confidence = smaller variance
3. Risk Budgeting

Core idea: allocate by risk contribution rather than by capital share.

Risk contribution: RC_i = w_i × (Σw)_i / σ_p
Target: RC_i / σ_p = budget_i  (for all i)
StrategyRisk BudgetBest Use Case
Equal risk contributionEach asset 1/NWhen you do not know which asset is best
Equity-tilted risk budgetStocks 60%, bonds 30%, commodities 10%When you want equities to contribute more risk
Dynamic risk budgetAdjust dynamically by signal strengthWhen you have market-timing ability
4. All-Weather Strategy

Bridgewater framework: allocate risk equally across economic environments.

Economic environment   Asset allocation
─────────              ─────────
Growth rising          Equities + commodities + corporate bonds
Growth falling         Government bonds + inflation-protected bonds
Inflation rising       Commodities + inflation-protected bonds + EM debt
Inflation falling      Equities + government bonds

Simplified allocation example for China-focused portfolios:
- 30% CSI 300 / CSI 500
- 40% government bonds / credit bonds
- 15% gold
- 15% commodities / REITs

Guide to the 5 Optimizers

Overview of the Built-In Optimizers

Configure them in config.json through optimizer and optimizer_params:

optimizerDisplay NameCore IdeaBest Use Case
equal_volatilityEqual VolatilityAllocate weights by inverse volatilitySimple and effective baseline
risk_parityRisk ParityEqualize risk contribution while accounting for correlationLong-term robust allocation
mean_varianceMean-VarianceMaximize Sharpe ratio or minimize varianceWhen return forecasts are available
max_diversificationMaximum DiversificationMaximize the diversification ratioWhen pursuing a low-correlation portfolio
turnover_awareTurnover-AwareMean-variance utility with an L1 penalty on weight changes vs the previous rebalanceWhen trading costs matter; tune turnover_penalty to your data frequency
1. equal_volatility
json
{
  "optimizer": "equal_volatility",
  "optimizer_params": {
    "lookback": 60
  }
}

Principle: w_i = (1/σ_i) / Σ(1/σ_j)

ParameterDefaultDescription
lookback60Volatility calculation window (trading days)

Advantages: simple and fast, no return forecast required, no correlation matrix required.
Disadvantages: ignores cross-asset correlation.

2. risk_parity
json
{
  "optimizer": "risk_parity",
  "optimizer_params": {
    "lookback": 60
  }
}

Principle: solve for weights such that each asset contributes the same amount of risk.

ParameterDefaultDescription
lookback60Covariance-matrix estimation window

Advantages: accounts for correlation, spreads risk more evenly, and is robust over long horizons.
Disadvantages: requires iterative solving and is sensitive to covariance estimates.

3. mean_variance
json
{
  "optimizer": "mean_variance",
  "optimizer_params": {
    "lookback": 60,
    "risk_free": 0.0
  }
}

Principle: Markowitz optimization that maximizes the Sharpe ratio.

ParameterDefaultDescription
lookback60Window for estimating means and covariances
risk_free0.0Risk-free rate (annualized)

Advantages: theoretically optimal (if inputs are accurate).
Disadvantages: extremely sensitive to inputs, prone to extreme weights, and often performs poorly out of sample.
Recommendation: do not make lookback too short (<30 easily overfits), and add upper/lower weight constraints.

4. max_diversification
json
{
  "optimizer": "max_diversification",
  "optimizer_params": {
    "lookback": 60
  }
}

Principle: maximize DR = (w'σ) / σ_p (the diversification ratio).

ParameterDefaultDescription
lookback60Calculation window

Advantages: does not require return forecasts and seeks true diversification.
Disadvantages: effectiveness is limited in highly correlated environments.

Show full SKILL.md (375 more words)Show less
5. turnover_aware
json
{
  "optimizer": "turnover_aware",
  "optimizer_params": {
    "lookback": 60,
    "risk_aversion": 1.0,
    "turnover_penalty": 0.5
  }
}

Principle: minimize -w'μ + λ·w'Σw + γ·||w - w_prev||₁ subject to long-only, fully-invested weights — mean-variance utility with an L1 penalty on weight changes versus the previous rebalance, so the optimizer only trades when the expected improvement outweighs the (implicit) cost.

ParameterDefaultDescription
lookback60Calculation window
risk_aversion1.0Weight on the variance term (λ)
turnover_penalty0.0Weight on the L1 turnover term (γ); 0 reduces to the mean-variance baseline

Advantages: dampens rebalancing churn, which usually dominates realized costs; the first rebalance is unpenalized so the cold start is undistorted.
Disadvantages: turnover_penalty is scale-sensitive to the return frequency of the input window — for daily returns even γ ≈ 0.5 strongly prefers holding still, so tune it per data frequency.

Optimizer Selection Decision Tree
Do you have return forecasts?
├── Yes → Do trading costs / churn matter?
│   ├── Yes → turnover_aware (tune turnover_penalty to data frequency)
│   └── No → mean_variance (remember to add constraints)
└── No → Do you need to account for correlation?
    ├── Yes → risk_parity (recommended default)
    └── No → Are volatility differences across assets large?
        ├── Yes → equal_volatility
        └── No → max_diversification

Rebalancing Strategy

Three Rebalancing Triggers
MethodTrigger ConditionAdvantagesDisadvantages
Periodic rebalancingFixed monthly / quarterly dateSimple, predictable trading costMay miss or delay adjustments
Threshold triggerDeviation from target weight > X%Trades only when neededFrequent trading in high-volatility markets
Volatility triggerVIX / volatility breaks a thresholdAdapts to market regimeParameter selection is difficult
Suggested Rebalancing Frequency
Asset ClassSuggested FrequencyThreshold
Equity portfolioMonthly±5%
Stock-bond mixQuarterly±10%
Global macroQuarterly / semiannual±10%
CryptocurrencyWeekly / biweekly±15% (high volatility)
Rebalancing in Backtests

Implement rebalancing logic in signal_engine.py:

python
# Periodic rebalancing example (every 20 trading days)
if bar_count % rebalance_freq == 0:
    # Recompute weights
    new_weights = calculate_target_weights(data_map)
    for code, weight in new_weights.items():
        signals[code].iloc[i] = weight

Cross-Asset Correlation Analysis

Typical Correlation Matrix (China-Focused Portfolio Example)
CSI 300CSI 500Government BondsGoldBTC
CSI 3001.000.85-0.150.050.10
CSI 5000.851.00-0.100.030.12
Government Bonds-0.15-0.101.000.20-0.05
Gold0.050.030.201.000.15
BTC0.100.12-0.050.151.00

Key patterns:

  • Negative stock-bond correlation is the foundation of allocation (but it does not always hold; in 2022 both stocks and bonds sold off)
  • Gold has low correlation with equities and serves as a hedge
  • BTC's correlation with traditional assets is unstable and tends to become positive in crises
  • Large-cap versus small-cap China A-shares have high correlation (0.85), so diversification benefits are limited

Output Format

markdown
## Asset Allocation Recommendation

### Allocation Plan
| Asset | Weight | Risk Contribution | Expected Return (Annualized) |
|------|------|---------|--------------|
| CSI 300 | 30% | 45% | 8% |
| Government Bond ETF | 40% | 15% | 3% |
| Gold | 15% | 20% | 5% |
| BTC | 15% | 20% | 15% |

### Optimizer Configuration
```json
{
  "optimizer": "risk_parity",
  "optimizer_params": {"lookback": 60}
}
Expected Risk / Return
MetricValue
Expected annualized return7.2%
Expected annualized volatility8.5%
Expected Sharpe0.85
Expected maximum drawdown-12%
Rebalancing Rules
  • Frequency: quarterly (first trading day of March / June / September / December)
  • Threshold: trigger when any asset deviates from target by ±10%
  • Cost: estimated annual trading cost 0.15%

## Notes

1. **The optimizer needs enough instruments**: at least 3 instruments are needed for meaningful optimization; with 2 instruments, `equal_volatility` is usually enough
2. **`lookback` window**: too short (`<20`) is noisy, too long (`>120`) reacts slowly, and 60 is a reasonable default
3. **`mean_variance` trap**: it is the easiest to overfit, and out-of-sample Sharpe is often cut by half or more
4. **Rebalancing cost**: frequent rebalancing eats into returns; for China A-share portfolios, stamp duty of 0.05% plus commissions is material
5. **Cross-market allocation**: use `"source": "auto"` in `config.json`, and let `codes` mix instruments from different markets
6. **Leverage constraint**: the sum of weights must be ≤ 1.0, and leverage is not allowed unless explicitly specified
7. **Survivorship bias**: historical correlations may be distorted by delistings and new listings

© HKUDS, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in agent/src/skills/asset-allocation of HKUDS/Vibe-Trading.

Open the folder on GitHubat commit 14cabaf

Compare with similar skills

Asset Allocation and Optimizers next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Asset Allocation and Optimizers compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Asset Allocation and Optimizers this skillHKUDS/Vibe-Trading35k—~2.9kAutomated safety check: PassMIT
Stock Deep Analysis Workflowwbh604/UZI-Skill7.1k—~9.1kAutomated safety check: NotesMIT
Three-Statement Model Builderginlix-ai/LangAlpha1.8k—~5.4kAutomated safety check: PassApache-2.0
Money Financeiamzifei/show-me-the-money1k—~2.2kAutomated safety check: PassCustom licence
Financial Model Checkerginlix-ai/LangAlpha1.8k—~4.2kAutomated safety check: PassApache-2.0
DCF Model Builderginlix-ai/LangAlpha1.8k—~7.7kAutomated safety check: PassApache-2.0

Similar skills

  • Runs a staged deep analysis of a single stock on China A-share, Hong Kong and US markets, ending in an HTML report with valuation models and investor-panel scores.

    7.1k GitHub stars~9.1k tokensUpdated 1 mo ago
    Business, Finance & HRAuto-check: notes
  • Builds or repairs an integrated income statement, balance sheet and cash flow model in Excel with live formulas, supporting schedules, scenarios and a Checks sheet.

    1.8k GitHub stars~5.4k tokensUpdated today
    Business, Finance & HRAuto-check passed
  • Money Finance

    iamzifei/show-me-the-money

    Financial tracking, revenue analytics, expense management, and pricing optimization.

    1k GitHub stars~2.2k tokensUpdated 1 mo ago
    Business, Finance & HRAuto-check passed
  • Financial Model Checker

    ginlix-ai/LangAlpha

    Audits an existing Excel financial model without editing it, checking structure, formulas, integrity identities and source tie-out, and ends in a prioritized issue log.

    1.8k GitHub stars~4.2k tokensUpdated today
    Business, Finance & HRAuto-check passed
  • DCF Model Builder

    ginlix-ai/LangAlpha

    Builds a live Excel DCF valuation workbook with free cash flow projections, WACC, terminal value, three scenarios, sensitivity grids and a reverse DCF.

    1.8k GitHub stars~7.7k tokensUpdated today
    Business, Finance & HRAuto-check passed
  • Financial statements, business segments, dividends, valuation multiples (PE/PB/PS), industry comparison, operating data, corporate actions, company and executive profiles, cross-stock comparison…

    269 GitHub starsUsed in 1 repo~1.8k tokens
    Business, Finance & HRAuto-check passed

More from HKUDS/Vibe-Trading

All 89 skills in this repo
  • Eastmoney Market Data

    HKUDS/Vibe-Trading

    Index of Eastmoney's free, no-token market data interfaces for China A-shares and Hong Kong stocks: fund flows, dragon-tiger lists, margin trading, reports and news.

    35k GitHub stars~1k tokensUpdated today
    Auto-check passed
  • OKX Market Data

    HKUDS/Vibe-Trading

    Retrieves public OKX cryptocurrency market data such as spot prices, candlesticks, funding rates and open interest through the OKX V5 REST API, with no authentication.

    35k GitHub stars~1.3k tokensUpdated today
    Auto-check passed
  • SEC EDGAR Filings Fetcher

    HKUDS/Vibe-Trading

    Fetches U.S. SEC EDGAR data: resolves tickers to CIK numbers, lists recent 10-K, 10-Q and 8-K filings with document URLs, and pulls XBRL financial series.

    35k GitHub stars~1.4k tokensUpdated today
    Auto-check passed
  • A-Share ST Risk Screener

    HKUDS/Vibe-Trading

    Predicts whether a mainland China A-share company risks an ST or *ST warning after its next annual report, using financial thresholds and Sina penalty records.

    35k GitHub stars~4.9k tokensUpdated today
    Auto-check passed
  • Breaks a structural trend such as AI infrastructure into its physical supply chain and ranks lesser-known listed companies sitting on each bottleneck.

    35k GitHub stars~2.7k tokensUpdated today
    Auto-check passed
  • Plans and drafts an eight-part, roughly 120k-word investigative series on one company, built around a strict fact-check pass rather than fast drafting.

    35k GitHub stars~2.4k tokensUpdated today
    Auto-check passed

Questions about Asset Allocation and Optimizers

What does Asset Allocation and Optimizers do?

Explains portfolio theory and the built-in optimizers: mean-variance (MPT), Black-Litterman, risk budgeting and all-weather allocation, plus rebalancing rules and config output. json. For modern portfolio theory it states the minimum-variance problem, lists pros and cons and advises against raw use in favor of bounds, sector limits or a regularized version.

When should I use Asset Allocation and Optimizers?

Asset Allocation and Optimizers fits situations like: choosing between mean-variance, Black-Litterman and risk budgeting for a portfolio; turning investor views into Black-Litterman inputs; setting up an equal risk contribution portfolio; deciding on rebalancing rules for a multi-asset allocation.

How do I install Asset Allocation and Optimizers in Claude Code?

Run `npx skills add HKUDS/Vibe-Trading --skill asset-allocation -a claude-code`. Or copy the skill folder (agent/src/skills/asset-allocation in HKUDS/Vibe-Trading) into .claude/skills/asset-allocation in your project. Claude Code loads it when a task matches its description.

How do I install Asset Allocation and Optimizers in Codex?

Run `npx skills add HKUDS/Vibe-Trading --skill asset-allocation -a codex`. Or copy the skill folder (agent/src/skills/asset-allocation in HKUDS/Vibe-Trading) into .agents/skills/asset-allocation in your project. Codex loads it when a task matches its description.

Can I use Asset Allocation and Optimizers in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add HKUDS/Vibe-Trading --skill asset-allocation -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/asset-allocation, .gemini/skills/asset-allocation, .github/skills/asset-allocation and .opencode/skills/asset-allocation in your project.

What does Asset Allocation and Optimizers need to run?

SKILL.md names no scripts, command-line tools or credentials: Asset Allocation and Optimizers is instructions for the agent only. Our summary lists: The optimizers built into the Vibe-Trading project.

Does Asset Allocation and Optimizers access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Asset Allocation and Optimizers safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Asset Allocation and Optimizers use?

Asset Allocation and Optimizers is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Asset Allocation and Optimizers use?

About 2.9k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Asset Allocation and Optimizers?

Skills that share tags, products or a category with Asset Allocation and Optimizers: Stock Deep Analysis Workflow (wbh604/UZI-Skill, 7.1k stars), Three-Statement Model Builder (ginlix-ai/LangAlpha, 1.8k stars), Money Finance (iamzifei/show-me-the-money, 1k stars) and Financial Model Checker (ginlix-ai/LangAlpha, 1.8k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Asset Allocation and Optimizers?

HKUDS (a GitHub organization) maintains it in HKUDS/Vibe-Trading, which has 34,949 GitHub stars. The repository holds 89 skills in this directory. The repository was last updated on October 8, 2026.

Source: HKUDS/Vibe-Trading on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.