Communitygithub.com

NVlabs/Skill2Env

在用於建構、優化、回測、再平衡或分析股票投資組合,並涉及均值-CVaR、效率前緣、情境生成或 NVIDIA cuOpt 時使用。

Skill2Env 是什麼?

此技能能讓 AI 代理使用 NVIDIA 加速的 cuFOLIO 套件建立與分析量化投資組合。它涵蓋 Mean-CVaR 優化,利用 cuOpt GPU 求解器進行資產配置。它支援多種工作流程,包括根據價格數據計算報酬率、使用 KDE 生成情境、描繪效率前緣、回測投資組合以及執行再平衡。此技能旨在與 Claude Code、Cursor 或 Codex 等 AI 代理開發工具配合使用。其 SDK 是以 Python 為基礎,需要一個具備 cuOpt 和 cuML 運作環境的 NVIDIA GPU。此工具透過一個結構化的 `SKILL.md` 檔案來管理,該檔案提供了詳細的使用說明、API 參考資料和工作流程範本。

相容平台~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 風險的同時,為各種股票代號配置權重。
  • 繪製或檢查一個投資組合世界(universe)的效率前緣。
  • 生成按風險厭惡程度劃分的權重表。
  • 對最佳化的投資組合進行回測,並與基準進行比較。
  • 按時間表或偏移觸發條件進行投資組合再平衡。
  • 對 S&P 500、S&P 100、Dow 30 或使用者提供的價格資料集執行工作流程。

常見的觸發詞包括「最佳化我的投資組合」、「建立一個 CVaR 投資組合」、「對這些股票代號使用 cuFOLIO」、「使用 cuOpt 求解」、「繪製效率前緣」、「按風險厭惡程度顯示權重」、「回測此配置」、「每月再平衡」、「使用 CVaR 分析我的持股」、「比較配置」、「降低下行風險」、「建構一個配置」、「評估配置選項」、「壓力測試我的持股」、「評估下行風險暴露」、「在權重限制下檢視我的持股」、「比較基準投資組合」、「模擬 CVaR 情境」、「篩選投資組合風險」、「在限制條件下最佳化持股」以及「尋找一個較低風險的配置」。

不要將它用於一般性的財務摘要、價格預測、神經網路訓練、車輛路徑規劃或非投資組合最佳化。

先決條件

  • 已安裝 cufolio 套件的 Python 環境。
  • 已安裝 cuOpt 和 cuML 的 NVIDIA GPU 執行環境。
  • 與主機匹配的 CUDA 擴充功能,例如 uv sync --extra cuda12 或 uv sync --extra cuda13。
  • cvxpy 需暴露 cp.CUOPT。
  • 如果是首次執行且必須下載預設的價格 CSV 檔案,則需要網路連線。

設定

此技能驅動已安裝的 cufolio 套件。一個現成的環境可以來自 Brev launchable 或來自 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;如果檔案缺失,請在使用 cufolio.utils.download_data 下載 sp500 之前提出請求。不要使用 glob 模式、替代或偽造價格數據。
  2. 在使用者提供 CSV 檔案之前進行驗證:需要一個類似日期的索引或第一個日期欄位、數字股票代號欄位、在日期過濾後至少 60 行,以及至少一個請求的股票代號。如果使用者提供開始/結束日期,請在計算報酬率之前先對價格 DataFrame 進行切片,並回報保留的日期範圍。在計算報酬率之前,先對價格 DataFrame 過濾股票代號。regime_dict 不接受股票代號欄位。
  3. 使用 utils.calculate_returns(...) 計算 LOG 報酬率。
  4. 使用 cvar_utils.generate_cvar_data(...)、KDE 和 KDESettings(device="GPU") 生成情境。
  5. 使用明確的 w_min 和 w_max 定義 CvarParameters。對於一般的「建立最佳投資組合」請求,將 c_min=0.0 和 c_max=0.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 solver is required; do not substitute a CPU solver.")

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 路徑。使用 re_optimize_criteria={"type": "drift_from_optimal", "threshold": 0, "norm": 1} 實體化 rebalance.rebalance_portfolio(dataset_directory=<csv_path>, ...),並呼叫 re_optimize(transaction_cost_factor=..., plot_title="Monthly Rebalancing")。再平衡器會回傳 (results_dataframe, re_optimize_dates, cumulative_portfolio_value)。

數據與預設值

設定預設值
資料集data/stock_data/sp500.csv
日期範圍完整的可用範圍
投資組合類型純做多 (Long-only)
最大權重除非指定,否則無
風險厭惡程度1.0
信心水準0.95
情境方法GPU 上的 KDE
求解器使用 PDLP 的 cuOpt GPU
再平衡除非請求,否則無

預設的 S&P 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 物件;對於等權重基準,使用 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。

範例

  • "從 S&P 500 建立最佳投資組合":載入價格、計算 LOG 報酬率、生成 GPU KDE 情境、設定純做多且完全投資的 CvarParameters、使用 cuOpt 求解,並回報分散的權重以及報酬率/CVaR。
  • "繪製效率前緣":呼叫 create_efficient_frontier(...)、回傳 results_df,並按需求顯示或儲存圖形。
  • "給我按風險厭惡程度劃分的權重":將 results_df["weights"] 展開為各資產的表格。
  • "針對等權重進行回測":建構最佳化和等權重的 Portfolio 物件,然後使用 cuFOLIO 回測器,並回報 Sharpe、Sortino 和最大回撤 (max drawdown)。
  • "回測每月再平衡":使用上述的偏移觸發條件配置 rebalance_portfolio,並執行 re_optimize(transaction_cost_factor=...)。

限制

  • 需要一個具備 cuOpt 和 cuML 的 NVIDIA GPU;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

相關技能