
Finance Guru
Plugin自托管的家族办公室理财系统:11 个专家代理调用经过测试的 Python 计算器算风险指标、蒙特卡洛与回测,券商 CSV 数据存在本机 SQLite,买入前有护栏拦截,数据源以美股为主。需 Python 3.12+、uv 和一定命令行基础;仅供学习,不构成投资建议,需专业人员复核。
Finance Guru
Your brokerage account is not a spreadsheet problem. It is an operating system problem.
A self-hosted family office engine: typed Python calculators, a private SQLite ledger, and specialist agents that run inside Claude Code or Codex. Your data never leaves your machine unless you point it somewhere.

Quick Start · How it works · What's free · Docs · For agents
One command, a full risk profile against live end-of-day data. No portfolio data required. Market analysis works from a fresh clone.
uv run python -m src.analysis.risk_metrics_cli TSLA --days 252 --benchmark SPY
The split
You paste a screenshot into a chat model and ask whether a position is too big. The answer is plausible and unchecked. Chat models are excellent at deciding what question to ask and terrible at being the calculator. So split the job.
Agents propose. Typed code computes.
Guardrails fail closed, in Python, with tests.
A self-hosted family office for $0.
This is for a household that wants its books on its own machine: what you hold, the risk in it, and a check that refuses to guess when a number is missing. The software in this repository is free to clone and run. You bring a terminal, your own Claude Code or Codex session if you want the agents, and broker CSV exports you already have.
Not financial advice, and this project makes no return claims.
Every number an agent quotes comes from a Pydantic-validated calculator with a CLI you can run yourself. Every irreversible action passes through a guardrail that blocks when its inputs are missing rather than guessing. The AI gets judgment. The math gets a test suite.
If a model can lie about it, a calculator owns it.
Quick start
Prerequisites
Python 3.12 or later, uv, and Git. Bun runs agent session hooks, repository PR gates, and the SimpleFIN sync app. The Python calculators run from a shell without Bun.
Install
git clone https://github.com/AojdevStudio/Finance-Guru.git
cd Finance-Guru
uv run python -m src.cli.instance_init ~/finance-guru-data --repo .
The instance is a small uv project outside the repo that depends on the engine. Private data lives there and nowhere else.
Run
cd ~/finance-guru-data
uv run python -m src.integrations.refresh_all --show
uv run python -m src.analysis.risk_metrics_cli TSLA --days 252 --benchmark SPY
The first command prints your position, transaction, and expense tables (empty on a new instance). Drop broker CSV exports into imports/ to work CSV-first, or wire up live sync later.
Install as a Claude Code plugin
claude plugin marketplace add AojdevStudio/Finance-Guru
claude plugin install finance-guru@finance-guru
Then run the instance-onboarding skill. It scaffolds the instance with --plugin, so the plugin is the single source of agents and skills and the checkout path's symlinks are skipped. The checkout path above remains the fully supported one.
What is in the box
Finance Guru is the open-core engine behind Keepfolio, a "claude-code for personal finance." This repo is the free, self-hosted, CLI-native experience: the whole engine, every skill, every agent, no withheld tier.
| Component | What it does | Why it matters |
|---|---|---|
Typed calculators (src/) | 20 CLIs for risk, momentum, volatility, correlation, optimization, backtesting, options, factors, hedging, total return, and margin metrics. Every one is Pydantic input, calculator class, CLI wrapper. | Calculations are testable outside any AI session. The suite is 1,100+ tests behind an 80% coverage gate. |
| Private instance | A directory outside the repo holding family_office.db, your .env, broker CSVs, and every artifact the engine writes. | No spreadsheet, no cloud sync, no vendor dashboard between you and your ledger. Tracked files never carry personal values. |
Sync layer (src/integrations/) | refresh_all pulls SnapTrade (brokerage) and SimpleFIN (bank and card) into SQLite with your own read-only credentials. | Partial provider responses raise before any write. You get an error instead of a coverage ratio computed on half your accounts. |
| Fail-closed guardrails | Concentration cap, margin coverage, and ITC risk run against trusted inputs before a buy ticket persists. | A block on missing NAV, missing rate, or an unrun Layer 3 score. A bad ticket needs a number to pass, not a prompt to agree. |
Skills and specialists (.claude/) | Skills and 11 specialist agents coordinated by a finance orchestrator. They read the DB, run the CLIs, and write Markdown into your instance. | Every output carries its data source, date stamp, and the educational-only disclaimer. You can trace any claim back to a CLI run. |
| Compliance scan on push | A pre-push hook scans history and the diff for secrets and PII. | The repo is public. Your data is not. The hook is what keeps that true. |

How it works
The guardrail loop
The buy-ticket pipeline is the clearest example of the split between judgment and arithmetic.

The model drafts a proposal. It has no say over the inputs that judge it. GuardrailContext carries the pre-borrow equity NAV, the configured annual margin rate, and the Layer 3 ITC score, and the checks run against those:
CONCENTRATION_LIMIT = 0.30 # of pre-borrow equity NAV, never of a margin-inflated total
MIN_MARGIN_COVERAGE = 2.0 # dividend income over projected interest, new borrowing included
MAX_ITC_RISK = 0.7 # from Layer 3 output only; missing, not-run, or failed blocks
A block returns a typed reason (equity_nav_unavailable, margin_rate_unavailable, coverage<2x) and writes nothing. A pass persists the draft under a stable run id, then notifies. A failed notification is its own outcome, so a retry reuses the draft instead of writing a second one.
The three-layer pattern
src/analysis/risk_metrics.py Pydantic input model + RiskCalculator
src/analysis/risk_metrics_cli.py argparse wrapper, --output json, disclaimer
tests/python/test_risk_metrics.py the math, tested without a network
Every tool in the engine follows this shape, so an agent can only ever call a CLI and quote its output. Nineteen of the twenty CLIs take --output json; margin metrics prints JSON by default. That is the contract the skills consume, so what an agent reports is exactly what the calculator returned. See the CLI reference for all 20.
uv run python -m src.analysis.risk_metrics_cli TSLA --days 252 --benchmark SPY --output json
The private instance
The engine reads every private file from an instance directory outside the repository, resolved from FIN_GURU_DATA_ROOT or the current working directory. The instance holds .env, user-profile.yaml, config.yaml, family_office.db, snaptrade-accounts.yaml, and the working directories imports/, analysis/, tickets/, strategies/, hedging/, reports/, auto-tickets/, and notes/. Tracked files describe behaviour and never carry personal values. The full rule and its enforcement live in DataClassification and PRIVACY.md.
Local-first does not mean network-free. Market data, brokerage, and LLM integrations send request data to their configured providers. Configure only the integrations you intend to use.
Scheduled checks with swamp
swamp (Swamp Club) runs Finance Guru's scheduled checks. The engine computes the numbers. swamp runs checks on a timer, compares those numbers with outside sources, and keeps a record of every run. Everything lives in this repository under automations/swamp/, and swamp's own service runs the schedule, so no other tool is needed.
Words used below:
- A behavior is a small TypeScript program with named methods.
fidelity-margin-rateis one. - A workflow is a YAML file that runs behavior methods in order.
margin-rate-checkis one. swamp serveis swamp's long-running process. It fires every workflow that has atrigger.schedule.
The margin-rate check. Fidelity charges a margin rate that depends on the size of your debt. The margin-rate-check workflow catches a rate in your .env that no longer matches:
refreshruns the engine's SnapTrade positions sync in your instance, so the margin debt infamily_office.dbis current.checkasks the engine'smargin_metrics_clifor your margin debt and configured rate (FG_MARGIN_INTEREST_RATE_DECIMAL), reads Fidelity's published rate table, and compares the rate for that debt with yours. A mismatch fails the run. The check never edits your.env.
It runs Mondays at 9:15 in the machine's local time zone. On a machine set to US Central time, that is after SnapTrade's daily holdings sync, about 8:45 AM CT.
What you need
- A Finance Guru checkout and an instance with a Fidelity margin account routed as
taxable_margininsnaptrade-accounts.yaml. FG_MARGIN_INTEREST_RATE_DECIMALandFG_MARGIN_JUMP_ALERT_THRESHOLDset in the instance.env. The engine'smargin_metrics_clineeds both.uvon the machine.- The swamp CLI, installed as its README describes, and signed in with
swamp auth login. Every swamp process, the service included, needs that sign-in to start.
Configure the check
Create the behavior definition once. It records your instance path and the full path to uv, so it stays on your machine: automations/swamp/.gitignore ignores models/.
cd automations/swamp
swamp behavior create @aojdevstudio/fidelity-margin-rate fidelity-margin-rate \
--global-arg instanceDir=/path/to/your/instance \
--global-arg uvPath="$(command -v uv)"
swamp workflow validate margin-rate-check
The service starts with a minimal PATH and without your shell's variables, so give full paths here, not FIN_GURU_DATA_ROOT.
Run it by hand
cd automations/swamp
swamp workflow run margin-rate-check --json
swamp data query 'behavior("fidelity-margin-rate") && name == "rate"' --select content --json
The last command prints the newest comparison: tier rate, configured rate, margin debt, and drift. To check the rate without syncing first, run swamp behavior run fidelity-margin-rate check. It refuses a ledger synced more than 24 hours ago.
Run the tests with the Deno that ships with swamp (swamp doctor extensions --json prints its path as denoPath):
~/.swamp/deno/deno test --allow-read extensions/behaviors/
Start the service
swamp installs swamp serve as a per-user service: a launchd agent on macOS, a systemd user unit on Linux. The command is marked experimental in swamp's help.
cd automations/swamp
swamp serve daemon enable --user --repo-dir "$PWD" --host 127.0.0.1 --port 9093
swamp serve daemon status
curl -s http://127.0.0.1:9093/health
/health lists each schedule with its nextRun in UTC. Check that the margin-rate and hedge-trigger checks appear there. Stop the service with swamp serve daemon disable.
- The service loads the behavior code once, at start. After you pull changes under
automations/swamp/extensions/, run thedaemon enablecommand again to restart it. Until then, scheduled runs use the old code. Workflow and schedule edits take effect without a restart. - swamp installs one serve service per user, so
daemon enablehere replaces a serve service you already run for another repository. The check needs this layout: the workflow, the behavior, and your local definition all inautomations/swamp/inside a Finance Guru checkout, because the behavior finds the engine two folders up. - On Linux, a user unit stops when you log out unless lingering is on:
loginctl enable-linger "$USER". - A schedule missed while the machine was asleep or off does not run later. Run the workflow by hand when that happens.
Where results and logs go
- Run history:
swamp workflow history search --json. A scheduled run shows"triggerSource": "schedule". - The latest comparison: the
swamp data querycommand above. - Why a run failed:
swamp report get @swamp/workflow-summary --workflow margin-rate-check --json. - Service logs:
~/Library/Logs/swamp/serve.stdout.logandserve.stderr.logon macOS,journalctl --user -u swamp-serveon Linux. - Run data lives in
automations/swamp/.swamp/, which git ignores.
A failed run notifies no one. Check the history, or point a tool you already use at it.
How it relates to the stale-equity guard. The engine computes margin debt as gross market value minus SnapTrade's account equity, and the equity is only as fresh as SnapTrade's last holdings sync (#259). The engine refuses equity over 12 hours old with StaleAccountEquityError, and the ledger stores an empty margin debt instead of a wrong one (#260). The rate check reads the debt through the engine, so it fails on an empty debt too, and it refuses a ledger synced more than 24 hours ago. It reads that time from ledger_synced_at in the engine's output. Stale data never picks a rate tier. The engine guard stops wrong numbers before they exist. The swamp check catches settings that have drifted from the broker.
The hedge-trigger check. The hedge-trigger-check workflow suggests when to start or exit a triggered inverse-ETF hedge. It suggests only. It never trades or moves money. It runs weekdays at 16:30 in the machine's local time zone, which on a US Central machine is after the US close and after SnapTrade's morning sync.
refreshruns the same SnapTrade positions sync as the margin-rate check. If the sync fails, the check still runs and reports the stale input.activityruns the SnapTrade activities sync, so a held hedge's entry date comes from current history. Activity that does not add up to the held shares givesNO_VERDICT.checkrunssrc.analysis.hedge_trigger_cli --output json. The engine reads your thresholds from thehedge_triggers:section ofuser-profile.yaml, margin numbers from the ledger, your hedge position and its entry date from the ledger, and daily closes from yfinance. It returns one action:STARTwith a size,HOLD,EXITwith the rules that fired, orNO_VERDICTnaming the input that was stale or missing.
Holdings/debt in these rules is gross holdings (account equity plus margin debt) divided by margin debt. margin_metrics_cli reports equity/debt as portfolio_margin_ratio, which is a different number.
The check writes every suggestion as a versioned record. It fails the run when the suggestion is START or EXIT, or differs from the last one, so those days show as red runs, like a margin-rate drift. A missing hedge_triggers: section fails the run with no record. Every key is required, and the engine has no defaults for them:
hedge_triggers:
hedge_symbol: "SQQQ"
index_symbol: "QQQ"
volatility_symbol: "^VIX"
moving_average_days: 50
start_ratio_below: 3.0 # holdings/debt
start_drawdown_at_least: 0.10 # below the 52-week high, and below the average
start_volatility_at_least: 25
exit_gain_at_least: 0.30 # alone, this exits half
exit_within_high: 0.05
exit_closes_above_average: 3
exit_ratio_above: 3.5
exit_after_days: 30
max_size_of_holdings: 0.06
Create its behavior definition, then run it and read the newest suggestion:
cd automations/swamp
swamp behavior create @aojdevstudio/hedge-trigger hedge-trigger \
--global-arg instanceDir=/path/to/your/instance \
--global-arg uvPath="$(command -v uv)"
swamp workflow validate hedge-trigger-check
swamp workflow run hedge-trigger-check --json
swamp data query 'behavior("hedge-trigger") && name == "hedge"' --select content --json
The workflow's refresh step uses the fidelity-margin-rate definition, so create that one too.
If you are an agent
You are the intended operator of this engine, not an afterthought. A few things that make you effective here:
- Read your instance's
AGENTS.mdfirst. It points to the canonical finance context and skill tree. Codex discovers those skills through the instance's.agentssymlink. Repository developer instructions stay in the engine checkout. - Run
datebefore any market work. Every specialist here is expected to know the current date before it searches or analyzes. - Never do the arithmetic yourself. Call the CLI with
--output jsonand quote what it returned. That is the whole reason the calculators exist. - Private data lives in the instance, not the repo. Resolve
FIN_GURU_DATA_ROOTor the working directory, read fromfamily_office.db, and write artifacts intoanalysis/ortickets/. Tracked files never carry personal values, and the pre-push scan will stop you if you try. - Every financial output carries the educational-only disclaimer, a date stamp, and its data source. The CLIs print it; the skills expect it.
- Fail closed. If a guardrail input is missing, the answer is a block with a typed reason. Do not fill the gap with an estimate.
- Contributing a tool means all three layers. Pydantic input model, calculator class, CLI wrapper, plus a test that runs without a network.
Skills in .claude/skills/ are the workflows; specialists in .claude/agents/ are the subagents; the finance orchestrator is the main session and routes between them.
Why this exists
Finance Guru started as one operator's answer to a personal constraint. Its author spent over a decade in pharmacy operations before teaching himself to build software, and along the way stopped using a checking account at all. Everything ran through a brokerage: paychecks in, margin as operating capital, dividends as the second income layer. No consumer finance app models that. They all assume a bank.
The stopgap was a chat model and a habit of pasting screenshots into it. Every answer was plausible. None of it was checked. The model did the arithmetic in its head, the positions lived in a CSV exported three weeks earlier, and the guardrail that should have stopped a bad ticket was a sentence in a prompt, not a line of code. Nothing was repeatable, so nothing was auditable.
"A fully autonomous, unbiased family office with agentic personalities grounded in math and truth, helping me achieve financial freedom." The vision statement in docs/VISION.md, March 2026.
The first commits were agent personas and prompts. Persuasive, and unverifiable. The fix was not a better prompt. It was moving every calculation into typed Python with a CLI, so the agent's only move is to run the tool and read the answer. That split, judgment in the agent and arithmetic in code, is the whole architecture.
The second lesson came from sync. SimpleFIN can return HTTP 200 with a dropped account buried in an errors array, and the sync used to count that and move on. Now the rule is that anything financial fails loud or fails closed. Missing data blocks. Partial data raises. A guardrail without its inputs is a block, not a pass.
The repo is public because the pattern is more useful than the portfolio. The commercial macOS product, Keepfolio, is built on this engine. The engine stays free and complete.
The artifacts are the argument.
Roadmap
- Three-layer calculators for risk, momentum, volatility, correlation, optimization, backtesting, options, factors, hedging, and margin
- Local SQLite system of record fed by SnapTrade and SimpleFIN
- Fail-closed buy-ticket guardrails with Layer 3 ITC authority
- Diátaxis documentation site on GitHub Pages
- Claude Code plugin as the primary install path (#131)
- Retirement-account sync migration gate (#74)
- Automated releases through release-please (#112)
Open items carry the roadmap label. Defects carry bug.
Recent changes are in the changelog.
Contributing
Read Contributing first. It covers the accepted surfaces, the quality gates, and the privacy rules every push must pass. The required Python gates mirror CI:
uv sync --dev
uv run ruff format --check .
uv run ruff check .
uv run mypy src/
uv run pytest -m "not integration"
Documentation
| Document | Purpose |
|---|---|
| Documentation site | Tutorials, how-to guides, reference, and explanation |
| Setup | Install the engine and create an instance |
| CLI reference | Commands, arguments, and output |
| Live sync credentials | Bring-your-own-credentials setup for SnapTrade and SimpleFIN |
| Runbooks | Recurring portfolio and operations workflows |
| Troubleshooting | Common installation and runtime failures |
Acknowledgments
Market data through yfinance. Brokerage connectivity through SnapTrade. Bank and card connectivity through SimpleFIN. Agent surfaces on Claude Code and Codex. Diagrams drawn with the diagram-design skill; terminal recording with vhs.
What's free / licensing
Everything tracked in this repository is free under the GNU Affero General Public License v3.0, or, at your option, any later version. That covers the Python calculators, the ledger code, the skills, the specialist agents, the docs, and the apps. There is no paid tier here, and no feature of this engine is held back. You can run it, change it, and share it. If you run a modified version as a network service, the license requires you to offer that version's source to the people who use it.
Keepfolio is a separate commercial macOS product built on this engine. Its source is not in this repository, and this repository does not state Keepfolio's license. This repo is the free terminal-native engine. Keepfolio is the polished app for someone who will not run one.
The copyright notice and the same split are in LICENSING.md.
License
Finance Guru is licensed under the GNU Affero General Public License v3.0, or any later version. See LICENSING.md.
Financial disclaimer
Not financial advice, and this project makes no return claims. Finance Guru is educational software. Financial markets involve risk, including possible loss of principal. Verify all data and calculations independently and consult appropriately licensed financial, tax, and legal professionals before acting.
Agents propose. Typed code computes.
If the split between judgment and arithmetic is the thing you were missing, star the repo.
相关资源

Finance Skills
Plugin面向投研的插件市场:6 组插件覆盖 yfinance 行情、财报前瞻与复盘、DCF 估值、期权收益图、ETF 溢价,以及 X、Discord 等社媒资讯的只读抓取和 TradingView 数据。仅供研究,不构成投资建议。
himself65/finance-skills3.6k
hithink-finance CLI(同花顺金融数据)
CLI同花顺官方金融数据命令行:查询 A 股行情、财务报表、估值、公募基金与期货期权数据,可把全市场历史行情同步到本地 DuckDB 用 SQL 分析。需要 Node.js 22+ 和在同花顺金融数据服务官网申请的 API Key;数据仅供研究,投资决策需专业人员复核。
HiThink-Tech/Financial-API4.6k
Finance Skills
Skill面向投资研究的金融技能合集:基于 yfinance 取行情与财报,做 DCF 估值、财报前瞻与复盘、期权收益图、相关性与流动性分析,另含 Twitter、Discord 等只读信息源。仅供研究参考。
himself65/finance-skills3.6k
Longbridge Skills
Plugin长桥证券官方技能插件:用中文或英文提问,即可查询港美 A 股与新加坡市场的行情、技术面与衍生品、财报与估值、分析师评级、自选股和个人持仓,并生成财报复盘与晨间简报。需要长桥账号并安装长桥命令行或接入长桥 MCP;输出不构成投资建议,需专业人员复核。
longbridge/skills73
TradingAgents
CLI多智能体投研框架:基本面、情绪、新闻、技术分析师与多空研究员、交易员、风控分工辩论,对指定股票输出研报与评级,支持美股、港股与 A 股。需 Python 环境和任一大模型 API Key;不构成投资建议,结论需专业人员复核。
TauricResearch/TradingAgents124k
AI Hedge Fund
CLI模拟对冲基金的多 Agent 系统:巴菲特、芒格等投资风格 Agent 与量化、风控模块共同分析个股并可回测,适合金融课堂演示与学习投资框架。首次运行时填入 Financial Datasets 与模型 API Key;不做真实交易,结论需专业人员复核。
virattt/ai-hedge-fund64.8k