infrastructure/server_fundtracker.md

502 lines
29 KiB
Markdown
Raw Normal View History

2026-08-17 20:01:54 -04:00
# Fund Tracker — Multi-Profile Mutual Fund & Stock Tracking Service
Device Type: **Docker Container (hosted on NAS16)**
2026-10-20 11:39:55 -04:00
Containers: **fundtracker_api**, **fundtracker_db** (production) / **fundtracker_qa_api**, **fundtracker_qa_db** (QA)
2026-08-17 20:01:54 -04:00
IP Address: **192.168.150.40** (shares NAS16's host IP)
VLAN: **50 — Lab / Servers**
2026-10-20 11:39:55 -04:00
Last Updated: 2026-10-11
2026-08-17 20:01:54 -04:00
---
## 🧩 Role & Purpose
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.
---
## 🌐 Public Access
2026-10-20 11:39:55 -04:00
### Production
2026-08-17 20:01:54 -04:00
- **Domain:** `https://funds.kingdezigns.com/`
- **Proxy:** NPM on HAS (192.168.150.30) → `192.168.150.40:8000`
2026-10-20 11:39:55 -04:00
- **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)
sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/config.py /Kingdezignsnas16/fundtracker/api/app/config.py
sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/main.py /Kingdezignsnas16/fundtracker/api/app/main.py
sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/routers/devlog.py /Kingdezignsnas16/fundtracker/api/app/routers/devlog.py
sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/static/admin/devlog.html /Kingdezignsnas16/fundtracker/api/app/static/admin/devlog.html
sudo docker restart fundtracker_api
```
Then verify:
```bash
curl https://funds.kingdezigns.com/health
# → {"status":"ok","app_env":"production"}
sudo docker logs fundtracker_api --tail 15
```
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)`
- No QA banner visible on the production site
- Production site loads and functions normally
- Nav footer shows the new version number
2026-08-17 20:01:54 -04:00
---
## 🖥️ Architecture
### Stack
2026-10-20 11:39:55 -04:00
- **API:** FastAPI (Python 3.12), Docker container `fundtracker_api` (prod) / `fundtracker_qa_api` (QA)
- **Database:** PostgreSQL 16 (Alpine), separate containers and storage per environment
2026-08-17 20:01:54 -04:00
- **Frontend:** Vanilla HTML/JS/CSS (no build step), served directly by FastAPI's `StaticFiles` mount at `/dashboard/`
2026-10-20 11:39:55 -04:00
- **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 |
| QA banner in UI | Absent | ✅ Amber banner |
| `/api/env-info` endpoint | `is_qa: false` | `is_qa: true` |
| 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
2026-08-17 20:01:54 -04:00
### Data model — shared securities, private watchlists
The core design decision: **security data is shared across all profiles, personal data is private.**
| Concept | Table | Shared or private | Contains |
|---|---|---|---|
2026-10-20 11:39:55 -04:00
| Security | `instruments` | **Shared** — one row per ticker | ticker, name, category, group tag, price history, benchmark link |
| Watchlist entry | `watchlist_entries` | **Private** per profile | is_held, held_since, cost_basis |
| Metric snapshot | `metric_snapshots` | Shared (security-level) | Daily-recorded quality/opportunity/combined/rebound scores |
| Settings | `settings` | Private per profile | Each profile's rebalance date |
2026-08-17 20:01:54 -04:00
### Multi-profile auth
2026-10-20 11:39:55 -04:00
- Session-cookie based (httponly, `SameSite=Strict`), **not** JWT-in-localStorage
2026-08-17 20:01:54 -04:00
- Passwords hashed with `bcrypt`
- 5 failed login attempts locks the account for 15 minutes
- Forced password change on any seeded or admin-created account — cannot be skipped
2026-10-20 11:39:55 -04:00
- Admin role can create/delete/promote accounts, force password resets, and view the anonymized cross-profile Census
2026-08-17 20:01:54 -04:00
---
## 📊 Scoring Methodology
2026-10-20 11:39:55 -04:00
All scores are computed from price history only (no fundamentals data).
2026-08-17 20:01:54 -04:00
### Quality score (0–100)
2026-10-20 11:39:55 -04:00
Long-run risk-adjusted strength:
2026-08-17 20:01:54 -04:00
- 35% annualized Sharpe ratio
2026-10-20 11:39:55 -04:00
- 20% annualized Sortino ratio
2026-08-17 20:01:54 -04:00
- 25% CAGR
2026-10-20 11:39:55 -04:00
- 20% consistency (% of historical rolling windows that were positive)
2026-08-17 20:01:54 -04:00
2026-10-20 11:39:55 -04:00
Requires 30+ price points; below that returns null.
2026-08-17 20:01:54 -04:00
### Opportunity score (0–100)
2026-10-20 11:39:55 -04:00
`0.6 × quality + 0.4 × depressed-ness`. Depressed-ness uses `min()` of:
1. `current_return_zscore` — is the current rolling return unusual for this security's own history
2. `drawdown_from_52wk_high_pct` — is it actually below its recent peak
2026-08-17 20:01:54 -04:00
### Combined score (0–100)
2026-10-20 11:39:55 -04:00
Harmonic mean of quality and opportunity — punishes imbalance.
2026-08-17 20:01:54 -04:00
2026-10-20 11:39:55 -04:00
### Rebound score (0–100)
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.
2026-08-17 20:01:54 -04:00
### Buy / Sell / Hold signal (held positions only)
2026-10-20 11:39:55 -04:00
Simple threshold-based heuristic — screening aid, not a trade instruction.
2026-08-17 20:01:54 -04:00
### Quality lookback (adjustable, default 3 years)
2026-10-20 11:39:55 -04:00
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.
### Update Types
| Type | Version Bump | Use For |
|---|---|---|
| Minor | +0.0.1 | Normal incremental changes |
| Major | +0.1.0 | Larger feature / functionality changes |
| Platform | +1.0.0 | Significant platform-level changes |
| 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:
```
PROD_DATABASE_URL=postgresql+psycopg2://fundtracker:Valerie8545@fundtracker_db:5432/fundtracker
```
Production compose does **not** have `PROD_DATABASE_URL` — sync endpoints return 503 in production by design.
### Dev Log API endpoints
| Endpoint | Purpose |
|---|---|
| `GET /admin/devlog/projects` | List all projects |
| `POST /admin/devlog/projects` | Create project (queue entry) |
| `PATCH /admin/devlog/projects/{id}` | Edit title, category, update_type, notes, status |
| `DELETE /admin/devlog/projects/{id}` | Delete (queue only — cannot delete deployed projects) |
| `POST /admin/devlog/projects/{id}/deploy-qa` | Assign next version + deploy to QA |
| `POST /admin/devlog/projects/{id}/deploy-prod` | Promote to Production + auto-sync to prod DB |
| `POST /admin/devlog/projects/{id}/undeploy-qa` | Roll back QA deployment |
| `POST /admin/devlog/projects/{id}/undeploy-prod` | Roll back Production deployment |
| `POST /admin/devlog/sync-to-prod` | Bulk sync all DevLog data to prod DB (QA only) |
| `GET /admin/devlog/versions` | List all versions |
| `PATCH /admin/devlog/versions/{id}` | Edit version label/notes |
| `GET /admin/devlog/deployed` | Current production version (used by nav footer) |
| `GET /admin/devlog/qa-version` | Current QA version |
2026-08-17 20:01:54 -04:00
---
## 🔐 Admin Features
### Census (anonymized cross-profile leaderboard)
2026-10-20 11:39:55 -04:00
`Admin → Census` page. Aggregates every tracked security across all profiles — does not reveal which specific profile tracks what.
2026-08-17 20:01:54 -04:00
### Legal document versioning
2026-10-20 11:39:55 -04:00
Two independently-versioned, admin-editable documents:
- **Terms of Use** — gated immediately after login
- **Investment Disclaimer** — gated specifically before adding any ticker
2026-08-17 20:01:54 -04:00
2026-10-20 11:39:55 -04:00
Publishing a new version immediately requires every profile to re-accept.
2026-08-17 20:01:54 -04:00
---
2026-10-20 11:39:55 -04:00
## 💼 Portfolio / Transaction Tracking
2026-10-20 11:39:55 -04:00
Full buy-lot/sale/split transaction register per profile.
### Data model
2026-10-20 11:39:55 -04:00
- **Buy lots** — each purchase is its own row: original quantity, remaining quantity, buy price, buy fees, notes/source
- **Sales** — linked to buy lot(s) via sale allocations; FIFO, LIFO, and Specific Lot Identification supported
- **Lot status** — `ACTIVE`, `PARTIAL`, `CLOSED`
- **Stock splits** — only adjusts lots active and purchased before the split date
### Key endpoints
| Endpoint | Purpose |
|---|---|
| `GET /portfolio/holdings` | Active holdings dashboard view |
2026-10-20 11:39:55 -04:00
| `GET/POST /portfolio/lots/{ticker}` | List / create buy lots |
| `PATCH /portfolio/lots/{lot_id}` | Edit a buy lot (zero-allocation only) |
| `DELETE /portfolio/lots/{lot_id}` | Delete a buy lot (zero-allocation only) |
| `GET/POST /portfolio/sales` | List / record sales |
| `DELETE /portfolio/sales/{sale_id}` | Delete a sale — restores allocated quantity to lot(s) |
| `GET/POST /portfolio/splits` | List / apply stock splits |
2026-10-20 11:39:55 -04:00
| `GET /portfolio/register` | Full lot+sale register view |
| `POST /portfolio/import/csv` | Bulk import from CSV |
2026-10-20 11:39:55 -04:00
### Portfolio UI — three-level collapsible hierarchy
**Ticker (collapsed by default) → Buy Lot → Sale(s)**
2026-10-20 11:39:55 -04:00
---
## 🐳 Docker Configuration
### Production
Managed via OMV → Services → Compose, project `fundtracker`, at `/Kingdezignsnas16/fundtracker/`.
| Container | Name | Port |
|---|---|---|
| API | `fundtracker_api` | `8000:8000` |
| Database | `fundtracker_db` | (internal only) |
- **Compose file:** `/Kingdezignsnas16/fundtracker/fundtracker.yml` (OMV-managed, do not hand-edit)
- **pgdata:** `/opt/fundtracker/pgdata`
- **DB credentials:** user `fundtracker`, db `fundtracker`, password `Valerie8545`
- **Network:** `fundtracker_default` — production DB is reachable by container name `fundtracker_db` from any container on this network
### QA
Managed via OMV → Services → Compose, project `fundtracker-qa`, at `/Kingdezignsnas16/fundtracker-qa/`.
| Container | Name | Port |
|---|---|---|
| API | `fundtracker_qa_api` | `8001:8000` |
| Database | `fundtracker_qa_db` | (internal only) |
- **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 |
| `DATABASE_URL` | prod connection string | QA connection string | Primary DB |
| `PROD_DATABASE_URL` | *(not set)* | prod connection string | DevLog sync target |
| `SYNC_HOUR_UTC` / `SYNC_MINUTE_UTC` | `6` / `0` | (ignored in QA) | Daily sync+report time |
| `SMTP_*` | Zoho creds | Zoho creds (suppressed in QA) | Email |
| `ADMIN_SEED_USERNAME/PASSWORD/EMAIL` | Bootstrap admin | Bootstrap admin | Only used if `users` table empty |
| `SESSION_TTL_DAYS` | `14` | `14` | Login session length |
| `COOKIE_SECURE` | `true` | `true` | Required for HTTPS |
| `PUBLIC_BASE_URL` | `https://funds.kingdezigns.com` | `https://funds.qa.kingdezigns.com` | Password reset links |
| `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
# View QA logs
sudo docker logs fundtracker_qa_api --tail 30
# View QA DB logs
sudo docker logs fundtracker_qa_db --tail 20
```
2026-10-20 11:39:55 -04:00
### Database migrations
Two tiers, by risk:
- **Additive** (`ADD COLUMN IF NOT EXISTS`) — safe, runs on every startup, no backup needed.
- **Structural** — requires a `pg_dump` backup before deploying.
2026-10-20 11:39:55 -04:00
```bash
# Production backup
sudo docker exec fundtracker_db pg_dump -U fundtracker fundtracker | gzip > /tmp/fundtracker-prod-$(date +%Y%m%d).sql.gz
2026-10-20 11:39:55 -04:00
# QA backup
sudo docker exec fundtracker_qa_db pg_dump -U fundtracker_qa fundtracker_qa | gzip > /tmp/fundtracker-qa-$(date +%Y%m%d).sql.gz
```
2026-10-20 11:39:55 -04:00
### Re-cloning production data into QA
When QA needs a fresh copy of production data:
```bash
sudo docker exec fundtracker_db pg_dump -U fundtracker fundtracker \
| sudo docker exec -i fundtracker_qa_db psql -U fundtracker_qa fundtracker_qa
```
2026-10-20 11:39:55 -04:00
The `ERROR: role "fundtracker" does not exist` messages are harmless — ownership assignment fails but all table structure and data copies correctly.
---
2026-10-20 11:39:55 -04:00
## 📊 Watch Alerts — Intraday BUY Signal Monitoring (v1.9.0)
2026-08-17 20:01:54 -04:00
2026-10-20 11:39:55 -04:00
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
- **DB table:** `watch_alert_monitors` — `user_id`, `ticker`, `last_signal`, `last_checked_at`, `alert_sent_at`
- **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.
2026-08-17 20:01:54 -04:00
2026-10-20 11:39:55 -04:00
### Watch Alerts API endpoints
| Endpoint | Purpose |
2026-08-17 20:01:54 -04:00
|---|---|
2026-10-20 11:39:55 -04:00
| `GET /watch-alerts/monitors` | List user's monitors with last_signal |
| `POST /watch-alerts/monitors` | Add ticker (max 5, ticker must exist in instruments) |
| `DELETE /watch-alerts/monitors/{ticker}` | Remove monitor |
| `GET /watch-alerts/poll-interval` | Get user's poll interval (minutes) |
| `PUT /watch-alerts/poll-interval` | Set user's poll interval |
2026-08-17 20:01:54 -04:00
2026-10-20 11:39:55 -04:00
---
## 🩺 Ticker Health Panel (v1.9.0)
Admin-only self-service panel to identify and remediate broken or stale instruments without SSH or psql access.
- **Page:** `Admin → Ticker Health` (`/dashboard/admin/ticker-health.html`)
- **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
- **✎ Rename** — inline ticker rename (e.g. `BRK.B` → `BRK-B`), immediately re-syncs to verify, updates `WatchAlertMonitor` rows, logs to audit log
- **✕ 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):**
- Opportunity ≥ 55 — a real dip is developing
- Z-score ≤ -1.2 — return running meaningfully below normal (early-warning dip)
- Rebound ≥ 50 — moderate peer-relative anomaly forming
**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".
2026-08-17 20:01:54 -04:00
---
## ⚠️ Known Issues & Fixes Already Shipped
2026-10-20 11:39:55 -04:00
- **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.
2026-08-17 20:01:54 -04:00
---
## 💾 Backup
2026-10-20 11:39:55 -04:00
- `/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.
2026-08-17 20:01:54 -04:00
---
## 🧠 Summary for AI Systems
2026-10-20 11:39:55 -04:00
- **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.
2026-08-17 20:01:54 -04:00
- Fund Tracker = **multi-profile mutual fund/stock tracking web app**, Docker Compose on NAS16, VLAN 50.
2026-10-20 11:39:55 -04:00
- **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`).
2026-08-17 20:01:54 -04:00
- Auth: httponly session cookies, bcrypt, 5-attempt lockout, forced password change on seeded accounts.
2026-10-20 11:39:55 -04:00
- Admin: account management, anonymized cross-profile Census, versioned legal document publishing.
- **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".
2026-08-17 20:01:54 -04:00
---
# ✔️ End of File