Asset Allocation logo

Asset Allocation

OrganizationPopular
HKUDS
asset-allocation

Asset allocation theory and optimizer usage — MPT / Black-Litterman / risk budgeting / all-weather strategy, including guides for 5 optimizers and rebalancing rules.

Overview

PublisherHKUDS
RepositoryVibe-Trading
Skill nameasset-allocation
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 Asset Allocation 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/asset-allocation .claude/skills/asset-allocation
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Asset Allocation 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 Asset Allocation 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 Asset Allocation 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.

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.

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

Frequently asked questions

What does the Asset Allocation AI skill do?

Asset allocation theory and optimizer usage — MPT / Black-Litterman / risk budgeting / all-weather strategy, including guides for 5 optimizers and rebalancing rules.

Why use Asset Allocation on TypingMind?

Because you install it once and use it with any model. Asset Allocation 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 Asset Allocation in TypingMind?

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

Which AI models can use Asset Allocation?

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 Asset Allocation?

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

Is the Asset Allocation 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 👇