Agent skill

Portfolio Optimization Guide

by wentorai in wentorai/research-plugins

Portfolio theory, optimization algorithms, and asset allocation methods

MITAuto-check passedBusiness, Finance & HR

Install Portfolio Optimization Guide

skills CLI
$ npx skills add wentorai/research-plugins --skill portfolio-optimization-guide -a claude-code

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

GitHub CLI
$ gh skill install wentorai/research-plugins portfolio-optimization-guide --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/wentorai/research-plugins.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/domains/finance/portfolio-optimization-guide .claude/skills/portfolio-optimization-guide && 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
portfolio-optimization-guide
GitHub stars
298
Used in
1 other repo
Token cost
~2.5k tokens
SKILL.md length
169 words
Files
1
Skills in repo
405
Repo updated
First seen
Licence
MIT

At a glance

Portfolio theory, optimization algorithms, and asset allocation methods

  • Tasks that involve Trading and backtesting
  • SKILL.md covers Mean-Variance Optimization, Black-Litterman Model, Risk Parity and Factor-Based Portfolio…, plus 3 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Portfolio Optimization Guide is an agent skill from wentorai/research-plugins. Portfolio theory, optimization algorithms, and asset allocation methods

Its SKILL.md is about 2.5k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Business, Finance & HR, covering Trading and backtesting. The repository describes itself as: 350+ academic research skills, MCP configs, and plugins for Research-Claw and AI agents. The licence is MIT.

When your agent uses it

  • Tasks that involve Trading and backtesting

Example prompts

  • “/portfolio-optimization-guide”

Requirements

  • Python 3

What it can do on your machine

Read from SKILL.md and the folder at commit bf44b3c. 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 python).

    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

Portfolio Optimization Guide loads about 2.5k tokens when it runs. Until then it costs about 25 tokens; SKILL.md has 169 words of instructions outside code blocks.

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

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 wentorai/research-plugins at commit bf44b3c, republished under its MIT licence (© wentorai). 169 words, ~2,475 tokens.

Download SKILL.mdSave it as .claude/skills/portfolio-optimization-guide/SKILL.md (or your agent's skills folder).
name
portfolio-optimization-guide
description
Portfolio theory, optimization algorithms, and asset allocation methods

Portfolio Optimization Guide

A skill for implementing and researching portfolio optimization methods, from classical mean-variance optimization to modern robust and factor-based approaches. Covers Markowitz theory, Black-Litterman, risk parity, and machine learning-enhanced portfolio construction.

Mean-Variance Optimization

Classical Markowitz Portfolio
python
import numpy as np
from scipy.optimize import minimize

def mean_variance_optimize(expected_returns: np.ndarray,
                             cov_matrix: np.ndarray,
                             target_return: float = None,
                             risk_free_rate: float = 0.02) -> dict:
    """
    Markowitz mean-variance optimization.
    expected_returns: array of expected returns for each asset
    cov_matrix: covariance matrix of asset returns
    target_return: target portfolio return (None for max Sharpe)
    """
    n_assets = len(expected_returns)

    def portfolio_volatility(weights):
        return np.sqrt(weights @ cov_matrix @ weights)

    def neg_sharpe(weights):
        ret = weights @ expected_returns
        vol = portfolio_volatility(weights)
        return -(ret - risk_free_rate) / vol

    # Constraints
    constraints = [
        {"type": "eq", "fun": lambda w: np.sum(w) - 1},  # weights sum to 1
    ]
    if target_return is not None:
        constraints.append(
            {"type": "eq", "fun": lambda w: w @ expected_returns - target_return}
        )

    # Bounds: no short selling (0 to 1 per asset)
    bounds = [(0, 1) for _ in range(n_assets)]

    # Initial guess: equal weight
    w0 = np.ones(n_assets) / n_assets

    if target_return is not None:
        # Minimize volatility for given return
        result = minimize(portfolio_volatility, w0,
                         bounds=bounds, constraints=constraints)
    else:
        # Maximize Sharpe ratio
        result = minimize(neg_sharpe, w0,
                         bounds=bounds, constraints=constraints)

    weights = result.x
    ret = weights @ expected_returns
    vol = portfolio_volatility(weights)

    return {
        "weights": {f"asset_{i}": round(w, 4) for i, w in enumerate(weights)},
        "expected_return": round(ret, 4),
        "volatility": round(vol, 4),
        "sharpe_ratio": round((ret - risk_free_rate) / vol, 4),
    }
Efficient Frontier
python
def compute_efficient_frontier(expected_returns: np.ndarray,
                                 cov_matrix: np.ndarray,
                                 n_points: int = 50) -> list[dict]:
    """
    Compute the efficient frontier by solving for minimum variance
    portfolios at each target return level.
    """
    min_ret = expected_returns.min() * 0.8
    max_ret = expected_returns.max() * 1.1
    target_returns = np.linspace(min_ret, max_ret, n_points)

    frontier = []
    for target in target_returns:
        try:
            result = mean_variance_optimize(
                expected_returns, cov_matrix, target_return=target
            )
            frontier.append({
                "return": result["expected_return"],
                "volatility": result["volatility"],
                "sharpe": result["sharpe_ratio"],
            })
        except Exception:
            continue

    return frontier

Black-Litterman Model

Incorporating Investor Views
python
def black_litterman(market_cap_weights: np.ndarray,
                      cov_matrix: np.ndarray,
                      P: np.ndarray,
                      Q: np.ndarray,
                      omega: np.ndarray = None,
                      risk_aversion: float = 2.5,
                      tau: float = 0.05) -> dict:
    """
    Black-Litterman model for combining market equilibrium with
    investor views.
    market_cap_weights: market-cap weighted portfolio
    cov_matrix: covariance matrix
    P: pick matrix (k views x n assets), identifies assets in each view
    Q: view returns (k x 1), expected returns for each view
    omega: view uncertainty (k x k), diagonal matrix
    """
    # Step 1: Implied equilibrium returns (reverse optimization)
    pi = risk_aversion * cov_matrix @ market_cap_weights

    # Step 2: View uncertainty (if not provided, use He-Litterman)
    if omega is None:
        omega = np.diag(np.diag(tau * P @ cov_matrix @ P.T))

    # Step 3: Posterior expected returns
    tau_sigma = tau * cov_matrix
    inv_tau_sigma = np.linalg.inv(tau_sigma)
    inv_omega = np.linalg.inv(omega)

    posterior_precision = inv_tau_sigma + P.T @ inv_omega @ P
    posterior_cov = np.linalg.inv(posterior_precision)
    posterior_mean = posterior_cov @ (inv_tau_sigma @ pi + P.T @ inv_omega @ Q)

    return {
        "equilibrium_returns": pi.round(4).tolist(),
        "posterior_returns": posterior_mean.round(4).tolist(),
        "posterior_covariance": posterior_cov.round(6).tolist(),
    }

Risk Parity

Equal Risk Contribution Portfolio
python
def risk_parity(cov_matrix: np.ndarray, budget: np.ndarray = None) -> dict:
    """
    Risk parity: each asset contributes equally to total portfolio risk.
    budget: risk budget (default: equal, 1/n each)
    """
    n = cov_matrix.shape[0]
    if budget is None:
        budget = np.ones(n) / n

    def objective(weights):
        portfolio_vol = np.sqrt(weights @ cov_matrix @ weights)
        marginal_risk = cov_matrix @ weights
        risk_contribution = weights * marginal_risk / portfolio_vol
        target_risk = budget * portfolio_vol
        return np.sum((risk_contribution - target_risk) ** 2)

    constraints = [{"type": "eq", "fun": lambda w: np.sum(w) - 1}]
    bounds = [(0.01, 1) for _ in range(n)]
    w0 = np.ones(n) / n

    result = minimize(objective, w0, bounds=bounds, constraints=constraints)
    weights = result.x

    # Verify risk contributions
    portfolio_vol = np.sqrt(weights @ cov_matrix @ weights)
    marginal_risk = cov_matrix @ weights
    risk_contrib = weights * marginal_risk / portfolio_vol
    risk_pct = risk_contrib / risk_contrib.sum()

    return {
        "weights": weights.round(4).tolist(),
        "portfolio_volatility": round(portfolio_vol, 4),
        "risk_contributions": risk_pct.round(4).tolist(),
        "max_risk_deviation": round(np.max(np.abs(risk_pct - budget)), 4),
    }

Factor-Based Portfolio Construction

Fama-French Factor Exposures
python
import statsmodels.api as sm

def estimate_factor_exposures(asset_returns: pd.DataFrame,
                                factor_returns: pd.DataFrame) -> pd.DataFrame:
    """
    Estimate asset exposures to Fama-French factors using regression.
    factor_returns columns: Mkt-RF, SMB, HML, RMW, CMA (5-factor model)
    """
    results = []
    for asset in asset_returns.columns:
        y = asset_returns[asset] - factor_returns.get("RF", 0)
        X = sm.add_constant(factor_returns[["Mkt-RF", "SMB", "HML", "RMW", "CMA"]])
        model = sm.OLS(y, X).fit()

        results.append({
            "asset": asset,
            "alpha": round(model.params["const"], 6),
            "beta_market": round(model.params["Mkt-RF"], 4),
            "beta_size": round(model.params["SMB"], 4),
            "beta_value": round(model.params["HML"], 4),
            "beta_profit": round(model.params["RMW"], 4),
            "beta_invest": round(model.params["CMA"], 4),
            "r_squared": round(model.rsquared, 4),
        })

    return pd.DataFrame(results)

Rebalancing and Transaction Costs

Optimal Rebalancing with Costs
python
def rebalance_with_costs(current_weights: np.ndarray,
                          target_weights: np.ndarray,
                          portfolio_value: float,
                          cost_per_trade: float = 0.001,
                          threshold: float = 0.02) -> dict:
    """
    Determine rebalancing trades considering transaction costs.
    threshold: minimum deviation to trigger rebalancing (2% default)
    cost_per_trade: proportional transaction cost (10 bps)
    """
    deviations = np.abs(current_weights - target_weights)
    needs_rebalance = np.any(deviations > threshold)

    if not needs_rebalance:
        return {"action": "hold", "reason": "within threshold"}

    trades = target_weights - current_weights
    trade_value = np.abs(trades) * portfolio_value
    total_cost = trade_value.sum() * cost_per_trade

    return {
        "action": "rebalance",
        "trades": trades.round(4).tolist(),
        "turnover": np.abs(trades).sum() / 2,
        "transaction_cost": round(total_cost, 2),
        "cost_as_pct": round(total_cost / portfolio_value * 100, 4),
    }

Key Academic References

  • Markowitz, H. (1952). Portfolio Selection. Journal of Finance.
  • Black, F. and Litterman, R. (1992). Global Portfolio Optimization. Financial Analysts Journal.
  • Maillard, S., Roncalli, T., and Teiletche, J. (2010). The Properties of Equally Weighted Risk Contribution Portfolios. Journal of Portfolio Management.
  • Fama, E. and French, K. (2015). A Five-Factor Asset Pricing Model. Journal of Financial Economics.

Tools and Libraries

  • PyPortfolioOpt: Portfolio optimization in Python (mean-variance, Black-Litterman, HRP)
  • riskfolio-lib: Advanced portfolio optimization with risk measures
  • cvxpy: Convex optimization for custom portfolio problems
  • QuantLib: Fixed income and derivatives analytics
  • Kenneth French Data Library: Factor returns data (free)
  • zipline / backtrader: Backtesting frameworks for strategy evaluation

© wentorai, 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 skills/domains/finance/portfolio-optimization-guide of wentorai/research-plugins.

Open the folder on GitHubat commit bf44b3c

Used in 1 other repository

We found 1 copy of this SKILL.md (exact, near-identical or edited) in other folders, from 1 other GitHub owner. This page covers the copy in wentorai/research-plugins, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Portfolio Optimization Guide 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.

Portfolio Optimization Guide compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Portfolio Optimization Guide this skillwentorai/research-plugins2981 repos~2.5kAutomated safety check: PassMIT
Tushare Datazillionare/zillionare3192 repos~2.3kAutomated safety check: PassNone
Tradingview MCPatilaahmettaner/tradingview-mcp5k—~1.3kAutomated safety check: PassMIT
Digital Oraclekomako-workshop/digital-oracle870—~5.9kAutomated safety check: PassMIT
Fintoolsecond-state/fintool3161 repos~5.9kAutomated safety check: PassNone
Polyclawchainstacklabs/polyclaw3601 repos~2kAutomated safety check: PassApache-2.0

Similar skills

  • Tushare Data

    zillionare/zillionare

    面向中文自然语言的 Tushare 数据研究技能。用于把“看看这只股票最近怎么样”“帮我查财报趋势”“最近哪个板块最强”“北向资金在买什么”“给我导出一份行情数据”这类请求,转成可执行的数据获取、清洗、对比、筛选、导出与简要分析流程。适用于 A 股、指数、ETF/基金、财务、估值、资金流、公告新闻、板块概念与宏观数据等研究场景。

    319 GitHub starsUsed in 2 repos~2.3k tokens
    Business, Finance & HRAuto-check passed
  • Tradingview MCP

    atilaahmettaner/tradingview-mcp

    AI Trading Intelligence — live prices, 30+ technical indicators, backtesting (6 strategies), walk-forward overfitting detection, trade logs, equity curves, licensed news sentiment (Marketaux), and…

    5k GitHub stars~1.3k tokensUpdated yesterday
    Business, Finance & HRAuto-check passed
  • Digital Oracle

    komako-workshop/digital-oracle

    Answer prediction questions using market trading data, not opinions.

    870 GitHub stars~5.9k tokensUpdated 2 mo ago
    Business, Finance & HRAuto-check passed
  • Fintool

    second-state/fintool

    Financial trading CLIs — spot and perp trading on Hyperliquid, Binance, Coinbase, OKX.

    316 GitHub starsUsed in 1 repo~5.9k tokens
    Business, Finance & HRAuto-check passed
  • Polyclaw

    chainstacklabs/polyclaw

    Trade on Polymarket via split + CLOB execution. An agent skill from chainstacklabs/polyclaw.

    360 GitHub starsUsed in 1 repo~2k tokens
    Business, Finance & HRAuto-check passed
  • Markdown

    facioquo/stock-indicators-dotnet

    Format and lint Markdown in this repository against GitHub Flavored Markdown and its markdownlint-cli2 configuration — headers, lists, code fences, callouts (VitePress containers on docs-site pages…

    1.2k GitHub stars~812 tokensUpdated yesterday
    Business, Finance & HRAuto-check passed

More from wentorai/research-plugins

All 405 skills in this repo
  • Abstract Writing Guide

    wentorai/research-plugins

    Craft structured research abstracts that maximize clarity and journal acceptance

    298 GitHub starsUsed in 1 repo~1.7k tokens
    Auto-check passed
  • Academic Citation Manager

    wentorai/research-plugins

    Manage academic citations across BibTeX, APA, MLA, and Chicago formats

    298 GitHub starsUsed in 1 repo~2.7k tokens
    Auto-check passed
  • Academic Paper Summarizer

    wentorai/research-plugins

    Summarize academic papers with structured extraction of key elements

    298 GitHub starsUsed in 1 repo~1.4k tokens
    Auto-check passed
  • Academic Study Methods

    wentorai/research-plugins

    Evidence-based study techniques for academic learning and retention

    298 GitHub starsUsed in 1 repo~1.8k tokens
    Auto-check passed
  • Academic Tone Guide

    wentorai/research-plugins

    Adjust writing tone and register for academic audiences and venues

    298 GitHub starsUsed in 1 repo~1.9k tokens
    Auto-check passed
  • Academic Translation Guide

    wentorai/research-plugins

    Academic translation, post-editing, and Chinglish correction guide

    298 GitHub starsUsed in 1 repo~1.6k tokens
    Auto-check passed

Questions about Portfolio Optimization Guide

What does Portfolio Optimization Guide do?

Portfolio theory, optimization algorithms, and asset allocation methods. Portfolio Optimization Guide is an agent skill from wentorai/research-plugins.

When should I use Portfolio Optimization Guide?

Portfolio Optimization Guide fits situations like: tasks that involve Trading and backtesting.

How do I install Portfolio Optimization Guide in Claude Code?

Run `npx skills add wentorai/research-plugins --skill portfolio-optimization-guide -a claude-code`. Or copy the skill folder (skills/domains/finance/portfolio-optimization-guide in wentorai/research-plugins) into .claude/skills/portfolio-optimization-guide in your project. Claude Code loads it when a task matches its description.

How do I install Portfolio Optimization Guide in Codex?

Run `npx skills add wentorai/research-plugins --skill portfolio-optimization-guide -a codex`. Or copy the skill folder (skills/domains/finance/portfolio-optimization-guide in wentorai/research-plugins) into .agents/skills/portfolio-optimization-guide in your project. Codex loads it when a task matches its description.

Can I use Portfolio Optimization Guide 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 wentorai/research-plugins --skill portfolio-optimization-guide -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/portfolio-optimization-guide, .gemini/skills/portfolio-optimization-guide, .github/skills/portfolio-optimization-guide and .opencode/skills/portfolio-optimization-guide in your project.

What does Portfolio Optimization Guide need to run?

SKILL.md names no scripts, command-line tools or credentials: Portfolio Optimization Guide is instructions for the agent only. Our summary lists: Python 3.

Does Portfolio Optimization Guide 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 Portfolio Optimization Guide 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 Portfolio Optimization Guide use?

Portfolio Optimization Guide 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 Portfolio Optimization Guide use?

About 2.5k tokens (SKILL.md is roughly 9.9k 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 Portfolio Optimization Guide?

Skills that share tags, products or a category with Portfolio Optimization Guide: Tushare Data (zillionare/zillionare, 319 stars), Tradingview MCP (atilaahmettaner/tradingview-mcp, 5k stars), Digital Oracle (komako-workshop/digital-oracle, 870 stars) and Fintool (second-state/fintool, 316 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Portfolio Optimization Guide?

wentorai (a GitHub user) maintains it in wentorai/research-plugins, which has 298 GitHub stars. The repository holds 405 skills in this directory. The repository was last updated on June 19, 2026.

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