Communitygithub.com

NVlabs/Skill2Env

在用户要求使用 Mean-CVaR、有效前沿、情景生成或 NVIDIA cuOpt 构建、优化、回测、再平衡或分析股票投资组合时使用。

Skill2Env 是什么?

cuFOLIO 是一个 NVIDIA 加速的量化投资组合构建与分析工具,专门用于 Mean-CVaR 优化。该技能使 AI 代理能够利用 GPU 加速的 cuOpt 求解器,从股票价格数据中计算收益率、生成核密度估计(KDE)情景、求解资产配置权重、绘制有效前沿、进行投资组合回测,并执行定期或漂移触发的再平衡。它支持标准普尔 500、标准普尔 100、道琼斯 30 等常见指数数据集,也支持用户提供的 CSV 文件。核心工作流完全基于 cuFOLIO 包,代理必须使用官方的 cuFOLIO API,而非自行实现或使用 pandas/scipy/cvxpy 等通用库。该技能要求 NVIDIA GPU 运行时环境以启用 cuOpt 和 cuML,触发的关键短语包括“优化我的投资组合”、“构建 CVaR 投资组合”、“使用 cuFOLIO”等。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/NVlabs/Skill2Env/tree/HEAD/SkillHub/skills/nvidia/cufolio

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

cuFOLIO 技能

目的

使用 NVIDIA 加速的 Mean-CVaR 优化来构建和分析量化投资组合。使用 cuFOLIO 计算收益率、生成 KDE 情景、通过 cuOpt GPU 求解器求解资产配置、追踪有效前沿、回测投资组合,并根据价格数据运行再平衡工作流。

何时使用

当任务涉及以下内容时使用此技能:

  • 根据股票价格构建或优化 Mean-CVaR 投资组合。
  • 在控制下行 CVaR 风险的同时,为多个股票代码分配权重。
  • 绘制或检查投资组合候选集的有效前沿。
  • 生成按风险厌恶程度排序的权重表。
  • 将优化后的投资组合与基准进行回测。
  • 按计划或漂移触发条件再平衡投资组合。
  • 在标准普尔 500、标准普尔 100、道琼斯 30 或用户提供的价格数据集上运行工作流。

常见的触发短语包括“优化我的投资组合”、“构建 CVaR 投资组合”、“对这些股票代码使用 cuFOLIO”、“使用 cuOpt 求解”、“绘制有效前沿”、“按风险厌恶程度显示权重”、“回测此配置”、“月度再平衡”、“使用 CVaR 分析我的持仓”、“比较配置”、“降低下行风险”、“构建资产配置”、“评估配置选项”、“压力测试我的持仓”、“评估下行风险暴露”、“在权重上限下审查我的持仓”、“比较基准投资组合”、“模拟 CVaR 情景”、“筛查投资组合风险”、“在约束下优化持仓”和“寻找更低风险的配置”。

请勿将其用于通用金融摘要、价格预测、神经网络训练、车辆路径规划或非投资组合优化。

前提条件

  • 已安装 cufolio 包的 Python 环境。
  • 已安装 cuOpt 和 cuML 的 NVIDIA GPU 运行时。
  • 与宿主机匹配的 CUDA 扩展,例如 uv sync --extra cuda12 或 uv sync --extra cuda13。
  • 暴露 cp.CUOPT 的 cvxpy。
  • 首次运行时若需下载默认价格 CSV,则需网络访问。

设置

此技能驱动已安装的 cufolio 包。就绪环境可通过 Brev 可启动实例获得,或从 NVIDIA-AI-Blueprints/cuFOLIO 获得(需安装匹配的 CUDA 扩展)。

在打包的代理/评估沙箱中,cufolio 可能通过 PYTHONPATH 提供,而非作为单独发布的 wheel 包。在声明其缺失前,请首先通过 python -c "import cufolio" 验证本地包。切勿 pip install cufolio,不要从头重写 cuFOLIO 工作流,也不要用通用的 pandas/scipy/cvxpy 组合代码替换包 API。

如需具体实现细节,请以 references/workflows/agent_recipes.md 为准。它包含加载价格、准备收益率、使用 cuOpt 求解、构建 25 点有效前沿、针对等权基准进行回测以及调用再平衡器的精确工作代码模板。

默认数据集是 data/stock_data/sp500.csv,已在 .gitignore 中忽略。在首次下载前,请告知用户这将通过 cuFOLIO/yfinance 数据助手获取公开市场数据,并在征得用户同意后执行:

import cvxpy as cp
from cufolio.cvar_parameters import CvarParameters
from cufolio.utils import download_data

download_data("data/stock_data", datasets=["sp500"])
SOLVER_SETTINGS = {"solver": cp.CUOPT, "verbose": False, "solver_method": "PDLP"}
cvar_params = CvarParameters(
    w_min=0.0, w_max=1.0,
    c_min=0.0, c_max=0.0,
    risk_aversion=1.0, confidence=0.95,
)

指示

在执行前简要说明将应用的默认设置,然后遵循以下指引:

  1. 加载 data/stock_data/sp500.csv;如果文件缺失,请在下载 sp500 前使用 cufolio.utils.download_data 征求用户同意。不要使用通配符、替换或虚构价格数据。
  2. 在求解前验证用户提供的 CSV:要求数据具有类日期索引或第一列为日期、数字类型的股票代码列、日期过滤后至少 60 行数据、且至少包含一个用户请求的股票代码。如果用户提供了起始/结束日期,则在收益率计算前对价格 DataFrame 进行切片,并报告保留的日期范围。在计算收益率前,对价格 DataFrame 过滤股票代码。regime_dict 不包含股票代码字段。
  3. 使用 utils.calculate_returns(...) 计算对数收益率。
  4. 使用 cvar_utils.generate_cvar_data(...)、KDE 和 KDESettings(device="GPU") 生成情景。
  5. 定义 CvarParameters,其中显式指定 w_min 和 w_max。对于普通的“构建最优投资组合”请求,设置 c_min=0.0 和 c_max=0.0,使结果实现满仓投资而非 100% 现金。
  6. 直接从收益率字典构建 cvar_optimizer.CVaR(returns_dict, cvar_params);保持股票代码、情景数组、均值和协方差的形状与 cuFOLIO 助手返回的一致。
  7. 仅使用 NVIDIA cuOpt 求解。求解前,验证 hasattr(cp, "CUOPT") 且 str(cp.CUOPT) in {str(s) for s in cp.installed_solvers()}。将 SOLVER_SETTINGS 传递给每次单次求解或循环的有效前沿求解。切勿回退到 CLARABEL、SCS、ECOS 或其他 CPU 求解器。如果 cuOpt 缺失,则完成验证/设置后报告 GPU/cuOpt 运行时缺失,而非虚构一个 CPU 结果。
  8. 对于自定义约束,将用户请求映射到 CvarParameters:权重上限映射到 w_min/w_max,风险偏好映射到 risk_aversion,置信水平映射到 confidence,现金允许比例映射到 c_max,基数约束仅当包为此工作流显式暴露了资产数量约束时才使用。如果约束冲突(例如,最大权重太低而无法在请求的股票代码数量上分配投资),请解释冲突并要求用户放松约束,而非自行猜测。
  9. 如果用户未指定回测基准,则使用相同股票代码的等权投资组合。如果用户未指定约束,则保持默认值表并简要重述求解前的重要假设。
  10. 按配置比例降序输出权重、现金权重、预期收益率、CVaR、求解器标签(cuOpt GPU),以及任何请求的有效前沿图、权重表、回测指标或再平衡计划。对于表格,应包括股票代码作为列或行,并显示小数权重和百分比;对于图表,保留 cuFOLIO 返回的图形而非从头重绘。
  11. 对于报告级答案,应包含所请求工作流实际运行的证据。对于有效前沿,说明 len(results_df) 并使用请求的 ra_num(除非用户另行指定,否则为 25)。对于权重表,将 results_df["weights"] 展开为股票代码列并包含 cash 和 risk_aversion。对于回测,包括优化组合和基准组合的 mean portfolio return、sharpe、sortino 和 max drawdown。对于再平衡,包括 results_dataframe、re_optimize_dates 和 cumulative_portfolio_value 的尾部。

标准工作流骨架

从以下模板开始积极的 cuFOLIO 任务,并仅调整所需的输出。在编写自定义代码前,请阅读 references/workflows/agent_recipes.md 获取完整的可复制函数。

import cvxpy as cp
import pandas as pd

from cufolio import backtest, cvar_optimizer, cvar_utils, rebalance, utils
from cufolio.cvar_parameters import CvarParameters
from cufolio.portfolio import Portfolio
from cufolio.settings import KDESettings, ReturnsComputeSettings, ScenarioGenerationSettings

if not hasattr(cp, "CUOPT") or str(cp.CUOPT) not in {str(s) for s in cp.installed_solvers()}:
    raise RuntimeError("需要 cuOpt GPU 求解器;请勿替换为 CPU 求解器。")

SOLVER_SETTINGS = {"solver": cp.CUOPT, "verbose": False, "solver_method": "PDLP"}

prices = utils.get_input_data("data/stock_data/sp500.csv")
returns_dict = utils.calculate_returns(
    prices,
    regime_dict=None,
    returns_compute_settings=ReturnsComputeSettings(return_type="LOG"),
)
returns_dict = cvar_utils.generate_cvar_data(
    returns_dict,
    ScenarioGenerationSettings(
        fit_type="kde",
        kde_settings=KDESettings(device="GPU"),
    ),
)
cvar_params = CvarParameters(
    w_min=0.0,
    w_max=1.0,
    c_min=0.0,
    c_max=0.0,
    risk_aversion=1.0,
    confidence=0.95,
)
optimizer = cvar_optimizer.CVaR(returns_dict, cvar_params)
result, optimal_portfolio = optimizer.solve_optimization_problem(
    solver_settings=SOLVER_SETTINGS,
    print_results=False,
)

如需有效前沿或权重表,调用:

results_df, fig, ax = cvar_utils.create_efficient_frontier(
    returns_dict,
    cvar_params,
    SOLVER_SETTINGS,
    ra_num=25,
    show_plot=False,
    show_discretized_portfolios=False,
    benchmark_portfolios=False,
    print_portfolio_results=False,
)
weights_table = pd.DataFrame(results_df["weights"].tolist(), index=results_df.index)

如需基准回测,将求解得到的配置包装为 Portfolio(name="cuOpt Optimal", tickers=returns_dict["tickers"], weights=optimal_portfolio.weights, cash=optimal_portfolio.cash),在相同的 returns_dict["tickers"] 上创建一个等权 Portfolio,然后使用 backtest.portfolio_backtester(..., test_method="historical").backtest_against_benchmarks(...)。回测器返回 (backtest_results, ax)。

如需月度再平衡,先将价格 DataFrame 写入 CSV 路径。实例化 rebalance.rebalance_portfolio(dataset_directory=<csv_path>, ...),设置 re_optimize_criteria={"type": "drift_from_optimal", "threshold": 0, "norm": 1},并调用 re_optimize(transaction_cost_factor=..., plot_title="Monthly Rebalancing")。再平衡器返回 (results_dataframe, re_optimize_dates, cumulative_portfolio_value)。

数据与默认值

设置项默认值
数据集data/stock_data/sp500.csv
日期范围全部可用范围
投资组合类型仅做多
最大权重除非指定,否则无限制
风险厌恶系数1.0
置信水平0.95
情景方法GPU 上的 KDE
求解器cuOpt GPU with PDLP
再平衡除非请求,否则无

默认的标准普尔 500 文件是一个历史快照,可能遗漏当前成分股。用户提供的 CSV 应为日期索引的价格表,包含股票代码列,兼容 utils.get_input_data。如果请求的股票代码不存在,则将其丢弃,报告遗漏情况,并使用可用列继续处理,除非用户明确要求获取其他数据。

关键 API

使用包 API 而非自行实现投资组合数学或模拟循环。cuFOLIO 助手返回扁平对象:returns_dict 包含 returns、mean、covariance 和 tickers 等键;不要将其索引为 returns_dict["regime_1"]。solve_optimization_problem(...) 返回 (result_row, portfolio),而非嵌套的结果字典。

  • 收益率:utils.calculate_returns(input_dataset, regime_dict, returns_compute_settings)。
  • 制度过滤器:regime_dict 为 None 或 {"name": "...", "range": ("YYYY-MM-DD", "YYYY-MM-DD")};不以制度名称为键,也不包含股票代码。
  • 情景:cvar_utils.generate_cvar_data(returns_dict, scenario_generation_settings)。
  • 优化器:cvar_optimizer.CVaR(returns_dict, cvar_params)。
  • 求解:result_row, portfolio = cvar_problem.solve_optimization_problem(solver_settings=SOLVER_SETTINGS, print_results=False)。
  • 有效前沿:cvar_utils.create_efficient_frontier(returns_dict, cvar_params, solver_settings=SOLVER_SETTINGS, ra_num=25)。返回的 results_df 包含指标、weights 字典列和 cash。
  • 投资组合:Portfolio(name="", tickers=None, weights=None, cash=0.0, time_range=None);传入股票代码和一个与这些股票代码对齐的扁平类数组 weights。
  • 回测:为优化配置和每个基准分别创建 portfolio.Portfolio 对象;对于等权基准,使用权 weight = 1 / len(tickers) 和 cash=0.0,然后调用 backtest.portfolio_backtester(test_portfolio, returns_dict, risk_free_rate=0.0, test_method="historical", benchmark_portfolios=[...]).backtest_against_benchmarks(...)。
  • 再平衡:rebalance.rebalance_portfolio(...) 要求 dataset_directory 为 CSV 路径,而非 DataFrame。调用 re_optimize(...);它返回 (results_dataframe, re_optimize_dates, cumulative_portfolio_value)。
  • 设置模型:ReturnsComputeSettings、ScenarioGenerationSettings、KDESettings、ApiSettings 和 CvarParameters。

示例

  • “从标准普尔 500 构建最优投资组合”:加载价格,计算对数收益率,生成 GPU KDE 情景,设置仅做多、满仓的 CvarParameters,使用 cuOpt 求解,并报告多元化权重及收益率/CVaR。
  • “绘制有效前沿”:调用 create_efficient_frontier(...),返回 results_df,并根据请求显示或保存图形。
  • “按风险厌恶程度给我权重”:将 results_df["weights"] 展开为每个资产的表格。
  • “针对等权基准进行回测”:构建优化组合和等权组合的 Portfolio 对象,然后使用 cuFOLIO 回测器并报告夏普比率、索提诺比率和最大回撤。
  • “回测月度再平衡”:使用上述漂移触发条件配置 rebalance_portfolio,并运行 re_optimize(transaction_cost_factor=...)。

限制

  • 需要 NVIDIA GPU 并安装 cuOpt 和 cuML;CPU 求解器被明确禁止。
  • 纯 CPU 的评估容器仍可验证路由、数据处理和报告行为,但无法产生有效的 cuOpt 求解结果。在这种情况下,请明确报告缺失 GPU/cuOpt 运行时。
  • 默认价格数据是历史快照,可能遗漏当前成分股。
  • 首次运行的数据集下载依赖于网络访问,除非用户提供 CSV。

故障排除

  • 缺少默认 CSV 或出现 FileNotFoundError:解释 cuFOLIO 将使用 download_data("data/stock_data", datasets=["sp500"]) 获取公开市场数据;仅在用户确认后运行。
  • SolverError 或缺失 cp.CUOPT:安装与宿主机匹配的 CUDA 扩展,并通过 python -c "import cvxpy as cp; print(hasattr(cp, 'CUOPT'), cp.installed_solvers())" 验证。

Individual skills in this repo

This repo contains 13 individual skills — each has its own dedicated page.

NVlabs/Skill2Env

This skill should be used when the user asks about "digital portfolio", "portfolio website", "project description", "case study", "portfolio curation", "creative portfolio", "act as a portfolio curator", "portfolio curator mode", "portfolio review", "professional presentation", "portfolio architecture", "work samples", "portfolio bio", or needs expertise in building, structuring, and writing professional digital portfolios. Part of the AlterLab FC Skills collection (New Media & Communication department).

NVlabs/Skill2Env

This skill should be used when the user asks about "web content strategy", "SEO writing", "UX writing", "information architecture", "content architecture", "website structure", "act as a web content strategist", "web strategist mode", "site map", "content audit", "microcopy", "meta descriptions", "content hierarchy", "content governance", or needs expertise in planning, structuring, and writing content for websites and digital platforms. Part of the AlterLab FC Skills collection (New Media & Communication department).

NVlabs/Skill2Env

When the user wants to create, generate, or produce video content using AI tools or programmatic frameworks. Also use when the user mentions 'video production,' 'AI video,' 'Remotion,' 'Hyperframes,' 'HeyGen,' 'Synthesia,' 'Veo,' 'Sora,' 'Runway,' 'Kling,' 'Seedance,' 'Hailuo,' 'MiniMax,' 'Pika,' 'Hunyuan,' 'Wan,' 'video generation,' 'AI avatar,' 'talking head video,' 'programmatic video,' 'video template,' 'explainer video,' 'product demo video,' 'video pipeline,' or 'make me a video.' Use this for video creation, generation, and production workflows. For video content strategy and what to post, see social. For paid video ad creative, see ad-creative.

NVlabs/Skill2Env

Balance visual design with ATS compatibility for creative roles

NVlabs/Skill2Env

Build immersive, cinematic 2.5D interactive websites using scroll storytelling, parallax depth, text animations, and premium scroll effects — no WebGL required. Use this skill for any web design task: landing pages, product sites, hero sections, scroll animations, parallax, sticky sections, section overlaps, floating products between sections, clip-path reveals, text that flies in from sides, words that light up on scroll, curtain drops, iris opens, card stacks, bleed typography, and any site that should feel cinematic or premium. Trigger on phrases like "make it feel alive", "Apple-style animation", "sections that overlap", "product rises between sections", "immersive", "scrollytelling", or any scroll-driven visual effect. Covers 45+ techniques across 8 categories. Always inspects, judges, and plans assets before coding. Use aggressively for ANY web design task.

NVlabs/Skill2Env

Read-only queue dashboard for workspace-aware ship. (gstack)

NVlabs/Skill2Env

Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.

NVlabs/Skill2Env

Audits any landing or service page across 48 checks in 10 categories for LLM/AI discoverability, GEO readiness, content clarity, schema markup, internal linking, freshness signals, and technical crawlability. Produces an overall score out of 100, a per-category score out of 100, pass/warn/fail/ manual counts, and a prioritised fix list — all rendered as a standalone HTML report saved to disk. Use when a user provides a URL and asks to audit it, score it, check its GEO readiness, test its AI discoverability, run a landing page audit, or evaluate it for LLM citation potential. Also trigger on phrases like "audit this page", "score this URL", "check GEO for", "is this page AI-ready", "run a GEO audit", "LLM page check", "how would AI read this page", or "landing page score".

NVlabs/Skill2Env

Generates a premium single-page HTML landing page with 3D CSS animations, GSAP scroll effects, and mouse-parallax depth. Forcing intake (product + elevator pitch, audience register, brand overrides, tone) locks down positioning before any copy or markup is written, so the page reflects the actual product rather than generic boilerplate. Use whenever the user says 'landing for X', 'create a landing page', 'build a landing page', 'make a landing page for X', 'I need a web page for Y', or provides product/service details and wants a polished website. Also triggers on 'promotional page', 'product page', 'one-pager', 'web presence', 'sales page'. Outputs a single self-contained HTML file (Claude Code) or HTML artifact (Claude.ai). Supports configurable brand colors via CSS custom property overrides.

NVlabs/Skill2Env

Transform resume bullets into detailed portfolio case studies

NVlabs/Skill2Env

Generates high-converting landing pages as complete Next.js/React (TSX) components with Tailwind CSS. Creates hero sections, feature grids, pricing tables, FAQ accordions, testimonial blocks, and CTA sections using proven copy frameworks (PAS, AIDA, BAB). Outputs SEO meta tags, structured data, and performance-optimised code targeting Core Web Vitals (LCP < 1s, CLS < 0.1). Use when the user asks to create a landing page, marketing page, homepage, single-page site, lead capture page, campaign page, promo page, or conversion-optimised web page — or when they want to A/B test landing page variants or replace a static page with one designed to convert.

NVlabs/Skill2Env

> Visual design direction framework organized by emotional intent (Warm/Cold x Active/Calm). The first design reference system that categorizes sites by what they make you FEEL, not how they look. Includes 48 annotated public website references.

NVlabs/Skill2Env

Run a structured 5-pass finishing audit on any website before launch — scoring visual polish, technical foundation, UX completeness, content quality, and cross-device readiness on 100 points. Use when: **Pre-launch** - Final validation before going live; **Post-redesign** - Verify nothing broke during the overhaul; **Client handoff** - Structured proof that the site is ready; **Quarterly review** - Catch accumulated debt; **Single-pass focus** - Run just Pass 2 after a perf sprint

相关技能