A lightweight yet powerful portfolio research tool for investors who want to study portfolio performance, run backtests, and calculate real-time position sizing with risk analysis.
Monitor your portfolio and analyze asset returns, volatility and correlations
Whether you're building a long-term investment strategy or rebalancing your current portfolio, PortfolioExpert helps you:
- Study historical performance — See how your portfolio allocation would have performed over any time period
- Make informed decisions — Understand risk metrics like Sharpe ratio, max drawdown, and volatility before committing capital
- Calculate exact positions — Know precisely how many shares to buy/sell to achieve your target allocation
- Analyze risk exposure — View Value-at-Risk (VaR) projections and Monte Carlo simulations
All running locally on your machine with automatic data caching — no subscription fees, no data limits.
| Feature | Description |
|---|---|
| Any Ticker | Add stocks, ETFs, indices, or bonds from Yahoo Finance |
| Auto Data Sync | Automatic data fetching and smart caching (no redundant API calls) |
| Custom Allocations | Set precise portfolio weights with auto-normalization |
| Leverage Support | Test leveraged strategies with realistic borrowing costs |
| Sub-Period Analysis | Change allocations mid-backtest to simulate rebalancing |
| Rich Metrics | Total return, CAGR, Sharpe ratio, volatility, max drawdown |
| Interactive Charts | Zoom, pan, and export Plotly.js visualizations |
| Save Strategies | Store and reload your portfolio configurations |
| Feature | Description |
|---|---|
| Position Sizing | Calculate exact share counts for your target allocation |
| Current Holdings | Input existing positions to get buy/sell orders |
| Risk Metrics | Expected return, volatility, Sharpe ratio |
| VaR Analysis | 95% and 99% Value-at-Risk over 30 days |
| Projections | Monte Carlo simulations for portfolio value forecasts |
cd backend
# Create virtual environment (first time only)
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate # macOS/Linux
# venv\Scripts\activate # Windows
# Install dependencies (first time only)
pip install -r requirements.txt
# Start the server
python main.pyOr simply run the convenience script from the project root:
./start.shOpen app/index.html in your browser:
# macOS
open app/index.html
# Or just double-click the file in Finder/ExplorerThe app opens Portfolio Watcher. In Asset Analysis or Stat Analysis, click Load from Portfolio Watcher to replace the selection with the saved IBKR main portfolio’s category proxies and allocation weights. Options and cash are excluded; ETF and futures exposures in the same category are combined. Weights show gross exposure shares as reference information; these pages analyze individual proxy returns. Analysis dates and windows stay unchanged. Refresh the broker snapshot in Portfolio Watcher before importing if needed.
Backtest is removed from navigation. Its UI remains at app/backtest.html, and its backend is retained.
- Add tickers — Type
SPY, QQQ, BNDand click "Add" - Adjust weights — Use sliders to set your allocation
- Set date range — Choose your analysis period
- Click "Run Backtest" — View results instantly
PortfolioExpert/
├── app/ # Frontend application
│ ├── index.html # Opens Portfolio Watcher
│ ├── backtest.html # Archived Backtest UI
│ ├── portfolio-watcher.html # Portfolio Watcher (position sizing)
│ ├── css/ # Stylesheets
│ └── js/ # Application logic
│
├── backend/ # Python API server
│ ├── main.py # FastAPI entry point
│ ├── config.py # Configuration
│ ├── requirements.txt # Dependencies
│ ├── database/ # SQLite models & schema
│ ├── modules/ # Core logic
│ │ ├── data_loader.py # Auto data fetching & caching
│ │ ├── backtest_engine.py # Backtesting calculations
│ │ └── portfolio.py # Portfolio management
│ └── routers/ # API endpoints
│
├── docs/ # Documentation assets
│ └── screenshot.png # UI screenshot for README
├── start.sh # One-command startup
├── .gitignore
└── README.md
| Method | Endpoint | Description |
|---|---|---|
| GET | /data/tickers |
List all cached tickers |
| POST | /data/load |
Fetch and cache ticker data |
| POST | /data/update |
Update ticker to latest prices |
| POST | /backtest |
Run portfolio backtest |
| POST | /backtest/subperiod |
Backtest with allocation changes |
| GET | /portfolios |
List saved strategies |
| POST | /portfolios |
Save a strategy |
Interactive API docs at http://localhost:8000/docs when running.
For Federal Funds Rate data (used in Sharpe ratio and leverage cost calculations):
export FRED_API_KEY="your_api_key_here"Or create backend/.env:
FRED_API_KEY=your_api_key_here
Get a free key at: https://fred.stlouisfed.org/docs/api/api_key.html
| Layer | Technology |
|---|---|
| Frontend | Vanilla HTML/CSS/JS, Plotly.js, Flatpickr |
| Backend | Python 3.9+, FastAPI, SQLAlchemy |
| Database | SQLite (local, zero-config) |
| Data | Yahoo Finance, FRED (optional) |
MIT
With the backend running, monitoring and backtest edits are automatically saved
as readable JSON in backend/data/portfolios/:
monitoring.json: Portfolio Watcher configuration, assets, and saved state.futures-monitor.json: Futures Monitor positions and latest prices.backtest.json: Current backtest tickers, weights, leverage, dates, and sub-periods.presets.json: Named strategies managed by the Save/Load dialogs.
These files live on the machine running the backend, persist across browsers and restarts, and are excluded from Git. Back up this directory to preserve portfolios. Stop the app before manually editing or restoring the files, then reload the pages. If multiple tabs edit the same portfolio, the last saved change wins.
On the first visit to each portfolio page, existing browser state is migrated only if its JSON file does not exist. Use the browser that holds your old portfolio for this first visit. Legacy browser data is removed only after a successful migration. Existing SQLite strategy presets are copied on their first access; the database is retained as a backup. Market data continues to use SQLite. Display preferences and analysis-only settings still use browser storage.
Saving requires the backend. Failed loads/saves show an error; after a failed load, reload with the backend available before editing. A malformed JSON file is reported as an error and is not silently replaced.
PortfolioExpert includes a local client for IBKR's official hosted MCP endpoint,
https://api.ibkr.com/v1/api/mcp-public. It uses browser OAuth with PKCE and requests
only mcp.read; no local IB Gateway or TWS is needed for this connection.
From the repository root:
backend/venv/bin/python backend/scripts/ibkr_check.py register
backend/venv/bin/python backend/scripts/ibkr_check.py loginWhen prompted, open http://127.0.0.1:8765/, log in directly with IBKR, complete
MFA and authorize the account. The callback server listens only on loopback and
waits up to 20 minutes. Login credentials are never collected by PortfolioExpert.
After login, inspect available tools:
backend/venv/bin/python backend/scripts/ibkr_check.py toolsClient registration and OAuth tokens are stored in backend/.env, which is
Git-ignored and written with owner-only permissions. Existing settings, including
FRED configuration, are preserved. Discovery metadata, tool schemas and any account
test results belong in backend/data/ibkr/, also Git-ignored. Do not force-add these
files to Git or paste their contents into issue reports. Tokens refresh when IBKR
provides a refresh token; otherwise rerun login after expiry. Access can be revoked
in IBKR Client Portal under Manage Third-Party Consents.
Tool calls are restricted to a code-level allowlist of reviewed read operations. Account-specific historical coverage, quote freshness and continuous streaming must be verified after authentication; MCP transport streaming is not by itself a streaming price-feed guarantee.
Run local regression tests:
(cd backend && venv/bin/python -m unittest discover -s tests)Run the live account and market-data smoke test after login:
backend/venv/bin/python backend/scripts/ibkr_smoke.py
# If the requested month of option history is unavailable, test shorter windows:
backend/venv/bin/python backend/scripts/ibkr_smoke.py --retry-option-historyThe test reads account summary, currency balances and positions, resolves held
futures against IBKR's expiry ladder, and retrieves quote snapshots and one month
of daily bars for supported held stocks, options and futures. It also tests five
years of daily bars and two days of five-minute bars for one held stock/ETF.
Results, including failures, are saved to backend/data/ibkr/latest_report.json;
timestamped raw evidence is retained under backend/data/ibkr/runs/. Console output
shows progress without balances, tokens or account IDs. FROZEN and
FROZEN_DELAYED quotes must not be presented as live updates. This connection test
does not overwrite your monitoring allocation or backtest portfolio.
For an individual reviewed read operation:
backend/venv/bin/python backend/scripts/ibkr_check.py call --tool get_account_balancesThe reviewed allowlist contains account summary/balances/positions, contract and futures searches, price snapshots and price history. IBKR may advertise write tools in its tool catalog even for a read-scoped connection; this client rejects them.
Open Portfolio Watcher with the backend running. The IBKR card loads the saved
snapshot, then refreshes balances and positions through the read-only MCP client.
Sync IBKR refreshes again. Failed refreshes preserve the last snapshot and show
an error. The snapshot is stored privately in backend/data/ibkr/watcher.json;
it is independent of the manual allocation and backtest inputs.
- Main · without options shows current stock/ETF and futures holdings.
- All options assigned delivers every supported short equity/ETF put and call at its strike and respective expiry, regardless of moneyness. Puts add shares and spend cash; calls remove shares and receive cash. Existing premiums are not counted twice. Resulting shares use current marks, not an expiry-price forecast.
- Ratios use gross instrument notional, excluding cash and options. Futures use contract multipliers, not margin requirements. Cash, net exposure and actual account equity are shown separately; account equity is not projected for expiry.
- GLD/IAU/GLDM/SGOL and GC/MGC group as Gold; QQQ/QQQM and NQ/MNQ as Nasdaq 100; TLT/VGLT and ZB/UB as Long US Treasuries; UUP and DX as US Dollar Index. Other instruments retain their own group. These are economic exposure groups; ETF and futures contracts can differ in duration, tracking and other risks.
- Hover, focus or click a group for instrument quantities, multipliers, marks and exposure. Options remain in a separate table with delivery and cash obligations.
Cash security is checked against current currency cash, excluding anticipated call proceeds. Covered calls are checked against currently held shares. Shortfalls are shown explicitly, even though the all-assigned scenario still models delivery. Long, futures and nonstandard options, unsupported asset classes and missing marks are flagged; incomplete scenarios are labeled. Position marks may be frozen or delayed. The watcher does not submit orders or stream ticks.
The /ibkr/portfolio and /ibkr/portfolio/sync endpoints accept only local clients
and local origins and disable HTTP caching. Serve the frontend from app/, not
the repository root, to keep local configuration and account files private.
The IBKR allocation pie supports hover, click/tap and keyboard focus on each slice. Colors remain stable between views. The assigned view shows metric deltas versus the main view and a diverging bar chart of allocation changes in percentage points, with dollar exposure changes alongside. Actual account equity remains fixed and is labeled accordingly; it is not an estimate of net liquidation at expiry.
Daily performance comes directly from the read-only
get_pa_performance_all_periods MCP tool. The watcher plots IBKR's cumulative return
fractions as percentages and retains the reported TWR/MWR method. It does not
calculate returns from NAV ratios, which would confuse deposits with gains, or
backfill performance using today's holdings. The 1Y and YTD buttons select separate
broker-reported series; the All button is disabled when no since-inception series
is supplied. Actual performance includes historical options and holdings and stays
unchanged when switching the hypothetical assignment view.
GET /ibkr/performance uses the same loopback/origin restrictions as holdings.
History is saved privately in backend/data/ibkr/performance.json, refreshed on
page load if older than 15 minutes, and retained with a stale notice if a refresh
fails. Hover a point on the return line to see its date, cumulative return and NAV.
The current official MCP catalog supplies 1D, 7D, MTD, 1M, YTD and 1Y windows;
it does not advertise a since-inception window.
Portfolio Watcher provides a dedicated risk panel with 1M, 3M, 6M (default), and 12M calendar windows ending on the latest common available daily session. It always uses the main non-option holdings, even when the assignment view is selected. Gold uses GLD, Nasdaq 100 uses QQQ, long US Treasuries use TLT, and the US Dollar Index uses UUP. Futures are mapped at signed full contract notional; ETF positions in the same category are combined. Other USD stock-only categories can use their own symbol. Unsupported categories or excluded holdings produce an explicit error.
The estimator uses daily simple closing-price returns, sample covariance (N−1),
and Pearson correlation on identical start/end date intervals. It neither fills
missing observations nor mixes different return horizons. Annualized volatility
is sqrt(252 * w' covariance w). Signed category exposure divided by gross
instrument exposure gives allocation weights; dividing by actual account NAV gives
the equity-based estimate, including notional leverage. Option returns and exposures
are excluded; actual NAV is only the equity denominator and still includes option
liabilities. A zero-variance series has undefined correlation, displayed as a dash.
This estimates historical risk of today's fixed allocation, not actual historical
account performance or a forecast. Prices exclude distributions; cash is constant
and financing, currency conversion, futures basis/roll and duration differences
between proxies and contracts are not modeled. Five years of daily proxy history
are fetched through read-only IBKR MCP and stored in the ignored
backend/data/ibkr/risk_prices.json with owner-only permissions. The current New
York calendar date is excluded to avoid partial sessions. All windows reuse the
same histories, with a 12-hour refresh interval and explicit stale-cache labeling.
The local-only /ibkr/risk?window=6M route recomputes using the current saved holdings;
a successful holdings sync refreshes the risk panel while retaining its window.
The non-option risk panel includes two daily historical plots: annualized portfolio volatility and a single selected pair's Pearson correlation. The 1M/3M/6M/12M window selector controls both the snapshot metrics and the rolling plots. The pair dropdown preserves its selection when the window changes. Volatility can be viewed relative to current account equity (current leverage included) or gross exposure.
Every historical estimate uses today's fixed signed category weights and current leverage with only the proxy returns in that date's trailing calendar window. The graphs are hypothetical fixed-allocation risk histories, not the account's realized historical risk. Five years of daily prices are requested; the first full window is reserved for warm-up, so a 6M window produces roughly 4.5 years of plotted estimates. Exact available dates are shown beneath the graphs. Insufficient windows and undefined correlations remain gaps, not zeros. Hover or use arrow keys on a focused chart to inspect the date, estimate and observation count.
Imported watcher portfolios default to the same saved IBKR daily-close history used by watcher risk estimates. The source selector also supports Yahoo adjusted-close data from the local database, without silently mixing sources. The page shows each asset’s actual date coverage and warns when prices are older than seven days. Refresh the watcher’s risk analysis to refresh its IBKR cache.
Stat Analysis windows count trading-day return observations; the watcher uses calendar months. Rolling volatility uses sample standard deviation times √252. Rolling return is the realized compounded return over the window, not an annualized forecast. The full-period summary still shows an annualized historical mean-return estimate. Each asset uses its own history, and correlations align both return-interval endpoints for that pair; a stale third asset cannot truncate GLD/QQQ history.
Futures Monitor now uses IBKR's read-only MCP contract discovery and market data for NQ (Nasdaq 100), GC (gold), DX (US Dollar Index), ZB (Treasury bonds), and HG (US COMEX copper). Refresh IBKR prices starts a background refresh with progress. /ibkr/futures reads the saved snapshot and progress; /ibkr/futures/sync starts a refresh. Both routes are local-only. Raw evidence and snapshots remain in ignored backend/data/ibkr/ with owner-only file permissions. The former manual monitor positions remain on disk but are no longer used by this screen.
The expiry ladder comes from search_futures, uses native exchanges, and includes listed last-trading dates within 365 days. It does not invent quarterly or monthly expiry dates. Daily cash and futures bars must share a completed IBKR UTC date label, with prices no more than seven days old. Midnight-UTC session labels are not shifted to the previous New York day. Session closing times can still differ, so the rate is indicative. Quote status, delay (where provided), timestamps and rate inputs are visible per contract.
- Spot basis APR =
(F / S - 1) * 365 / days(price date, last trading date). Positive is a futures premium; negative is a discount. Net basis includes income/storage effects and is not a broker financing charge. - Calendar spread APR =
(F_later / F_front - 1) * 365 / days(front expiry, later expiry). It is a separately labelled futures-to-futures price slope, never passed off as spot carry. The nearest listed expiry remains the anchor even if its prices are missing. - Cash references must be verified equivalent instruments. No GLD fixed-ounce multiplier, Treasury yield-to-price approximation, or ETF substitution is used. ZB requires the deliverable bond, conversion factor, accrued interest and coupons for proper cash carry; the reviewed MCP toolset does not expose that complete dataset. Copper requires a compatible US physical cash reference; an LME price is not automatically equivalent.
For a read-only live coverage test after login: cd backend && venv/bin/python scripts/ibkr_futures_check.py. Missing entitlements or prices are reported per asset/contract. A connection failure preserves the previous snapshot; an unavailable cash input leaves spot APR blank.
The app header now includes Connect IBKR / Reconnect IBKR. Clicking it starts the local read-only PKCE flow and opens IBKR's login in a new tab. Complete login/MFA there; the app detects completion, and Futures Monitor resumes its data refresh. No terminal command is needed. The registered callback remains http://127.0.0.1:8765/callback, served only on loopback, with state validation and callback logging disabled. Access/refresh tokens never go to frontend JavaScript; they remain in ignored, owner-only backend/.env.
The observed MCP access token lifetime is 600 seconds (10 minutes). Access expiry alone does not require login: the client refreshes on demand, reuses the latest saved credentials, serializes refresh across threads/processes, and retries a read-only request once after HTTP 401. A rejected refresh grant requires user login. The earlier invalid_grant response does not establish a specific refresh-token lifetime or prove why it became invalid. The connection indicator reports safe expiry metadata and whether credentials are saved; server acceptance is checked by actual data requests. Refresh-token lifetime is shown only if IBKR supplies it.
