Repository navigation
Add hidden Portfolio Builder agent and route - #14
Conversation
Click the FINNY brand wordmark in the sidebar to open a Portfolio Builder form (funds, currency, account type, horizon, risk, asset universe, geography). Submitting composes a prompt and auto-submits it to a new hidden portfolio_builder agent (recommendation-only, edit/write/patch denied). Adds a portfoliobacktest tool that runs a yfinance-backed weighted-holdings backtest with configurable rebalance cadence. Also: deep-link from Recent algorithms card to a specific algorithm via algorithmId route param; titlecase converts underscores to spaces so agent names like portfolio_builder render as "Portfolio Builder".
There was a problem hiding this comment.
Pull request overview
Adds a hidden “Portfolio Builder” flow to the Finny TUI that navigates to a new intake form, auto-submits a composed prompt to a new hidden portfolio_builder agent, and introduces a new yfinance-backed portfolio backtest tool. Also adds algorithm deep-linking via a new algorithmId route parameter and improves display formatting for underscore-delimited identifiers.
Changes:
- Add hidden
portfolio_builderagent + prompt, and a discoverable TUI route opened by clicking the FINNY wordmark. - Add
finny_portfolio_backtesttool and register it in the tool registry. - Add route param support for deep-linking to a specific algorithm from the “Recent algorithms” card.
Reviewed changes
Copilot reviewed 14 out of 14 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/opencode/src/util/locale.ts | Update Locale.titlecase to render underscore names with spaces. |
| packages/opencode/src/tool/registry.ts | Register the new portfolio backtest tool in the tool registry. |
| packages/opencode/src/tool/portfolio-backtest.ts | Add Python/yfinance-powered portfolio backtest tool implementation. |
| packages/opencode/src/cli/cmd/tui/routes/portfolio-builder.tsx | New TUI intake form that composes a prompt and navigates to Home with auto-submit. |
| packages/opencode/src/cli/cmd/tui/routes/home.tsx | Add autoSubmit handling for route-provided initial prompts. |
| packages/opencode/src/cli/cmd/tui/routes/algorithms.tsx | Support selecting an algorithm via route algorithmId and react to updates. |
| packages/opencode/src/cli/cmd/tui/context/route.tsx | Extend route types with autoSubmit, algorithmId, and portfolio-builder. |
| packages/opencode/src/cli/cmd/tui/context/local.tsx | Adjust agent selection to prevent choosing subagents (while keeping hidden behavior). |
| packages/opencode/src/cli/cmd/tui/component/sidebar-nav.tsx | Make FINNY wordmark navigate to the hidden Portfolio Builder route. |
| packages/opencode/src/cli/cmd/tui/component/route-header.tsx | Add icon for the new portfolio-builder route. |
| packages/opencode/src/cli/cmd/tui/component/card-recent-algos.tsx | Deep-link to Algorithms route with a specific algorithmId. |
| packages/opencode/src/cli/cmd/tui/app.tsx | Wire up new route + title mapping + component mount for Portfolio Builder. |
| packages/opencode/src/agent/prompt/finny-portfolio-builder.txt | Add the Portfolio Builder system prompt content and output spec. |
| packages/opencode/src/agent/agent.ts | Register the new hidden portfolio_builder agent and prompt. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| permission: Permission.merge( | ||
| defaults, | ||
| Permission.fromConfig({ | ||
| question: "allow", | ||
| edit: "deny", | ||
| write: "deny", | ||
| patch: "deny", | ||
| }), | ||
| user, | ||
| ), |
| ## Equities (60%) | ||
| | Ticker | Name | Sector | Region | Weight | $ | Rationale | | ||
| |---|---|---|---|---:|---:|---| | ||
| | VFV.TO | Vanguard S&P 500 (CAD-hedged) | Broad | US | 25% | 6,250 | core US large-cap | |
| import sys, json, argparse, math, subprocess | ||
| from pathlib import Path | ||
|
|
||
| try: | ||
| import yfinance as yf | ||
| import pandas as pd | ||
| except ImportError: | ||
| subprocess.check_call([sys.executable, "-m", "pip", "install", "--quiet", "yfinance", "pandas"]) | ||
| import yfinance as yf | ||
| import pandas as pd |
| return (date.replace(day=1) + pd.offsets.MonthEnd(1)).normalize() | ||
| if kind == "quarterly": | ||
| return (date + pd.offsets.QuarterEnd(0)).normalize() | ||
| if kind == "yearly": | ||
| return (date + pd.offsets.YearEnd(0)).normalize() |
| let pythonCmd = "python3" | ||
| try { | ||
| await Process.run(["python3", "--version"]) | ||
| } catch { | ||
| try { | ||
| await Process.run(["python", "--version"]) | ||
| pythonCmd = "python" | ||
| } catch { | ||
| return { | ||
| title: "Portfolio backtest failed", | ||
| output: "Python 3 not found. Install Python 3 (e.g. brew install python3) and try again.", | ||
| metadata: {}, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| let tmpDir: string | undefined | ||
| try { | ||
| tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "finny-pf-backtest-")) | ||
| const scriptPath = path.join(tmpDir, "pf_backtest.py") | ||
| const configPath = path.join(tmpDir, "config.json") | ||
| await fs.writeFile(scriptPath, PORTFOLIO_BACKTEST_PY) | ||
| await fs.writeFile( | ||
| configPath, | ||
| JSON.stringify( | ||
| { | ||
| holdings: params.holdings.map((h) => ({ ticker: h.ticker, weight: h.weight })), | ||
| capital: params.capital, | ||
| start, | ||
| end, | ||
| rebalance: params.rebalance, | ||
| }, | ||
| null, | ||
| 2, | ||
| ), | ||
| ) | ||
|
|
||
| const result = await Process.run([pythonCmd, scriptPath, "--config", configPath], { | ||
| cwd: tmpDir, | ||
| nothrow: true, | ||
| timeout: 120_000, | ||
| }) |
| } | ||
|
|
||
| function fmtUsd(x: number): string { | ||
| return `$${x.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` |
- agent.ts: apply finnyFileSystemSandbox to portfolio_builder so the hidden agent can't read/grep/list/bash the user's filesystem; matches the sandbox already in use on build/research/chat. - finny-portfolio-builder.txt: VFV.TO is the unhedged CAD-listed S&P 500 ETF, not the CAD-hedged variant — correct the example label so generated plans don't propagate the mismatch. - portfolio-backtest.ts: replace the inline `pip install` fallback with ensurePythonEnv (matches quote.ts / price-history.ts). Drops the PEP 668 / no-pip Linux failure mode and stops pip logs from contaminating the JSON-on-stdout contract. - portfolio-backtest.ts: wire ctx.abort into Process.run so cancelling a session reliably kills the python child. - portfolio-backtest.ts: rewrite next_threshold so the next rebalance date is strictly AFTER the pivot. The old code returned the current period end when the pivot was already at month/quarter/year end, triggering a duplicate rebalance on the next trading day. - portfolio-backtest.ts: add `currency` parameter (USD/CAD/EUR) and format output via Intl.NumberFormat instead of hardcoded `$` + en-US. Prompt updated to forward the intake currency to the tool.
| currency: z | ||
| .enum(["USD", "CAD", "EUR"]) | ||
| .default("USD") | ||
| .describe("ISO currency for `capital` and output formatting. Default 'USD'."), | ||
| }) |
| # Daily returns from equity curve. | ||
| ec_vals = list(ec.values) | ||
| rets = [] | ||
| for i in range(1, len(ec_vals)): | ||
| if ec_vals[i - 1] > 0: | ||
| rets.append((ec_vals[i] - ec_vals[i - 1]) / ec_vals[i - 1]) | ||
| if len(rets) > 1: | ||
| mean_r = sum(rets) / len(rets) | ||
| var_r = sum((r - mean_r) ** 2 for r in rets) / (len(rets) - 1) | ||
| std_r = math.sqrt(var_r) | ||
| ann_vol = std_r * math.sqrt(252) | ||
| ann_sharpe = (mean_r * 252) / ann_vol if ann_vol > 0 else 0.0 |
| function computeDateRange(duration: string): { start: string; end: string } { | ||
| const end = new Date() | ||
| const start = new Date() | ||
| const m = /^(\d+)([dwmy])$/.exec(duration.trim().toLowerCase()) | ||
| if (m) { | ||
| const n = parseInt(m[1], 10) | ||
| switch (m[2]) { | ||
| case "d": | ||
| start.setDate(start.getDate() - n) | ||
| break | ||
| case "w": | ||
| start.setDate(start.getDate() - n * 7) | ||
| break | ||
| case "m": | ||
| start.setMonth(start.getMonth() - n) | ||
| break | ||
| case "y": | ||
| start.setFullYear(start.getFullYear() - n) | ||
| break |
| if (totalWeight <= 0) { | ||
| return { | ||
| title: "Portfolio backtest failed", | ||
| output: "All weights are zero — nothing to backtest.", | ||
| metadata: {}, | ||
| } | ||
| } |
| return ( | ||
| sync.data.agent.find((x) => x.name === agentStore.current && x.mode !== "subagent") ?? agents()[0] | ||
| ) | ||
| }, | ||
| set(name: string) { | ||
| if (!agents().some((x) => x.name === name)) | ||
| if (!sync.data.agent.some((x) => x.name === name && x.mode !== "subagent")) | ||
| return toast.show({ |
- portfolio-backtest.ts: detect each ticker's listing currency via
yfinance fast_info / .info and FX-convert non-matching series into
the target currency before computing shares + equity. Without this
the canonical Canadian-TFSA case (VFV.TO + VOO + BTC-USD into CAD
capital) produced unit-mismatched equity curves. FX failures error
out with a clear message instead of silently corrupting results.
- portfolio-backtest.ts: derive the annualization factor from observed
span (len(rets) / span_days * 365.25) instead of hardcoding 252.
Equity-only portfolios still annualize at ~252, crypto-only at ~365,
mixed sits between — vol/Sharpe no longer skewed for crypto-bearing
portfolios. Surfaced in the rendered output ("annualizing at ~N
obs/yr").
- portfolio-backtest.ts: computeDateRange now setDate(1) before
subtracting months/years so a Mar-31 anchor doesn't roll forward to
Mar-3 when JS interprets "Feb 31" — the duration window now reliably
contains the requested span.
- portfolio-backtest.ts: validate that weights sum to ~1.0 (±0.02
tolerance) and reject unnormalized inputs with a clear error rather
than silently rescaling in Python. Surfaced in the prompt so the
agent emits normalized weights.
- local.tsx: agent.color() now does a direct name lookup against
sync.data.agent (which includes hidden agents) for a configured
color, falling back to the visibleAgents cycling palette only when
no color is set. Hidden agents like portfolio_builder now render
with their configured #eab308 instead of the default secondary.
- prompt: tell the agent that weights MUST sum to 1.0 and that
mixed-currency portfolios are auto-FX-converted, so it doesn't
manually rescale or refuse to mix US + Canadian listings.
- portfolio-backtest.ts: surface ticker_currencies, fx_converted, and
annualization_periods_per_year in metadata for downstream callers.
| assetClass: z.enum(["stock", "etf", "crypto", "bond", "cash"]).optional(), | ||
| }), | ||
| ) | ||
| .min(1) |
| }), | ||
| ) | ||
| .min(1) | ||
| .describe("Holdings in the portfolio with their target weights."), |
| setTimeout(() => { | ||
| if (r) r.reset() | ||
| }, 100) |
- portfolio-backtest.ts: enforce no duplicate tickers in `holdings` (case-folded). The Python side built weights via dict comprehension (last-write-wins), so duplicates would silently change the allocation and make the TS-side sum-to-1 check disagree with what actually ran. Force callers to merge duplicates explicitly. - portfolio-backtest.ts: cap holdings at 50 entries. Prevents pathological calls (hundreds of tickers) from triggering large yfinance fan-out plus per-ticker currency detection that would blow past the 120s tool timeout. - home.tsx: drop the 100ms setTimeout fallback that called r.reset() after r.submit(). Prompt.submit() already clears input + schedules a navigate-to-session ~50ms later, so the follow-up reset raced the unmount and touched a destroyed input ref.
| { | ||
| holdings: params.holdings.map((h) => ({ ticker: h.ticker, weight: h.weight })), | ||
| capital: params.capital, |
| def detect_currency(t): | ||
| try: | ||
| fi = yf.Ticker(t).fast_info | ||
| ccy = getattr(fi, "currency", None) | ||
| if not ccy and hasattr(fi, "get"): |
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
|
@copilot apply changes based on the comments in this thread |
Implemented the requested thread fixes in commit |
Fixes all 17 Copilot comments: Telemetry opt-out (polarline-markets#1, polarline-markets#2, polarline-markets#3, polarline-markets#9, polarline-markets#16): - tracker.ts now reads FINNY_TELEMETRY=0 / OPENCODE_TELEMETRY=0 at module load, so the opt-out applies in every entrypoint (TUI worker, server, CLI), not just the bootstrap path. - Email dialog auto-prompt and /subscribe slash command also gated on Analytics.isEnabled() — email POST goes to the same Convex deployment. Tracker correctness (polarline-markets#5, polarline-markets#14, polarline-markets#17): - drain() now also waits for the DeviceProfile.userId() resolution promise, not just the post-send promise. - worker rpc.shutdown() and main-thread thread.ts both call Analytics.drain() before tearing down — neither beforeExit nor SIGTERM fire on worker.terminate() / process.exit(0). - beforeExit handler runs at most once per process, preventing an infinite drain loop when a hung telemetry request later resolves and re-empties the loop. Privacy (polarline-markets#10, polarline-markets#11, polarline-markets#12): - Drop process.argv from tui.worker.booted (could include --prompt text and project paths). - error.surfaced now sends only error.name; error messages frequently embed user prompt content and local file paths. - Don't persist the submitted email address to local KV (no reader, just unnecessary PII retention). Email dialog state machine (polarline-markets#4, polarline-markets#6, polarline-markets#8): - Wait for kv.ready before evaluating the prompt gate so we don't re-show the dialog to users who already submitted/skipped. - Conditional dismiss handler — only marks "skipped" when no terminal status has been set, so a successful submit isn't overwritten by the dismiss callback that fires on dialog.clear() and isn't suppressed by another dialog replacing this one. Server-side validation (polarline-markets#15): - subscribe mutation now rejects empty / oversized / regex-failing emails with a ConvexError, so the public Convex client can't bypass the TUI regex. Command coverage (polarline-markets#13): - Hook Analytics.track() in DialogCommand.trigger() instead of the bus event handler. trigger() is the central activation point for palette, slash, keybind, plugin, and bus paths — single hook, full coverage, no double-counting. Comment wording (polarline-markets#7): - bootstrap.ts: "opt-in by default" → "enabled by default" (correct description of opt-out semantics). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Adds a hidden, click-to-discover Portfolio Builder flow: clicking the FINNY wordmark in the sidebar opens a structured form (funds / currency / account / horizon / risk / asset universe / geography). Submitting composes a prompt and auto-submits it to a new sandboxed
portfolio_builderagent that produces a diversified, TFSA-aware investment plan — recommendation only, never executes trades.portfolio_builderagent (hidden: true,mode: primary, edit/write/patch denied). Acts as a "Portfolio Architect" — ETF-first defaults, allocation tables by risk × horizon, mandated "not financial advice" disclaimer top + bottom.portfoliobacktesttool — yfinance-backed weighted-holdings backtest with configurable rebalance cadence (none/monthly/quarterly/yearly).portfolio-builderwith segmented controls; auto-submits via a newautoSubmitflag onHomeRoute.mode === "subagent"so the hidden agent doesn't leak into the dropdown.algorithmIdroute param.Locale.titlecaseconverts underscores to spaces (portfolio_builder->Portfolio Builder).Test plan
portfolio_builderdoes NOT appear in the agent picker dropdownportfoliobacktestruns end-to-end (yfinance install path, weighted holdings, monthly rebalance)