Fund Tracker is a self-hosted, multi-profile web service for tracking mutual funds and stocks, built to answer one specific question: *which securities are historically strong performers that are currently trading below where they normally sit* — a systematic "buy the proven dip" screen, rather than chasing whatever's up the most right now.
It is **not** a data source or execution platform — it pulls public price history (Yahoo Finance), computes a set of derived scores, and presents ranked, filterable, exportable views plus a daily email report. All investment decisions remain manual.
- **SSL:** Force SSL enabled, Let's Encrypt via NPM
- **Internal LAN access:** `http://192.168.150.40:8000/dashboard/`
### QA
- **Domain:** `https://funds.qa.kingdezigns.com/`
- **Proxy:** NPM on HAS (192.168.150.30) → `192.168.150.40:8001`
- **SSL:** Force SSL enabled, Let's Encrypt via NPM
- **Internal LAN access:** `http://192.168.150.40:8001/dashboard/`
No CrowdSec/Fail2Ban changes were required — traffic proxied through NPM inherits the same protection as every other service behind it.
---
## 🔀 QA → Production Deployment Workflow (v1.8.0+)
All changes follow a structured deployment path. **No changes are ever made directly to production as a development workflow.**
```
DEVELOPMENT
↓
QA (funds.qa.kingdezigns.com)
↓
Test / Verify in QA
↓
1. cp files to Production + docker restart fundtracker_api
2. Verify the site works
3. Click "Deploy to Prod" in the Dev Log on the QA site
→ auto-syncs DevLog records to prod DB
→ nav version updates for all users
```
**Critical order:** always copy files and restart FIRST, then click Deploy to Prod. If you click Deploy to Prod before copying files, the nav will show the new version number while the old code is still running.
### Promoting a tested QA version to Production
```bash
# Copy changed files (adjust list to what actually changed)
Then click **Deploy to Prod** in the Dev Log on the QA site — this simultaneously marks the project as prod-deployed in the QA database and syncs the DevLog records to the production database.
### Post-promotion verification checklist
-`app_env: production` in `/health` response
- Scheduler registered in logs: `Added job "sync_and_report"` and `Scheduler started (APP_ENV=production)`
- **Scheduler:** APScheduler, in-process — runs the daily sync + report job inside the API container (production only; disabled in QA)
- **Market data:** Yahoo Finance via the `yfinance` library, using a `curl_cffi` session with Chrome browser impersonation (required — Yahoo's bot detection blocks the default HTTP client)
### Environment Configuration (v1.7.0+)
A single authoritative environment flag controls all environment-specific behaviour:
| Setting | Production | QA |
|---|---|---|
| `APP_ENV` | `production` | `qa` |
| Automatic stock sync | ✅ Enabled | ❌ Disabled |
| Scheduled emails | ✅ Enabled | ❌ Suppressed |
| Manual stock sync endpoint | Available | Available |
| DevLog sync to prod DB | ❌ Not available | ✅ Available (via `PROD_DATABASE_URL`) |
**`APP_ENV` is the only flag.** There are no `IS_DEV`/`IS_PROD` split flags — any unrecognised value defaults to `production` so the live site can never be left in a broken state.
### Email behaviour in QA
-`send_email()` in `mailer.py` accepts a `force` parameter (default `False`)
- Automatic/scheduled sends return `False` silently in QA without touching SMTP
- Explicit manual actions (password reset) use `force=True` and still deliver
- Any QA email that does send has `[QA TEST]` prepended to the subject
Does this security normally rank near the top of its peer group by raw return, and has it recently fallen hard in that ranking? Requires a peer group of 5+ securities sharing the same group tag.
All scores can be restricted to a trailing window (6mo/1yr/2yr/3yr/5yr/all).
---
## 📋 Dev Log — Auto-Versioning System (v1.8.0)
### Overview
The Dev Log tracks all projects through a QA → Production pipeline with automatic version assignment. Versions are never manually entered — they are calculated and assigned at deployment time.
| No Version | no bump | Changes that should not count as a version (hotfixes, config tweaks) |
### Lifecycle
```
Create Project (select update type)
↓
Queue (no version assigned yet)
↓
Deploy to QA → version auto-assigned based on update type + current highest version
↓
QA column (grouped by version, collapsible cards)
↓
Deploy to Prod → same version used, DevLog records auto-synced to prod DB
↓
Production column
```
### Nav version behaviour
- The nav footer version updates **only when a project is deployed to Production** — not on QA deploy
- This is intentional: the nav reflects what is actually live in production, not what's in QA
- The Dev Log page shows both the current QA version and Production version in the env info bar at the top
### DevLog DB sync (QA → Production)
- **Automatic per-project sync:** clicking "Deploy to Prod" in the Dev Log auto-syncs that project's version row and task row to the production database — no manual SQL needed
- **One-time bulk sync:** `POST /admin/devlog/sync-to-prod` — available via the "↑ Sync DevLog to Prod DB" button visible on the Dev Log page in QA only. Safe to run multiple times (upserts by version_number and title+created_at)
- Sync is **non-fatal** — if the prod DB connection fails, the QA-side deploy still succeeds and an error is logged
### Docker network configuration (required for sync)
The QA API container must be on the same Docker network as the production DB container. Configured in the QA compose file:
```yaml
# In qa_api service:
networks:
- default
- fundtracker_prod
# At bottom of compose file:
networks:
fundtracker_prod:
external: true
name: fundtracker_default
```
`PROD_DATABASE_URL` in the QA compose environment points at the production DB by container name:
- **Compose file:** `/Kingdezignsnas16/fundtracker-qa/fundtracker-qa.yml` (OMV-managed, do not hand-edit)
- **pgdata:** `/opt/fundtracker_qa/pgdata` (owned by UID/GID 70:70 — the postgres user on this host)
- **DB credentials:** user `fundtracker_qa`, db `fundtracker_qa`, password `Valerie8545_qa`
- **Service names in compose:** `qa_db` and `qa_api` (not `db`/`api` — OMV named them differently)
- **Networks:** QA API is on both `default` (its own network) and `fundtracker_prod` (external, mapped to `fundtracker_default`) — required for DevLog DB sync to reach the prod DB container
### Key environment variables (both environments)
| Variable | Production | QA | Purpose |
|---|---|---|---|
| `APP_ENV` | `production` | `qa` | Single environment flag |
| `PRIMARY_ADMIN_USERNAME` | `rufusking` | `rufusking` | Cannot be deleted or demoted |
| `TRUSTED_PROXY_IP` | `192.168.150.30` | `192.168.150.30` | Real IP forwarding from NPM |
### Deployment patterns
- **Code-only changes** (edits inside `api/app/`): copy updated files into the project directory, then `sudo docker restart fundtracker_api`. Plain restart is sufficient since `app/` is bind-mounted.
- **New Python dependencies** (`requirements.txt` changes): requires `docker compose build --no-cache api` followed by `up -d`.
- **Compose YAML / environment variable changes**: requires `up -d --force-recreate` — a plain restart reuses the old in-memory environment.
- **Structural DB migrations**: take a `pg_dump` backup first.
### QA-specific compose commands
```bash
# Start QA
sudo docker compose -f /Kingdezignsnas16/fundtracker-qa/fundtracker-qa.yml up -d
# Restart QA API only (code change)
sudo docker restart fundtracker_qa_api
# Force-recreate QA API (compose/env change)
sudo docker compose -f /Kingdezignsnas16/fundtracker-qa/fundtracker-qa.yml up -d --force-recreate qa_api
Per-profile, intraday monitoring of up to 5 tickers for BUY signal transitions. Sends one email alert when a signal changes *to* BUY — not repeatedly while it stays BUY. Once the signal leaves BUY and returns, a new alert fires.
- **Module:** `watch_alerts.py` — self-contained: migration, scheduler job, API router
- **Poll interval:** per-user setting (`watch_poll_minutes` in the `settings` table, valid: 5/10/15/30/45/60). Scheduler job fires on a 5-minute base tick; each monitor's `last_checked_at` gates whether the user's chosen interval has elapsed.
- **Market hours:** `pandas-market-calendars` (NYSE calendar) — correctly excludes weekends AND NYSE holidays. Graceful fallback to weekday-only check if library unavailable.
- **Price refresh:** `period="5d"` Yahoo pull per unique monitored ticker — lightweight, not a full 5-year re-download.
- **Live dashboard row refresh:** frontend polls `/watch-alerts/monitors` on the user's chosen interval and surgically updates only the Signal cell for monitored tickers — no full page reload.
- **New dependency:** `pandas-market-calendars>=4.3.1` added to `requirements.txt` — requires image rebuild on first deploy.
- **UI panel:** "Watch Alerts" panel on dashboard — single row layout: interval dropdown | ticker chips with signal badges | Add input | Track button. Market Open badge updates every minute client-side.
- **Backend:** `ticker_health_router` appended to `admin.py`, registered in `main.py`
- **Migration:** `migrate_sync_metadata()` in `migrations.py` — adds `last_sync_at`, `last_sync_rows`, `last_sync_error` to `instruments` table via `ADD COLUMN IF NOT EXISTS`. Safe, additive, no backup needed.
### Flags surfaced
| Flag | Condition |
|---|---|
| `no_prices` | 0 price points ever stored |
| `last_sync_empty` | Most recent sync returned 0 rows |
| `never_synced` | `last_sync_at` is NULL |
| `stale` | `last_sync_at` > 3 days ago |
| `suspicious_symbol` | Ticker contains `.``/``\``,` or space |
| `sync_error` | `last_sync_error` is non-null |
### Admin actions (all inline, no DB access needed)
- **↻ Re-sync** — force immediate Yahoo sync, shows row count or error inline
- **✕ Delete** — dry-run first (shows price count + affected profile count), then `?confirm=true` to execute. Cascades: price points, watchlist entries, metric snapshots, watch alert monitors.
### Sync metadata stamping
`data_fetch.sync_instrument_from_yahoo()` now stamps `last_sync_at`, `last_sync_rows`, and `last_sync_error` on every call — success, empty, and exception all leave a clear trail. Covers daily job and admin force-syncs.
---
## 📈 Signal Logic Refinement — WATCH Threshold Tightening (v1.9.0)
WATCH was previously a catch-all "else" for non-held securities — anything that didn't trigger BUY/SELL/null got WATCH, which was the majority of the portfolio. Reclassified as a high-value alert requiring positive evidence.
**New WATCH criteria (non-held only, all require quality ≥ 55):**
**Securities that now get null instead of WATCH:** solid quality, normal z-score, no dip forming, no peer anomaly — "nothing to see here" is correctly represented as no signal.
**MUTF null case fully preserved:** `quality_score is None` still returns null for non-held (the "do not touch" marker). No change to that path.
**Key threshold constants** (all in `signals.py`, named for easy adjustment):
-`_WATCH_QUALITY_FLOOR = 55.0`
-`_WATCH_OPPORTUNITY = 55.0`
-`_WATCH_ZSCORE = -1.2`
-`_WATCH_REBOUND = 50.0`
---
## 🖥️ Dashboard Layout Consolidation (v1.9.0)
View Controls and Add Ticker panels merged into a single split panel (left/right) to reduce vertical space. Export/Import, Send Report, and Held Only moved from a third row under View Controls to a second row under Add Ticker (right column). "Send email report now" button renamed to "Send Report".
- **Yahoo Finance blocking (fixed):** `yfinance`'s default HTTP client gets silently blocked by Yahoo's bot detection. Fixed by routing all requests through a `curl_cffi` session impersonating a real Chrome browser's TLS fingerprint.
- **Bogus-ticker crash (fixed):** a nonexistent ticker could make `yfinance`'s internal metadata lookup throw an unhandled exception. Now caught and treated as "0 rows synced."
- **Ticker verification with override:** adding a brand-new ticker attempts a real sync as verification. Zero rows returned prompts a warning with an explicit "add anyway" override.
-`/opt/fundtracker/pgdata` (production) and `/opt/fundtracker_qa/pgdata` (QA) can both fold into `nas16-backup.sh`.
- Use `pg_dump` rather than raw file-copy for reliable backups of live Postgres data.
- The one exception to "re-syncable from Yahoo": user accounts, watchlist memberships, cost basis, and legal-acceptance records — keep backups current for these.
- **MANDATORY (added 2026-10-11):** every delivery of Fund Tracker files must OPEN with the exact `scp` → `sudo cp` (QA path `/Kingdezignsnas16/fundtracker-qa/api/app/...`) → `sudo docker restart fundtracker_qa_api` command block, with real file names and restart-vs-rebuild stated, before any explanation — then, after QA passes, the production copy + `sudo docker restart fundtracker_api` + Deploy to Prod order described above. See `server_debteliminator.md` §3a-0 for the template.
- **Two environments:** production (`funds.kingdezigns.com`, port 8000, containers `fundtracker_api`/`fundtracker_db`) and QA (`funds.qa.kingdezigns.com`, port 8001, containers `fundtracker_qa_api`/`fundtracker_qa_db`). Both run on NAS16 simultaneously with completely separate databases.
- **Single environment flag:** `APP_ENV=production` or `APP_ENV=qa`. No `IS_DEV`/`IS_PROD` flags. Unrecognised values default to `production`.
- **QA behaviour:** scheduler idle, `send_email()` suppresses automatic sends, password-reset emails use `force=True` and still deliver, amber "⚠️ QA ENVIRONMENT" banner in UI, DevLog sync to prod DB available.
- **Production behaviour:** scheduler runs at 06:00 UTC, emails send normally, no QA banner, no `PROD_DATABASE_URL`.
- **Deployment workflow:** changes → QA → test → (1) cp files to prod + docker restart → (2) verify → (3) click Deploy to Prod in Dev Log on QA site. Never reverse steps 1 and 3.
- **Dev Log auto-versioning (v1.8.0):** projects created in Queue with update_type (minor/major/platform/no-version). Deploy to QA auto-assigns next version. Deploy to Prod uses same version + auto-syncs DevLog records to prod DB. Nav version only updates on Deploy to Prod. Cards collapsed by default, click to expand.
- **DevLog DB sync:** QA API is joined to `fundtracker_default` network so it can reach `fundtracker_db` by container name. `PROD_DATABASE_URL` set in QA compose. Auto-syncs on Deploy to Prod. Bulk sync via `POST /admin/devlog/sync-to-prod` (button on Dev Log page in QA only). Non-fatal if prod DB unreachable.
- **QA compose network config:** `qa_api` service has `networks: [default, fundtracker_prod]`; bottom of compose declares `networks: fundtracker_prod: external: true, name: fundtracker_default`. Required for DevLog sync. If QA API can't reach prod DB, verify this network config and run `docker compose up -d --force-recreate qa_api` (not just `docker restart`).
- **`docker restart` vs `up -d --force-recreate`:** restart reuses the existing in-memory container environment — compose file changes (env vars, networks, volumes) are NOT picked up. Always use `force-recreate` after editing the compose file.
- **Production compose project:** `fundtracker` at `/Kingdezignsnas16/fundtracker/`, compose file `fundtracker.yml`, pgdata at `/opt/fundtracker/pgdata`.
- **QA compose project:** `fundtracker-qa` at `/Kingdezignsnas16/fundtracker-qa/`, compose file `fundtracker-qa.yml`, pgdata at `/opt/fundtracker_qa/pgdata` (owned 70:70), service names `qa_api`/`qa_db` in compose.
- Scoring: quality → opportunity → combined → rebound (all from price history via `yfinance`+`curl_cffi`).
- **Portfolio / transaction tracking:** buy-lot/sale/split register, FIFO/LIFO/Specific ID matching, `GET /portfolio/register`, lot locking on sale allocation.
- **Portfolio UI:** three-level collapsible hierarchy — Ticker (collapsed by default) → Buy Lot → Sale(s).
-`COOKIE_SECURE=true` and correct `PUBLIC_BASE_URL` must both be set in both environments.
- **Watch Alerts (v1.9.0):** Per-profile intraday BUY-transition monitoring. Up to 5 tickers per profile. Email fires once on BUY transition, resets when signal leaves BUY. Poll interval is per-user (5/10/15/30/45/60 min), stored in `settings` table as `watch_poll_minutes`. Scheduler base tick is 5 min; `last_checked_at` on each monitor gates the user's chosen interval. Market hours via `pandas-market-calendars` (NYSE, excludes holidays). Live dashboard row refresh on user's chosen interval — only Signal cell updated, no page reload. New dependency: `pandas-market-calendars>=4.3.1` (requires image rebuild on first deploy). Module: `watch_alerts.py`. Table: `watch_alert_monitors`.
- **Ticker Health panel (v1.9.0):** Admin-only page at `Admin → Ticker Health`. Surfaces instruments with `no_prices`, `last_sync_empty`, `never_synced`, `stale` (>3d), `suspicious_symbol`, or `sync_error` flags. Inline Re-sync, Rename (with immediate re-sync verification + audit log), and Delete (dry-run then confirm). `data_fetch.sync_instrument_from_yahoo()` now stamps `last_sync_at`/`last_sync_rows`/`last_sync_error` on every call. Migration: `migrate_sync_metadata()` adds three columns to `instruments` via `ADD COLUMN IF NOT EXISTS`. Router: `ticker_health_router` in `admin.py`.
- **WATCH signal tightened (v1.9.0):** WATCH was previously a catch-all else for non-held securities. Now requires quality ≥ 55 AND one of: opportunity ≥ 55, z-score ≤ -1.2, or rebound ≥ 50. Securities that are "fine but unexciting" now correctly return null. MUTF null (insufficient history) preserved unchanged. Thresholds are named constants at the top of `signals.py`.
- **Dashboard layout (v1.9.0):** View Controls and Add Ticker merged into one split panel. Export/Import + Send Report + Held Only moved to second row of right column. "Send email report now" → "Send Report".