MyFinanceMCP
Sends personalised daily portfolio briefings with per-stock signals and LLM-written summaries to users via WhatsApp.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
MyFinanceMCP — Angel One Portfolio Tracker
A multi-user MCP server and web dashboard for tracking your Angel One portfolio, with AI-powered daily briefings, a trading agent, and calibrated ML price predictions.
Features
MCP Server (SSE transport) — connect from Cursor, Claude Desktop, or any MCP-compatible client
Web Dashboard — browser-based portfolio viewer with login, holdings, positions, orders, and P&L pages
Finance ADK Agent — chat with the Google ADK finance assistant (Angel One + research tools) via the Agent tab. Requires
OPENROUTER_API_KEYon the serverTrading ADK Agent — risk-aware, proposal-based order execution agent. Analyses prices and technicals; proposes trades but never places orders without explicit approval
Daily Briefing Scheduler — automatically sends a WhatsApp message each day with per-stock signals (green/yellow/red), LightGBM predictions, and an LLM-written summary of your portfolio
ML Price Prediction — gradient-boosted direction models over 1 day, 1 week and 1 month, trained on daily bars with purged walk-forward validation and isotonic calibration. Features span technicals, cross-sectional ranks, market and industry context, delivery and turnover flow, point-in-time fundamentals and FinBERT news sentiment. Every prediction states which engine produced it; when no model is registered the response is labelled a rule-based score, not a model output
Local market store — the whole NSE cash market, one call per trading day from the exchange bhavcopy, kept as Parquet (
services/marketstore). Carries delivery percentage, which the broker candle API does not exposePeer-relative research — valuation and quality percentiles against NSE industry peers, analyst estimate revision momentum, and ownership/flow signals
Mandate compliance gate — proposed trades are checked against a dated, versioned ruleset and blocked with the specific rule cited; every decision, including blocked ones, lands in an append-only decision record
Admin API — REST endpoints (
/api/admin/*) for registering premium users with Fernet-encrypted Angel credentials and managing their schedulesMulti-user — each session authenticates with its own Angel One credentials; premium users' credentials are stored encrypted in Postgres
Zero plaintext credential storage — transient sessions live only in RAM; premium user credentials are encrypted at rest with a Fernet key
Related MCP server: Angel One Mcp
Project Structure
├── main.py # Combined entry point (MCP + Web on one port)
├── mcp_server.py # MCP FastMCP app (tools: login, portfolio, trading)
├── web_app.py # FastAPI web dashboard + briefing schedule API
├── angel_client.py # Angel One SmartAPI client wrapper
├── session_manager.py # Per-session client management (in-memory)
│
├── db/ # Postgres layer (SQLModel + Neon)
│ ├── engine.py # Engine, init_db, additive column migrations
│ ├── models.py # User, Schedule, Log tables
│ ├── crypto.py # Fernet encrypt/decrypt for stored credentials
│ └── __init__.py
│
├── adminApi/ # Admin REST API (X-Admin-Key protected)
│ ├── router.py # /api/admin/users, /api/admin/schedules, /api/admin/logs
│ └── __init__.py
│
├── agents/ # Google ADK agents
│ ├── factory.py # LlmAgent builder (OpenRouter via LiteLLM)
│ ├── finance/ # Finance research agent
│ └── trading/ # Proposal-based trading agent
│
├── services/ # Domain logic
│ ├── schedular/ # Scheduler pipeline
│ │ ├── runner.py # APScheduler tick (every 1 min)
│ │ ├── repository.py # DB claim / finish (FOR UPDATE SKIP LOCKED)
│ │ ├── job_executor.py # Per-schedule pipeline (session → briefing → WhatsApp)
│ │ ├── daily_briefing.py # LLM briefing generation (holdings + candles + model)
│ │ └── whatsapp.py # WhatsApp delivery via webhook
│ ├── marketstore/ # Local NSE history + point-in-time store
│ │ ├── bhavcopy.py # One day of the whole market, normalised
│ │ ├── store.py # Parquet, partitioned by year, idempotent
│ │ ├── backfill.py # Resumable CLI backfill
│ │ ├── universe.py # 451 names with cap band and NSE industry
│ │ └── pit.py # Point-in-time fundamental snapshots
│ ├── features/ # The versioned feature contract
│ │ ├── contract.py # Ordered feature list + interval guards
│ │ ├── technical.py # Indicators, vectorised across the panel
│ │ ├── cross_sectional.py # Ranks within universe and industry
│ │ ├── market_context.py # Market and industry context
│ │ ├── flow.py # Delivery % and turnover
│ │ ├── fundamental.py # Scores read through the PIT store
│ │ └── sentiment.py # FinBERT aggregates from the news archive
│ ├── compliance/ # Mandate gate over a dated ruleset
│ ├── prediction_service.py # Registry-backed, interval-strict predictions
│ ├── decision_record.py # Append-only audit trail for trades
│ ├── peer_service.py # Valuation percentiles vs industry peers
│ ├── estimates_service.py # Consensus, revision momentum, surprises
│ ├── ownership_service.py # Delivery, deals, insiders (pluggable source)
│ ├── ai_service.py # OpenRouter AI helpers
│ ├── technical_service.py # RSI, MACD, Bollinger, SMA, volume signals
│ ├── fundamental_service.py # Fundamental data
│ ├── sentiment_service.py # News sentiment scoring
│ ├── sector_service.py # Sectoral analysis
│ ├── news_service.py # News fetching
│ ├── risk_profile.py # User risk profile
│ ├── trade_proposals.py # Proposal store + risk and compliance gates
│ └── realtime_feed.py # Real-time price feed
│
├── integrations/ # Adapters bridging sessions ↔ MCP / local accounts
├── models/ # Labelling, validation, registry, training
│ ├── labeling.py # Triple barriers, CUSUM events, weights
│ ├── validation.py # Purged walk-forward CV and metrics
│ ├── registry.py # Model + contract + metrics, versioned
│ ├── train.py # The training CLI
│ └── artifacts/ # Trained models and their reports
├── frontend/ # Jinja2 templates and static assets (CSS, JS)
├── data/ # JSON data files served under /static/data
│ ├── compliance_rules.json # Mandate ruleset (TEMPLATE — see the file)
│ ├── market/ # Parquet daily bars
│ └── pit/ # Point-in-time snapshots
├── requirements.txt # Python dependencies
├── Dockerfile # Container definition
└── .env.example # Environment variable templateArchitecture
One process (main.py) mounts the MCP app under /mcp and the FastAPI web app at / on a single Uvicorn port. The scheduler runs inside the same process (APScheduler async) when SCHEDULER_ENABLED=1.
flowchart TB
subgraph clients [Clients]
Browser[Web browser]
MCPClient[MCP client e.g. Cursor]
WhatsApp[WhatsApp ← user's phone]
end
subgraph server [MyFinanceMCP process]
Starlette[Starlette / Uvicorn]
Web[FastAPI web_app]
MCP[mcp_server FastMCP SSE]
Admin[adminApi router]
SM[session_manager in-memory]
FinanceADK[Finance ADK agent]
TradingADK[Trading ADK agent]
Scheduler[APScheduler tick 1 min]
AngelWrap[angel_client AngelOneClient]
end
subgraph db [Postgres / Neon]
Users[users encrypted creds]
Schedules[schedules next_run status]
Logs[logs run history]
end
subgraph external [External services]
AngelAPI[Angel One SmartAPI]
OR[OpenRouter API]
WAHook[WhatsApp webhook service]
Other[yfinance gnews NSE data etc.]
end
Browser -->|HTTPS session cookie| Starlette
MCPClient -->|Streamable HTTP /mcp/mcp + Bearer token| Starlette
Starlette --> Web
Starlette --> MCP
Web --> Admin
Web --> SM
Web --> FinanceADK
Web --> TradingADK
MCP --> SM
SM --> AngelWrap
AngelWrap --> AngelAPI
FinanceADK --> OR
TradingADK --> OR
Web --> Other
Admin --> db
Scheduler --> db
Scheduler -->|run_one| AngelWrap
Scheduler -->|send| WAHook
WAHook --> WhatsAppRequest paths
Path | Purpose |
| Jinja pages + static assets |
| JSON for dashboard, news, research, |
| MCP over SSE ( |
| Swagger UI (FastAPI auto-generated) |
Session flows
Registration: a WhatsApp number and app password create a
usersrow withbrokerage_status = not_connectedand every Angel One column NULL. Learning is open from there. Angel One credentials can be supplied at the same time, or later throughPOST /api/brokerage/register.Web login: WhatsApp number + app password → the server verifies the scrypt hash and writes
uid/uvto a signed session cookie. No broker call. Login works whether or not a broker is connected, and whether or not Angel One is up.Brokerage access: every endpoint that reads the Angel One account depends on
require_brokerage(web/dependencies.py). It answers 401 when signed out, 403brokerage_not_connected/brokerage_reauth_requiredwhen there is no usable link, and 503brokerage_unavailablewhen Angel One cannot be reached. Otherwise it builds theAngelOneClientfrom the encrypted credentials and records itssidin the cookie. If Angel One rejects stored credentials, the link becomesexpiredand the user reconnects.Daily briefing: Scheduler ticks every minute → queries
schedulesfor rows wherenext_run <= now()→ claims them withFOR UPDATE SKIP LOCKED→ for each claimed schedule: skips users whose broker is notconnected, decrypts credentials fromusers, creates an ephemeral Angel session, generates the briefing, sends WhatsApp, writes tologs, and armsnext_run.MCP: Read-only. Each request carries
Authorization: Bearer <token>: either an OAuth 2.1 access token (claude.ai custom connectors and other OAuth clients; PKCE S256, Dynamic Client Registration, consent at/oauth/consent, tokens hashed and bound to the/mcp/mcpresource) or a personal access token created on/connect. The user is derived from the verified token and their broker session is rebuilt from their encrypted stored credentials; no credentials pass through tools.
Getting Your Angel One API Credentials
You need 4 credentials from the Angel One SmartAPI portal:
https://smartapi.angelbroking.com/signin
Credential | How to get it |
API Key | SmartAPI → My Apps → Create App → copy the API Key |
Client ID | Your Angel One account ID (e.g. |
PIN | The 4-digit trading PIN you use to log into Angel One |
TOTP Secret | SmartAPI → My Profile → Enable TOTP → copy the Base32 secret key |
Note: The TOTP secret is only shown once when you enable it. Save it immediately.
Run Locally
1. Create a virtual environment
python3 -m venv .venv
source .venv/bin/activate # macOS / Linux
# .venv\Scripts\activate # Windows2. Install dependencies
pip install -r requirements.txt3. Set up Postgres
The scheduler and admin API require a Postgres database. The easiest option for development is a free Neon database. The schema is created and migrated automatically on startup by init_db() (see Database migrations).
Database migrations
The schema is managed by Alembic (alembic.ini, migrations/versions/). On every start, init_db() brings the database to the head revision inside one transaction, under a Postgres advisory lock:
Database state | What happens |
Empty | Tables created from the models, stamped at head |
Created before Alembic (no | The old additive ALTERs run, the database is stamped at |
Already versioned | Upgraded to head (a no-op when current) |
At a revision this release does not know (e.g. the | Startup refuses, with nothing changed |
In production a migration failure stops the app from starting. A schema the code does not match would break every request. Set DB_AUTO_MIGRATE=0 to run migrations yourself instead (alembic upgrade head; alembic current shows where a database is).
Deploying the optional-brokerage release (20261109_02_broker_nullable, 20261109_03_brokerage_status):
Back up the database first (a Neon branch or snapshot).
Check that production has never been migrated by another branch:
SELECT version_num FROM alembic_version;must fail (no table) or return a20261109_*revision. If it returns0001_baseline…0003_broker_connections, stop: that is thestaginghistory, and the two need reconciling first.Deploy the backend. The startup log shows
init_db: stamped 20261109_01_baseline and upgraded to head.Verify:
SELECT brokerage_status, count(*) FROM users GROUP BY 1;. Every row with all four Angel One credentials isconnected; the rest arenot_connected. Existing IDs, password hashes and credentials are untouched.Then deploy the React app. It expects the new session shape, with a nullable
client_id.
Rolling back the code is safe while every user still has broker credentials. Once phone-only users exist, alembic downgrade 20261109_01_baseline refuses rather than delete them.
Migration tests: python tests/test_migrations.py. They run on SQLite always, and on Postgres too when MIGRATION_TEST_PG_URL points at a server where they may create and drop a throwaway database.
4. Configure environment variables
cp .env.example .envEdit .env with your values:
Variable | Required | Description |
| For ADK CLI only | Bootstrap credentials for local ADK agent testing |
| For ADK CLI only | See above |
| For ADK CLI only | See above |
| For ADK CLI only | See above |
| Yes (for Agent/Trading/Briefing) | Server-side LLM key |
| Yes | Postgres connection string (e.g. Neon pooler URL with |
| Yes | Fernet key for encrypting Angel credentials in DB. Generate with: |
| Yes | Static key protecting all |
| Yes (for briefings) | Set to |
| Recommended | Signs session cookies. Random key generated on each restart if unset (invalidates existing cookies) |
| Recommended | Comma-separated hostnames the app answers to. Unset accepts any |
Note on two OpenRouter keys: The server
OPENROUTER_API_KEYis used by the ADK agents and the daily briefing pipeline. There is a separate optional per-browser OpenRouter key for Dashboard → AI Insights / Ask AI (/api/ai/*) — that is stored only in the browser and never sent to the server's env.
Scaling note: The ADK integration uses in-memory runners in the same process. Use a single Uvicorn worker (the default with python main.py) so chat state and Angel sessions stay consistent.
5. Start the server
python main.pyThe server starts on http://localhost:8000:
Web dashboard:
http://localhost:8000/Swagger UI:
http://localhost:8000/docsMCP endpoint (Streamable HTTP, bearer token):
http://localhost:8000/mcp/mcp
The app runs without a trained model. Predictions then come from a rule-based technical score, and every response and the dashboard label say so.
Training the Prediction Model
1. Build the market store. One HTTP call per trading day pulls the entire NSE cash market, including delivery percentage. Resumable — interrupt it freely.
python -m services.marketstore.backfill --from 2020-01-01The delivery-enriched bhavcopy archive starts around January 2020; earlier dates
return "data not found". Check progress any time with --status.
2. Train. Walk-forward validated, calibrated, and registered with its full contract:
python models/train.pyArtefacts land in models/artifacts/<version>/ with a report.md you should
read before trusting anything. Use --sample for a fast smoke test and
--no-register to evaluate without making a model live.
What to expect. An out-of-sample AUC near 0.54 on daily Indian equities is a real result. A number far above that is almost always a leak rather than an edge, and should be investigated as a bug rather than celebrated. Shorter horizons are weaker: in the first run the 1-day and 1-week models scored ~0.50 (no signal) while 1-month scored 0.55.
On fundamentals and sentiment. Both feature blocks are forward-only. yfinance reports today's restated figures, so historical values cannot be reconstructed without look-ahead bias. Snapshots accumulate from the day capture begins — every fundamentals fetch the app makes writes one. Until the archive is deep enough, those blocks are null, and the training report says so explicitly rather than implying coverage the model did not have.
Mandate Compliance
Proposed trades pass through a hard gate before reaching the broker. Rules live
in data/compliance_rules.json with an effective date and a source per rule, so
a rule change is a data edit and the ruleset in force on a past date can be
reconstructed.
The shipped file is a template. Its limits are placeholders that exist to exercise the engine. Before it governs a real trade, every limit must be read from and cited to the current SEBI master circular, the scheme information document, and the fund's own policy. The loader logs a warning while the template is in use, and every API response carries
is_template: true.
Every decision — executed, blocked or failed — is written to the append-only
decision_records table and readable at GET /api/trading/decisions.
Daily Briefing Scheduler
The scheduler sends a personalised WhatsApp message to each premium user at their configured time each day. The message includes:
Per-stock signals (🟢 / 🟡 / 🔴) with price and % changes
1-day and 1-week direction predictions (model or labelled rule-based score)
An LLM-written portfolio summary via OpenRouter
How to set it up
Create a user via the Admin API (see below).
Set a schedule — log in as that user and go to the Trading tab → Daily Briefing, or call
POST /api/briefing/schedulewith{"time_ist": "08:30"}.Ensure
SCHEDULER_ENABLED=1in your environment and restart.
How it works internally
APScheduler tick (every 1 min)
└── repository.claim_due_schedules() ← SQL: next_run <= now(), FOR UPDATE SKIP LOCKED
└── job_executor.run_one(claim)
├── Load user + decrypt credentials (Fernet)
├── Create ephemeral Angel session
├── generate_daily_briefing() ← holdings + candles + model + LLM
├── whatsapp.send() ← POST to webhook service
├── Write Log row
└── finish_schedule() ← advance next_run by interval_minutesAdmin API
All endpoints require the X-Admin-Key: <your ADMIN_API_KEY> header. Browse to /docs for interactive Swagger UI.
Endpoint | Method | Description |
| GET | List all registered users |
| POST | Create a user (encrypts password + TOTP before storing) |
| GET | Get a single user |
| DELETE | Deactivate a user |
| GET | List all schedules |
| POST | Create a schedule for a user |
| GET | Get a single schedule |
| PATCH | Update schedule (enable/disable, interval, next_run) |
| DELETE | Delete a schedule |
| GET | Recent scheduler run logs (filterable by user_id) |
Example: register a user
curl -X POST http://localhost:8000/api/admin/users \
-H "X-Admin-Key: $ADMIN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"whatsapp_number": "918107037133",
"angel_api_key": "",
"angel_client_id": "",
"angel_password": "",
"angel_totp_secret": ""
}'Connect from an MCP Client
Claude (claude.ai, Desktop, mobile): custom connector
Settings → Connectors → Add custom connector, URL https://agentfolio.in/mcp/mcp (use the apex domain; www redirects). Claude discovers the OAuth server from /.well-known/oauth-protected-resource/mcp/mcp, registers itself, and sends you to a sign-in page (WhatsApp number + app password) to approve read-only portfolio:read access. No token to paste. Connected apps can be disconnected on /connect.
OAuth needs PUBLIC_BASE_URL set to the exact public origin (e.g. https://agentfolio.in): the issuer, the endpoints and the resource that tokens are bound to are all derived from it. Optional: OAUTH_EXTRA_REDIRECT_URIS (comma-separated, exact) to allow other clients' callbacks beyond claude.ai/claude.com and loopback; OAUTH_ALLOW_LOOPBACK_REDIRECTS=0 to refuse http://localhost callbacks.
Cursor
Add to your .cursor/mcp.json:
{
"mcpServers": {
"angelone-portfolio": {
"url": "http://localhost:8000/mcp/mcp"
}
}
}Add an Authorization: Bearer <token> header using a token from the /connect page. See /connect for per-client examples.
Claude Desktop
Add to your claude_desktop_config.json:
{
"mcpServers": {
"angelone-portfolio": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:8000/mcp/mcp"]
}
}
}ChatGPT Desktop
Go to Settings → Beta features → MCP Servers → Add Server and enter:
Command:
npxArguments:
-y mcp-remote http://localhost:8000/mcp/mcp
Available MCP Tools
Tool | Description |
| Account profile |
| Stock holdings with P&L |
| Complete holdings overview |
| Open positions |
| Today's orders |
| Executed trades |
| Account funds / margin |
| Last traded price |
| Search stocks by name |
| High-level portfolio summary |
| Historical OHLC data |
| OHLCV history by symbol |
| P&L for one symbol |
| Best 5 bids/asks |
| Technical-signal outlook (not advice) |
All tools are read-only. There are no order placement, modification, cancellation or login tools.
Deploy to Railway (Recommended)
Push this repo to GitHub
Go to railway.app and create a new project
Connect your GitHub repository
Railway auto-detects the Dockerfile and deploys
Set the following environment variables in Railway:
DATABASE_URL(Postgres connection string)ENCRYPTION_KEYADMIN_API_KEYOPENROUTER_API_KEYSCHEDULER_ENABLED=1SESSION_SECRET
Get your public URL (e.g.
https://myfinancemcp.up.railway.app)
After Deployment
Web users: Visit https://your-app.up.railway.app and log in with Angel One credentials.
MCP users: Update the url in your MCP client config:
{
"mcpServers": {
"angelone-portfolio": {
"url": "https://your-app.up.railway.app/mcp/mcp"
}
}
}Deploy to Render (Free Tier)
Push to GitHub
Go to render.com, create a new Web Service
Connect your repo, select Docker as the runtime
Set all required environment variables (same list as Railway above)
Deploy
Note: Render free tier spins down after inactivity. The scheduler resumes when the service wakes up, but will immediately fire all overdue schedules on the next tick.
Security
What lives where
Location | What is stored | Notes |
Server memory | Transient | Not written to DB; cleared on logout, session expiry (~8 hours), or process restart |
Postgres DB | Premium | Encrypted with Fernet ( |
Server |
| Protect the host and use a secrets manager in production |
Signed session cookie | Opaque | Signed with |
Server memory (ADK) |
| Lost on restart. Use a single Uvicorn worker |
Browser | Optional encrypted OpenRouter key for Dashboard → AI Insights only | Not used by |
Browser (typical) | No Angel credentials after login | Sent once over HTTPS at login; session cookie identifies the server-side session |
Practices reflected in the app
Transient Angel credentials are never persisted by the application; they live in RAM for the session lifetime.
Stored premium credentials are Fernet-encrypted at rest; the raw values are only decrypted in the scheduler worker for the duration of a briefing run and then discarded.
Web-backed Angel sessions expire after 8 hours (
SESSION_TTL_SECONDSinsession_manager.py).The
FOR UPDATE SKIP LOCKEDpattern inrepository.pymakes the scheduler safe to run across multiple replicas, though only one process should haveSCHEDULER_ENABLED=1.Terminate TLS at the edge for public deployments (Railway, Render, etc.).
Operational cautions
Lock down
.env(file permissions, no commits) and use platform secret stores in production.Dashboard "Save OpenRouter key" keeps ciphertext in
localStorage— treat the device as trusted.Provider rate limits (Angel, OpenRouter, news APIs) still apply; heavy polling can trigger throttling.
The TOTP secret stored in the DB allows the scheduler to generate TOTP codes autonomously. Treat it with the same sensitivity as a password.
License
MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Open-source MCP server for Zerodha Kite Connect. Portfolio, market data, backtesting, alerts.
Research-only MCP server: your AI as a quant research desk. 90 tools, no trades, no brokers.
Trading MCP server for AI agents, with live market data, account reads and controlled execution.
MCP server for Mudrex futures trading enabling AI agents to securely access data and risk tools.
Related MCP Servers
- AlicenseAqualityDmaintenanceAn MCP server that enables users to manage equity holdings, execute trades, and track market data on Groww using natural language. It supports mutual fund investments and SIP management, including a mock mode for risk-free testing.23MIT
- AlicenseBqualityDmaintenanceMCP server for Angel One SmartAPI. Lets AI clients trade Indian stocks, manage orders and GTT rules, read holdings/positions/funds, fetch quotes/candles/OI/Greeks, and estimate margin/brokerage with TOTP login and built-in safety guards.3256 npm1MIT
- AlicenseAqualityDmaintenanceAn MCP server that lets an AI agent read your portfolio, place paper trades, and check the leaderboard on your ChartObserver account.137 npmMIT
- FlicenseNot gradedqualityDmaintenanceAn MCP server for Zerodha Kite Connect that enables AI agents to execute trades, manage portfolios, fetch market data, and perform technical and fundamental analysis.-