Agent skill

Portfolio Analytics

by agiprolabs in agiprolabs/claude-trading-skills

Portfolio-level performance measurement including return metrics, risk metrics, risk-adjusted ratios, rolling analysis, and HTML reports

MITAuto-check passedBusiness, Finance & HR

Install Portfolio Analytics

skills CLI
$ npx skills add agiprolabs/claude-trading-skills --skill portfolio-analytics -a claude-code

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

GitHub CLI
$ gh skill install agiprolabs/claude-trading-skills portfolio-analytics --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/agiprolabs/claude-trading-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/portfolio-analytics .claude/skills/portfolio-analytics && 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-analytics
GitHub stars
410
Token cost
~2.9k tokens
SKILL.md length
259 words
Files
5 (incl. scripts, references)
Skills in repo
68
Repo updated
First seen
Licence
MIT

At a glance

Portfolio-level performance measurement including return metrics, risk metrics, risk-adjusted ratios, rolling analysis, and HTML reports

  • Business, Finance & HR work in your project
  • SKILL.md covers When to Use This Skill, Prerequisites, Input Format and Return Metrics, plus 9 more sections
  • Runs Python scripts from its folder; calls uv

What it does

Portfolio Analytics is an agent skill from agiprolabs/claude-trading-skills. Portfolio-level performance measurement including return metrics, risk metrics, risk-adjusted ratios, rolling analysis, and HTML reports

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. The skill folder holds 6 other files, including scripts and reference files (for example `references/metrics_guide.md`, `references/quantstats_guide.md` and `scripts/analyze_portfolio.py`).

It sits in Business, Finance & HR. The repository describes itself as: 68 trading, DeFi, and quantitative finance Agent Skills. Works with Claude Code, Cursor, Codex, Gemini CLI, and 30+ other tools. The licence is MIT.

When your agent uses it

  • Business, Finance & HR work in your project

Example prompts

  • “/portfolio-analytics”

Requirements

  • Python 3

What it can do on your machine

Read from SKILL.md and the folder at commit 981e1d7. 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

    Ships 2 files in scripts/ (Python), which the agent can run.

    Shell commands in SKILL.md call:

    • uv

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

  • Network

    No URLs in SKILL.md. Its commands use uv, which can reach the network depending on how they are called.

    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 Analytics loads about 2.9k tokens when it runs, and up to ~6.6k if it reads all its reference files. Until then it costs about 39 tokens; SKILL.md has 259 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~39
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~6.6k

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); the scripts in this folder are not scanned.

SKILL.md

The full file from agiprolabs/claude-trading-skills at commit 981e1d7, republished under its MIT licence (© agiprolabs). 259 words, ~2,873 tokens.

Download SKILL.mdSave it as .claude/skills/portfolio-analytics/SKILL.md (or your agent's skills folder). This skill also uses 4 other files; get the full folder from GitHub.
name
portfolio-analytics
description
Portfolio-level performance measurement including return metrics, risk metrics, risk-adjusted ratios, rolling analysis, and HTML reports

Portfolio Analytics

Compute portfolio-level performance metrics from equity curves and trade logs. Covers return metrics, risk metrics, risk-adjusted ratios, drawdown analysis, rolling windows, benchmark comparison, trade-level statistics, and automated HTML report generation via quantstats.

When to Use This Skill

  • After backtesting a strategy (e.g., from vectorbt or strategy-framework)
  • Comparing multiple strategies or parameter sets side-by-side
  • Generating investor-ready performance reports
  • Evaluating live trading performance against benchmarks
  • Assessing risk-adjusted returns for portfolio allocation decisions

Prerequisites

bash
uv pip install pandas numpy quantstats

Input Format

All analytics start from an equity curve — a time-indexed Series of portfolio values:

python
import pandas as pd
import numpy as np

# From a backtest
equity = pd.Series(
    [10000, 10150, 10080, 10320, 10510, 10440, 10680],
    index=pd.date_range("2025-01-01", periods=7, freq="D"),
    name="strategy_equity"
)

# Convert to returns
returns = equity.pct_change().dropna()

Return Metrics

Total Return
python
total_return = (equity.iloc[-1] / equity.iloc[0]) - 1
CAGR (Compound Annual Growth Rate)
python
days = (equity.index[-1] - equity.index[0]).days
cagr = (equity.iloc[-1] / equity.iloc[0]) ** (365.25 / days) - 1
Daily Mean Return
python
daily_mean = returns.mean()
annualized_mean = daily_mean * 252  # trading days
Cumulative Returns
python
cumulative = (1 + returns).cumprod() - 1

Risk Metrics

Annualized Volatility
python
daily_vol = returns.std()
annual_vol = daily_vol * np.sqrt(252)
Value at Risk (VaR)

Historical VaR at a given confidence level:

python
def historical_var(returns: pd.Series, confidence: float = 0.95) -> float:
    """Compute historical VaR.

    Args:
        returns: Daily return series.
        confidence: Confidence level (e.g., 0.95 for 95%).

    Returns:
        VaR as a positive number representing potential loss.
    """
    return -np.percentile(returns, (1 - confidence) * 100)
Conditional VaR (CVaR / Expected Shortfall)
python
def historical_cvar(returns: pd.Series, confidence: float = 0.95) -> float:
    """Mean of returns below the VaR threshold."""
    var = historical_var(returns, confidence)
    return -returns[returns <= -var].mean()
Maximum Drawdown
python
def max_drawdown(equity: pd.Series) -> float:
    """Maximum peak-to-trough decline."""
    peak = equity.cummax()
    drawdown = (equity - peak) / peak
    return drawdown.min()  # negative number

def drawdown_series(equity: pd.Series) -> pd.Series:
    """Full drawdown time series."""
    peak = equity.cummax()
    return (equity - peak) / peak
Time Underwater
python
def time_underwater(equity: pd.Series) -> int:
    """Longest consecutive period below previous peak (in days)."""
    dd = drawdown_series(equity)
    is_underwater = dd < 0
    groups = (~is_underwater).cumsum()
    underwater_periods = is_underwater.groupby(groups).sum()
    return int(underwater_periods.max()) if len(underwater_periods) > 0 else 0

Risk-Adjusted Ratios

Sharpe Ratio
python
def sharpe_ratio(
    returns: pd.Series,
    rf: float = 0.0,
    periods_per_year: int = 252
) -> float:
    """Annualized Sharpe ratio.

    Args:
        returns: Period returns.
        rf: Risk-free rate per period.
        periods_per_year: Annualization factor.

    Returns:
        Annualized Sharpe ratio.
    """
    excess = returns - rf
    if excess.std() == 0:
        return 0.0
    return (excess.mean() / excess.std()) * np.sqrt(periods_per_year)
Sortino Ratio
python
def sortino_ratio(
    returns: pd.Series,
    rf: float = 0.0,
    periods_per_year: int = 252
) -> float:
    """Annualized Sortino ratio (penalizes only downside vol)."""
    excess = returns - rf
    downside = excess[excess < 0]
    if len(downside) == 0 or downside.std() == 0:
        return float("inf") if excess.mean() > 0 else 0.0
    return (excess.mean() / downside.std()) * np.sqrt(periods_per_year)
Calmar Ratio
python
def calmar_ratio(equity: pd.Series, periods_per_year: int = 252) -> float:
    """CAGR divided by max drawdown (absolute value)."""
    returns = equity.pct_change().dropna()
    days = (equity.index[-1] - equity.index[0]).days
    cagr = (equity.iloc[-1] / equity.iloc[0]) ** (365.25 / days) - 1
    mdd = abs(max_drawdown(equity))
    if mdd == 0:
        return float("inf") if cagr > 0 else 0.0
    return cagr / mdd
Omega Ratio
python
def omega_ratio(
    returns: pd.Series,
    threshold: float = 0.0
) -> float:
    """Ratio of probability-weighted gains to losses."""
    excess = returns - threshold
    gains = excess[excess > 0].sum()
    losses = abs(excess[excess <= 0].sum())
    if losses == 0:
        return float("inf") if gains > 0 else 1.0
    return gains / losses
Information Ratio
python
def information_ratio(
    returns: pd.Series,
    benchmark_returns: pd.Series,
    periods_per_year: int = 252
) -> float:
    """Excess return per unit of tracking error."""
    active = returns - benchmark_returns
    if active.std() == 0:
        return 0.0
    return (active.mean() / active.std()) * np.sqrt(periods_per_year)

Rolling Analysis

Rolling Sharpe
python
def rolling_sharpe(
    returns: pd.Series,
    window: int = 63,
    rf: float = 0.0,
    periods_per_year: int = 252
) -> pd.Series:
    """Rolling annualized Sharpe ratio."""
    excess = returns - rf
    roll_mean = excess.rolling(window).mean()
    roll_std = excess.rolling(window).std()
    return (roll_mean / roll_std) * np.sqrt(periods_per_year)
Rolling Max Drawdown
python
def rolling_max_drawdown(equity: pd.Series, window: int = 252) -> pd.Series:
    """Rolling max drawdown over a fixed window."""
    result = pd.Series(index=equity.index, dtype=float)
    for i in range(window, len(equity)):
        window_eq = equity.iloc[i - window:i + 1]
        peak = window_eq.cummax()
        dd = (window_eq - peak) / peak
        result.iloc[i] = dd.min()
    return result

Trade-Level Analysis

When you have individual trade records:

python
def trade_statistics(pnl: pd.Series) -> dict:
    """Compute trade-level statistics from a series of trade PnL values.

    Args:
        pnl: Series where each value is the PnL of one trade.

    Returns:
        Dictionary of trade statistics.
    """
    wins = pnl[pnl > 0]
    losses = pnl[pnl < 0]
    total = len(pnl)

    win_rate = len(wins) / total if total > 0 else 0.0
    avg_win = wins.mean() if len(wins) > 0 else 0.0
    avg_loss = losses.mean() if len(losses) > 0 else 0.0
    largest_win = wins.max() if len(wins) > 0 else 0.0
    largest_loss = losses.min() if len(losses) > 0 else 0.0

    gross_profit = wins.sum() if len(wins) > 0 else 0.0
    gross_loss = abs(losses.sum()) if len(losses) > 0 else 0.0
    profit_factor = gross_profit / gross_loss if gross_loss > 0 else float("inf")

    expectancy = pnl.mean() if total > 0 else 0.0

    return {
        "total_trades": total,
        "win_rate": win_rate,
        "avg_win": avg_win,
        "avg_loss": avg_loss,
        "largest_win": largest_win,
        "largest_loss": largest_loss,
        "profit_factor": profit_factor,
        "expectancy": expectancy,
        "gross_profit": gross_profit,
        "gross_loss": gross_loss,
    }

Monthly / Yearly Return Tables

python
def monthly_returns_table(returns: pd.Series) -> pd.DataFrame:
    """Pivot returns into a month-by-year table.

    Returns:
        DataFrame with years as rows, months (1-12) as columns,
        and an Annual column.
    """
    monthly = returns.resample("ME").apply(lambda x: (1 + x).prod() - 1)
    table = monthly.groupby([monthly.index.year, monthly.index.month]).first()
    table = table.unstack(level=1)
    table.columns = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ]
    # Annual column
    annual = returns.resample("YE").apply(lambda x: (1 + x).prod() - 1)
    table["Annual"] = annual.values[:len(table)]
    return table

Benchmark Comparison

python
def benchmark_comparison(
    strategy_returns: pd.Series,
    benchmark_returns: pd.Series,
    rf: float = 0.0
) -> dict:
    """Compare strategy to benchmark across key metrics."""
    strat_eq = (1 + strategy_returns).cumprod()
    bench_eq = (1 + benchmark_returns).cumprod()

    return {
        "strategy_total_return": strat_eq.iloc[-1] - 1,
        "benchmark_total_return": bench_eq.iloc[-1] - 1,
        "strategy_sharpe": sharpe_ratio(strategy_returns, rf),
        "benchmark_sharpe": sharpe_ratio(benchmark_returns, rf),
        "strategy_max_dd": max_drawdown(strat_eq),
        "benchmark_max_dd": max_drawdown(bench_eq),
        "information_ratio": information_ratio(strategy_returns, benchmark_returns),
        "correlation": strategy_returns.corr(benchmark_returns),
        "beta": (
            strategy_returns.cov(benchmark_returns)
            / benchmark_returns.var()
        ),
        "alpha": (
            strategy_returns.mean()
            - (strategy_returns.cov(benchmark_returns) / benchmark_returns.var())
            * benchmark_returns.mean()
        ) * 252,
    }

Quantstats HTML Reports

Generate investor-ready HTML reports with one function call:

python
import quantstats as qs

# From returns Series
qs.reports.html(
    returns,
    benchmark=benchmark_returns,  # optional
    output="report.html",
    title="My Strategy",
    rf=0.0,
    periods_per_year=252
)

# Individual metrics
print(f"Sharpe: {qs.stats.sharpe(returns):.2f}")
print(f"Sortino: {qs.stats.sortino(returns):.2f}")
print(f"Max DD: {qs.stats.max_drawdown(returns):.2%}")
print(f"Calmar: {qs.stats.calmar(returns):.2f}")

# Console tearsheet
qs.reports.full(returns)

See references/quantstats_guide.md for full API reference and customization.

Integration with Vectorbt

python
import vectorbt as vbt

# After running a vectorbt backtest
portfolio = vbt.Portfolio.from_signals(close, entries, exits, init_cash=10000)

# Extract equity curve
equity = portfolio.value()
returns = portfolio.returns()

# Use quantstats
qs.reports.html(returns, output="backtest_report.html")

Files

FileDescription
references/metrics_guide.mdFormulas, derivations, annualization factors, interpretation benchmarks
references/quantstats_guide.mdQuantstats library API, customization, integration patterns
scripts/analyze_portfolio.pySingle portfolio analysis with all metrics, rolling stats, monthly table
scripts/compare_strategies.pyMulti-strategy comparison with ranking by risk-adjusted metrics
  • vectorbt — Backtesting engine that produces equity curves for analysis
  • risk-management — Portfolio-level risk guardrails and allocation
  • position-sizing — Optimal position sizing using portfolio metrics
  • kelly-criterion — Optimal growth rate sizing from win rate and payoff
  • trading-visualization — Chart generation for equity curves and drawdowns

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

Files

SKILL.md and 4 other files (scripts, references) in skills/portfolio-analytics of agiprolabs/claude-trading-skills.

  • SKILL.md
  • references/metrics_guide.md
  • references/quantstats_guide.md
  • scripts/analyze_portfolio.py
  • scripts/compare_strategies.py

Open the folder on GitHubat commit 981e1d7

Compare with similar skills

Portfolio Analytics 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 Analytics compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Portfolio Analytics this skillagiprolabs/claude-trading-skills410—~2.9kAutomated safety check: PassMIT
Technical Analysttradermonty/claude-trading-skills3k4 repos~4.6kAutomated safety check: PassMIT
Theme Detectortradermonty/claude-trading-skills3k2 repos~4.9kAutomated safety check: PassMIT
Creating Financial ModelsChen-zexi/open-ptc-agent7293 repos~1.3kAutomated safety check: PassMIT
Stock APIzhangxiangliang/stock-api2k—~507Automated safety check: PassMIT
Itr Walakaranb192/itr-wala871—~3.6kAutomated safety check: PassMIT

Similar skills

  • Technical Analyst

    tradermonty/claude-trading-skills

    This skill should be used when analyzing weekly price charts for stocks, stock indices, cryptocurrencies, or forex pairs.

    3k GitHub starsUsed in 4 repos~4.6k tokens
    Business, Finance & HRAuto-check passed
  • Theme Detector

    tradermonty/claude-trading-skills

    Detect and analyze trending market themes across sectors. An agent skill from tradermonty/claude-trading-skills.

    3k GitHub starsUsed in 2 repos~4.9k tokens
    Business, Finance & HRAuto-check passed
  • Creating Financial Models

    Chen-zexi/open-ptc-agent

    This skill provides an advanced financial modeling suite with DCF analysis, sensitivity testing, Monte Carlo simulations, and scenario planning for investment decisions

    729 GitHub starsUsed in 3 repos~1.3k tokens
    Business, Finance & HRAuto-check passed
  • Stock API

    zhangxiangliang/stock-api

    Fetch real-time stock quotes, K-line (candlestick) history, and search symbols for China A-shares, Hong Kong, and US markets.

    2k GitHub stars~507 tokensUpdated today
    Business, Finance & HRAuto-check passed
  • Itr Wala

    karanb192/itr-wala

    File Indian income tax returns (ITR) for FY 2025-26 / AY 2026-27.

    871 GitHub stars~3.6k tokensUpdated 5 days ago
    Business, Finance & HRAuto-check passed
  • Tushare Data

    zillionare/zillionare

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

    321 GitHub starsUsed in 2 repos~2.3k tokens
    Business, Finance & HRAuto-check passed

More from agiprolabs/claude-trading-skills

All 68 skills in this repo
  • Backtrader

    agiprolabs/claude-trading-skills

    Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Birdeye API

    agiprolabs/claude-trading-skills

    Solana token market data via Birdeye — prices, OHLCV, trades, token metadata, security checks, and trader activity

    410 GitHub stars~1.8k tokensUpdated 1 mo ago
    Auto-check passed
  • Coingecko API

    agiprolabs/claude-trading-skills

    Broad crypto market data from CoinGecko covering 13,000+ tokens.

    410 GitHub stars~1.6k tokensUpdated 1 mo ago
    Auto-check passed
  • Cointegration Analysis

    agiprolabs/claude-trading-skills

    Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis

    410 GitHub stars~2.1k tokensUpdated 1 mo ago
    Auto-check passed
  • Copy Trading

    agiprolabs/claude-trading-skills

    Wallet evaluation, monitoring, and copy-trade strategy design for Solana DEX trading

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Correlation Analysis

    agiprolabs/claude-trading-skills

    Cross-asset correlation analysis including rolling correlation, hierarchical clustering, tail dependence, and regime-dependent correlation

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed

Questions about Portfolio Analytics

What does Portfolio Analytics do?

Portfolio-level performance measurement including return metrics, risk metrics, risk-adjusted ratios, rolling analysis, and HTML reports. Portfolio Analytics is an agent skill from agiprolabs/claude-trading-skills.

When should I use Portfolio Analytics?

Portfolio Analytics fits situations like: business, Finance & HR work in your project.

How do I install Portfolio Analytics in Claude Code?

Run `npx skills add agiprolabs/claude-trading-skills --skill portfolio-analytics -a claude-code`. Or copy the skill folder (skills/portfolio-analytics in agiprolabs/claude-trading-skills) into .claude/skills/portfolio-analytics in your project. Claude Code loads it when a task matches its description.

How do I install Portfolio Analytics in Codex?

Run `npx skills add agiprolabs/claude-trading-skills --skill portfolio-analytics -a codex`. Or copy the skill folder (skills/portfolio-analytics in agiprolabs/claude-trading-skills) into .agents/skills/portfolio-analytics in your project. Codex loads it when a task matches its description.

Can I use Portfolio Analytics 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 agiprolabs/claude-trading-skills --skill portfolio-analytics -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-analytics, .gemini/skills/portfolio-analytics, .github/skills/portfolio-analytics and .opencode/skills/portfolio-analytics in your project.

What does Portfolio Analytics need to run?

Going by SKILL.md and its folder, Portfolio Analytics needs Python for the scripts in its folder and the command-line tools its instructions call (uv). Our summary lists: Python 3.

Does Portfolio Analytics access the network?

SKILL.md contains no URLs. Its commands use uv, which can reach the network depending on how they are called. This is read from the text; nothing was executed.

Is Portfolio Analytics 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. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Portfolio Analytics use?

Portfolio Analytics 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 Analytics use?

About 2.9k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 3.7k tokens, read only when the agent opens those files.

What are the alternatives to Portfolio Analytics?

Skills that share tags, products or a category with Portfolio Analytics: Technical Analyst (tradermonty/claude-trading-skills, 3k stars), Theme Detector (tradermonty/claude-trading-skills, 3k stars), Creating Financial Models (Chen-zexi/open-ptc-agent, 729 stars) and Stock API (zhangxiangliang/stock-api, 2k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Portfolio Analytics?

agiprolabs (a GitHub user) maintains it in agiprolabs/claude-trading-skills, which has 410 GitHub stars. The repository holds 68 skills in this directory. The repository was last updated on September 3, 2026.

Source: agiprolabs/claude-trading-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.