Skip to content

Claude/audit gui f f vhp#25

Merged
Frostbite1536 merged 14 commits intomainfrom
claude/audit-gui-fFVhp
Mar 12, 2026
Merged

Claude/audit gui f f vhp#25
Frostbite1536 merged 14 commits intomainfrom
claude/audit-gui-fFVhp

Conversation

@Frostbite1536
Copy link
Owner

No description provided.

claude added 14 commits March 12, 2026 16:16
The GUI was missing several major features that existed in the core
library. This update adds:

- Trade Browser tab: sortable treeview showing all individual trades
  with timestamp, market, type, side, price, shares, cost, PnL,
  source, and currency columns
- Portfolio tab: open positions, concentration risk (HHI) analysis,
  and detailed drawdown analysis with period tracking
- Tax Report tab: capital gains/losses with FIFO/LIFO/Average cost
  basis methods and short-term vs long-term classification
- Side filter (YES/NO): was available in core but missing from GUI
- Period Comparison: dialog in Analysis menu to compare two date ranges
- JSON export: added alongside existing CSV and Excel options
- Currency breakdown: global summary now shows per-currency stats
- Provider breakdown: shows per-source trade counts and PnL
- Market trade counts: listbox now shows trade count per market
- Improved Charts tab: split into Global and Market-Specific sections
  with descriptions for each chart type
- Updated About dialog: lists all 4 providers, currencies, and the
  full feature set

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
Critical bug fixes:
- compare_periods(): GUI accessed wrong dict keys (total_trades/
  total_pnl/sharpe_ratio instead of trades/pnl/sharpe), causing
  all comparison values to display as 0
- concentration_risk(): GUI accessed 'exposure_pct' instead of the
  actual 'pct_of_total' key, showing 0% for all markets
- drawdown periods: GUI accessed 'start_date'/'end_date' instead of
  actual 'start'/'end' keys, never displaying period dates
- HHI thresholds used 0-1 scale (0.15/0.25) but the actual HHI is
  on 0-10000 scale; corrected to 1500/2500 so diversification
  assessment is accurate
- Compare periods dialog accepted empty dates (passing validation
  since _validate_date_format returns True for empty strings),
  causing crash in compare_periods()

Other fixes:
- Use pre-computed by_source from calculate_global_pnl_summary()
  instead of manually recalculating provider breakdown
- Add breakeven trades count to both global and market summaries
- Use correct currency symbol (MANA prefix instead of $) for
  non-USD/USDC currencies throughout all displays
- Add keyboard shortcuts (Ctrl+O/E/D/G/Q) with menu accelerators
- Add market search/filter box to Market Analysis tab
- Show duration_days in drawdown period details
- Remove hardcoded $ from PnL filter labels

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
- README: 7-tab GUI layout, JSON export, side filter, portfolio/tax features, missing modules
- CLAUDE: Trade dataclass 14 fields (added fee)
- ARCHITECTURE: 7-tab layout, new modules (metrics, positions, drawdown, tax, comparison), JSON export, filter_by_side
- TUTORIAL: Full 7-tab documentation, keyboard shortcuts, portfolio/tax API examples, side filter
- CHANGELOG: Added v1.1.0 entry with all GUI audit additions and fixes
- STATE_MACHINE_DIAGRAMS: Side filter states, JSON export, GUI tab table, new triggers

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
1. Double-fetch race condition: Add _fetch_in_progress guard to prevent
   concurrent API fetches when user clicks "Load from API" rapidly

2. Market search desync: Clear listbox selection when search text changes
   to prevent stale selection index mapping to wrong market slug

3. Wash sale display incomplete: Show total disallowed loss dollar amount
   and per-wash-sale details (market, dates, amount) in tax report

4. Tax report filter confusion: Add note informing user that tax report
   uses all trades regardless of active filters (correct for FIFO basis)

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
…ency, security

1. Persistence DB missing fee column - Kalshi trade fees silently lost on save/restore
2. calculate_open_positions wrong avg_entry_price - was subtracting sell proceeds
   from total cost instead of using FIFO lot tracking, producing incorrect
   unrealized PnL calculations
3. MCP market_breakdown/provider_breakdown missing sanitize_numeric - NaN/Inf
   floats in PnL could produce invalid JSON responses
4. Wash sale detection missing same-day repurchases - IRS §1091 includes
   same-day repurchases in the 30-day window, but delta==0 was excluded
5. SSE transport sharing global singleton session - multiple SSE clients
   would corrupt each other's state; added per-connection contextvars
6. _handle_load_trades corrupting sources list with file paths - was adding
   "file:/path/..." alongside provider names like "limitless"
7. fetch_trades MCP tool leaking API key prefix into persisted session sources

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
- charts/global_chart.py: Use Decimal accumulation for cumulative PnL
- charts/enhanced.py: Use Decimal for running cost/shares/PnL accumulation
- api/routers/trades.py: Add sanitize_numeric to JSON and CSV exports
  to prevent NaN/Infinity producing invalid JSON
- providers/pnl_calculator.py: Use Decimal for FIFO PnL matching

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
- gui.py: Use threading.Lock for atomic check-and-set of _fetch_in_progress
  flag, preventing concurrent API fetch threads from corrupting trade data
- persistence.py: Add threading.Lock around save/restore, increase SQLite
  timeout to 30s, and allow cross-thread access (check_same_thread=False)
- api/main.py: Wrap rate limiter _rate_store access with threading.Lock to
  prevent TOCTOU races and KeyError under concurrent requests
- api/config.py: Replace @lru_cache with double-checked locking pattern to
  prevent concurrent mutation of cached Settings.SECRET_KEY during startup

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
- chart_tools.py: Add empty list guard before trades[0] access to
  prevent IndexError when market has no trades after filtering
- analysis_tools.py: Add empty list check before calculate_advanced_metrics
  to return proper error instead of passing empty list to metrics calc
- api/models/trade.py + services/trade_service.py: Add pnl_is_set (Boolean)
  and fee (Numeric) columns to Trade model, save/restore them in service.
  Previously fee data and pnl_is_set flag were silently lost on upload.
- api/services/auth_service.py: Catch ValueError/TypeError from int(raw_sub)
  in JWT parsing to prevent crash on malformed token sub claim

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
- api/routers/trades.py: Add CSV formula injection protection by
  prefixing dangerous strings (=, +, -, @) with single quote in CSV
  export. Prevents Excel/Sheets from executing injected formulas.
- prediction_mcp/tools/data_tools.py: Reject file paths containing '..'
  in load_trades handler to prevent path traversal attacks via MCP.
- api/routers/auth.py: Catch IntegrityError on user creation to handle
  TOCTOU race condition where concurrent signups pass the uniqueness
  check but fail at the database constraint level.

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
- api/config.py: Replace `Settings | None` (3.10+ syntax) with
  `Optional[Settings]` for Python 3.9 compatibility
- api/services/auth_service.py: Reformat long except tuple per Black
- prediction_mcp/server.py: Add blank lines after imports per Black

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
1. positions.py: Fix unrealized PnL sign inverted for NO (short)
   positions — NO positions profit when price drops, not rises
2. positions.py: Track YES/NO buy lots separately so sells consume
   correct side's lots (mixed lots corrupted cost basis)
3. tax.py: Use Decimal accumulation for monetary totals to prevent
   float drift across many transactions (per CLAUDE.md invariant)
4. tax.py: Scope total_fees to tax year only (was counting all years)
5. trade_loader.py: Handle Decimal NaN/Infinity in sanitize_numeric
   (previously only handled float NaN/Inf)
6. analysis_tools.py: Use Decimal for provider breakdown PnL/volume
   accumulation (per CLAUDE.md invariant)

Includes 13 regression tests covering all fixes.

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
- Wrap API fetch thread start in try/except to reset _fetch_in_progress
  flag on failure, preventing permanent lockout of the fetch button
- Add _get_currency_symbol() helper that derives symbol from trade data
- Replace hardcoded $ with dynamic currency symbol in all display methods:
  show_open_positions, show_concentration_risk, show_drawdown_analysis,
  generate_tax_report, _show_comparison_result
- Apply Black formatting

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
- Add pytest.importorskip("mcp") to test classes that import from
  prediction_mcp (TestExportPathTraversal, TestApplyFiltersMinMaxPnl,
  TestActiveFiltersNoEmpty, TestApplyFiltersCombined) so they skip
  gracefully on Python 3.9 CI without the mcp package
- Remove unused imports: functools.lru_cache (config.py), typing.Optional
  (tax.py), math (test_bugfixes_audit2.py)
- Rename ambiguous loop variable 'l' to 'lt' in tax.py (E741)

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
…prediction_mcp

F401 (unused imports) - 13 fixes:
- sqlalchemy.Float (api/models/trade.py)
- typing.List, trade_loader.Trade as TradeDataclass (api/services/chart_service.py)
- datetime.datetime (api/services/trade_service.py)
- typing.Optional, datetime.datetime, datetime.timedelta (metrics.py)
- numpy as np (pnl.py)
- dataclasses.asdict (trade_loader.py)
- typing.Optional (utils/time_utils.py, persistence.py)
- math (serializers.py)
- os (tools/export_tools.py)
- serializers.sanitize_dict (tools/portfolio_tools.py)
- starlette.routing.Mount (server.py)

F841 (unused variable) - 1 fix:
- Remove unused pnl_colors in charts/enhanced.py

E712 (comparison to True) - 2 fixes:
- Use df["pnl_is_set"].eq(True) instead of == True in pnl.py

E501 (line too long) - 7 fixes:
- Shorten docstrings (limitless.py, manifold.py)
- Break long SQL string (persistence.py)
- Split long f-string (server.py)
- Shorten description strings (data_tools.py, portfolio_tools.py, validators.py)

E402 (import not at top) - 2 fixes:
- Add noqa comments for structurally necessary late imports (server.py, state.py)

https://claude.ai/code/session_01GeuDE5MQSW6zVjxYgZU2PR
@Frostbite1536 Frostbite1536 merged commit 916c300 into main Mar 12, 2026
5 checks passed
@Frostbite1536 Frostbite1536 deleted the claude/audit-gui-fFVhp branch March 17, 2026 00:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants