name: migration-tracker
description: Context for ongoing migration from old Portfolio Buddy app. Use when: fixing bugs, adding migrated features, checking feature parity, or understanding why certain code exists. Contains list of 40 features being migrated and known issues.
Portfolio Buddy 2 - Migration Tracker
Migration Status: 40 Features
✅ Completed (36/40 - 90%)
Core features migrated and working:
CSV upload and parsing with PapaParse
Supabase storage integration
Basic metrics calculation (Sharpe, Max DD, CAGR, Win Rate, etc.)
Sortino Ratio (completed commits 258ba3a, 9f25040)
Risk-free rate input (completed commit 258ba3a)
Asset correlation matrix (Spearman & Pearson)
Portfolio comparison charts (Chart.js)
Equity curve visualization
Responsive UI with Tailwind CSS
shadcn/ui color system integration
Date range filtering (completed commit 258ba3a)
Contract multipliers for futures (useContractMultipliers hook)
Advanced multi-column sorting (useSorting hook)
Error handling and validation
File upload progress tracking
Multiple file management
Database Integration (Nov 16, 2025) - PRODUCTION READY ✓
- Python script uploads trades automatically ✓
- New database schema (portfolios, strategies, trades) ✓
- Frontend database fetch ✓ (commits c4fa57c through ee7cec8)
- Dual CSV/Database support ✓
- Format auto-detection (1-row vs 2-row) ✓
- User tested and verified ✓
- Merged to main and deployed ✓
- See:
dev-docs/supabase-migration-plan.md
🚧 In Progress (3/40)
- Advanced filtering - Partial implementation
- Date filtering complete ✓
- Symbol filtering needed
- Strategy filtering needed
- Export functionality - CSV export only
- Excel export pending
- PDF reports pending
- Historical comparison - Backend ready, UI pending
- Need UI for comparing multiple time periods
❌ Not Started (2/40)
- Multi-period analysis - Complex, low priority
- Compare performance across different time windows
- Requires significant UI work
- Risk scenario modeling - Requires new backend logic
- Monte Carlo simulations
- Stress testing
Recent Completed Features
Database Fetch Implementation (Nov 16, 2025) ✅ COMPLETED
Status: Production ready - Tested and deployed
Commits: c4fa57c, a5ce0ec, 676de06, eba4c8d, ee7cec8, ae9202d
Merged to main: d56497a (PR #1)
Implementation Journey (6 commits):
Initial Implementation (c4fa57c)
- Added
calculateMetricsFromDatabase() and buildFilenameFromMetadata() to dataUtils.ts
- Rewrote
fetchFromSupabase() in App.tsx
- Changed from old
csv_files table to new strategies + trades schema
- Added TypeScript interfaces: DatabaseTrade, StrategyMetadata
Fix Query Syntax (a5ce0ec)
- Fixed Supabase order clause syntax error
- Changed
order('trades.trade_date') to order('trade_date') with foreignTable parameter
- Error: "failed to parse order (trades.trade_date.asc)"
Fix Trade Count Limit (676de06)
- Discovered Supabase embedded resource limit (~60 rows)
- Separated queries: fetch strategies first, then fetch trades separately
- Added explicit
.limit(10000) to get all trades
- Fixed: 59 trades → 119 trades ✅
Fix TypeScript Build Errors (eba4c8d)
- Added StrategyFromDB interface with optional
trades? property
- Added DatabaseTrade interface to App.tsx
- Fixed: "Property 'trades' does not exist" errors
Fix Metrics Calculation (ee7cec8) ⭐ CRITICAL FIX
- Auto-detect format: 2-row (Entry/Exit) vs 1-row (database)
- Modified
calculateMetrics() to check for "Entry/Exit" column
- If present → loop by 2 (old CSV format)
- If absent → loop by 1 (new database format)
- Fixed: Metrics now calculated correctly for all 119 trades ✅
Update Documentation (ae9202d)
- Updated migration-tracker skill with implementation details
- Documented all changes and line numbers
Final Results:
- ✅ 119 trades loaded from database (not 59)
- ✅ All metrics calculated correctly (win rate, profit factor, etc.)
- ✅ CSV upload backward compatibility preserved
- ✅ Dual-mode support: both CSV and database work simultaneously
- ✅ Format auto-detection works seamlessly
- ✅ User tested and verified working
- ✅ Deployed to production
Files Modified:
src/utils/dataUtils.ts: +235 lines (functions, interfaces, auto-detection)
src/App.tsx: +145 lines (database fetch, TypeScript types)
.claude/skills/migration-tracker/SKILL.md: Documentation updates
How It Works:
- User clicks "Load Data" button
- App fetches strategies from Supabase
- For each strategy, fetches ALL trades separately (no 60-row limit)
- Builds filename from metadata (e.g., SI_Long_Test_TestStrategy1.csv)
- Transforms to cleanedData format with 3 columns (no Entry/Exit column)
calculateMetrics() auto-detects format and processes correctly
- Pre-populates contract multipliers from database
- Auto-selects strategies and displays metrics/charts
Backward Compatibility:
- ✅ CSV upload with 4 columns (includes Entry/Exit) → 2-row processing
- ✅ Database with 3 columns (no Entry/Exit) → 1-row processing
- ✅ Both formats work simultaneously
- ✅ All existing components, hooks, charts unchanged
Database Integration Planning (Nov 16, 2025)
Status: Planning complete, ready for implementation
What Changed:
- Created comprehensive migration plan (
dev-docs/supabase-migration-plan.md)
- Analyzed new Supabase database schema (portfolios, strategies, trades tables)
- Designed dual-mode support (CSV upload + database fetch)
- Planned data transformation strategy (single-row trades vs entry/exit pairs)
New Database Schema:
portfolios: Portfolio definitions with is_master flag
strategies: Strategy metadata (market, direction, contract_multiplier, etc.)
trades: Individual trade records (trade_date, trade_time, profit)
portfolio_strategies: Links portfolios to strategies
Implementation Plan:
- Add
calculateMetricsFromDatabase() function in dataUtils.ts (~80 lines)
- Update
fetchFromSupabase() query in App.tsx (~60 lines changed)
- Transform database data to match cleanedData format
- Pre-populate contract multipliers from database
- Test with 119 existing trades
Current State:
- Python script on Windows VPS uploads trades automatically ✓
- Database contains 1 strategy with 119 trades ✓
- Frontend still queries old
csv_files table (needs update)
Next Steps:
- Implement Phase 1: New calculation function
- Implement Phase 2: Update Supabase query
- Test dual CSV/Database support
- Deploy to production
Strategy Delete Feature (Nov 19, 2025) ✅
Commit: c372ab7a92d267eda3e540b298872484ef09e38d
Files: App.tsx (+47), MetricsTable.tsx (+18), PortfolioSection.tsx (+8)
What it does:
- Delete database strategies permanently (red trash icon with confirmation)
- Remove CSV strategies from view (gray trash icon, immediate)
- strategyIdMap tracks DB vs CSV (App.tsx line 67)
- handleDeleteStrategy with Supabase deletion (App.tsx lines 423-458)
- Trash2 icon in Actions column (MetricsTable.tsx lines 1, 239-246)
Git Forensic Recovery (Dec 2, 2025) ✅
Problem: Delete feature was "lost" (local repo behind origin/main)
Solution:
git fetch origin
git merge origin/main # Fast-forward to c372ab7
Key lesson: Always check git log origin/main when work seems missing
Sortino Ratio (Oct 2025)
Commits: 258ba3a, 9f25040
What Changed:
- Added risk-free rate input field in PortfolioSection (line 131:
useState<number>(0))
- Implemented inline Sortino calculation in PortfolioSection (lines 133-158)
- Fixed downside deviation calculation (now properly annualized using sqrt(365))
- Corrected variance calculation (divides by total returns, not just negative returns)
- Displays in portfolio stats section (line 535)
Files Modified:
PortfolioSection.tsx: Added riskFreeRate state, downside deviation calculation, and display
Implementation Details:
- NOT in dataUtils.ts - Sortino is calculated inline in PortfolioSection using
useMemo
- NOT in MetricsTable - Only displayed in portfolio stats area
- Kept in component due to portfolio-level context requirements:
- Needs user input (risk-free rate)
- Operates on portfolio daily returns (not trade-level metrics)
- Different calculation scope than win rate, profit factor, etc.
Date Range Filtering (Oct 2025)
Commit: 258ba3a
What Changed:
- usePortfolio hook now accepts date range params
- Filters trades by start/end date
- Recalculates metrics for filtered period only
- UI controls in PortfolioSection
Files Modified:
usePortfolio.ts: Added date filtering logic
PortfolioSection.tsx: Added date picker controls
Enhanced Error Handling (Sept 2025)
Commit: 9fb7fdb
What Changed:
- Better Supabase error messages
- Client validation before upload
- Error list component shows all errors
- Toast notifications for user feedback
Files Modified:
UploadSection.tsx: Enhanced error handling
ErrorList.tsx: New component for error display
usePortfolio.ts: Better error propagation
Current Tech Debt
High Priority
PortfolioSection.tsx is 591 lines (3x the 200-line limit)
- Needs refactoring into:
EquityChartSection.tsx
PortfolioStats.tsx
ContractControls.tsx
- Estimated effort: 4-6 hours
Remove unused Recharts dependency (11.5KB waste)
- Currently using Chart.js
- Recharts never imported anywhere
- Run:
npm uninstall recharts
Fix 15 TypeScript any violations
- usePortfolio.ts: 11 instances
- useMetrics.ts: 4 instances
- dataUtils.ts: 1 instance
- Need proper interfaces for Trade and Metric types
Medium Priority
App.tsx is 351 lines (175% of limit)
- Extract sections into components
- Estimated effort: 2-3 hours
MetricsTable.tsx is 242 lines (121% of limit)
- Improved from 350 lines
- Still over limit, could extract more
No error boundaries implemented
- Should wrap risky components
- Prevents full app crashes
Low Priority
No testing setup
- Should test critical calculations
- Vitest recommended for Vite projects
No CI/CD pipeline
- Manual Cloudflare deployments
- Could automate with GitHub Actions
Known Issues
Issue 1: Supabase 500 Errors
Status: Partially fixed (commit 9fb7fdb)
Root cause: Row limit exceeded on free tier
Current workaround:
- Enhanced error handling shows user-friendly messages
- Batch uploads in smaller chunks recommended
Long-term fix: Implement data aggregation before storage
Issue 2: Large Component Files
Status: Documented but not fixed
Problem: Components grew during migration
Affected:
- PortfolioSection.tsx: 591 lines (was 280, now worse!)
- App.tsx: 351 lines
- MetricsTable.tsx: 242 lines (improved from 350)
Fix needed: Systematic refactoring into smaller components
Issue 3: No Select All Button
Status: Feature doesn't exist
Note: Previous skill version documented a "Select All bug" but this feature was either removed or never implemented. MetricsTable has individual selection but no "Select All" functionality.
Issue 4: Lost/Missing Code
Status: Recoverable via git forensics
Problem: Can't find recently added features or code seems to have disappeared
Solution:
- Check remote:
git log origin/main --oneline -10
- Search commits:
git log --all --grep="keyword"
- Fast-forward if behind:
git merge origin/main
- Use reflog to see recent HEAD positions:
git reflog
Example: On Dec 2, 2025, the delete feature was recovered by fast-forwarding from f4e752a to c372ab7
Migration Priorities (ICE Scored)
| Feature |
Impact |
Confidence |
Ease |
ICE Score |
Status |
| Refactor PortfolioSection |
6 |
8 |
4 |
19.2 |
❌ |
| Remove Recharts |
3 |
10 |
10 |
30 |
❌ |
Fix TypeScript any |
5 |
9 |
6 |
27 |
❌ |
| Export to Excel |
8 |
8 |
7 |
44.8 |
🚧 |
| Advanced filters |
7 |
6 |
5 |
21 |
🚧 |
| Historical comparison UI |
6 |
7 |
4 |
16.8 |
🚧 |
| Error boundaries |
7 |
9 |
8 |
50.4 |
❌ |
| Testing setup |
6 |
8 |
5 |
24 |
❌ |
| Risk scenarios |
5 |
4 |
2 |
4 |
❌ |
Top Priorities by ICE Score:
- Error boundaries (50.4) - High impact, easy to implement
- Export to Excel (44.8) - User-requested feature
- Remove Recharts (30) - Quick win, technical cleanup
- Fix TypeScript violations (27) - Code quality
- Testing setup (24) - Long-term maintainability
What Changed from Old App
Tech Stack Evolution
| Component |
Old App |
New App |
Reason |
| React |
16.x |
19.x |
Latest features, better performance |
| Language |
JavaScript |
TypeScript |
Type safety, better DX |
| Build Tool |
Create React App |
Vite |
10x faster builds, modern |
| Styling |
Material-UI v4 |
Tailwind + shadcn |
More flexible, lighter |
| Charts |
Recharts |
Chart.js |
Better performance, more features |
| State |
Redux |
Plain React hooks |
Simpler, less boilerplate |
| Backend |
Custom Node.js |
Supabase |
Faster development, PostgreSQL |
State Management Migration
- Old: Redux with actions, reducers, middleware (complex)
- New: Plain React hooks (useState, useMemo, useCallback)
- Result: 70% less boilerplate, easier to understand
Note: Skills previously claimed migration to TanStack Query + Zustand, but actual implementation uses plain React hooks only.
Why No Global State Library?
Portfolio Buddy 2 is simple enough to use React's built-in state:
- Small component tree (14 components)
- State rarely shared across distant components
- Custom hooks encapsulate shared logic effectively
- No complex async state management needed
Migration Lessons Learned
What Went Well
- Vite adoption - Build times dropped from 30s to 2s
- TypeScript migration - Caught many bugs early
- Chart.js over Recharts - Better performance with large datasets
- Simplified state - No Redux complexity
- Supabase integration - Fast backend setup
What Could Be Better
- Component size discipline - Let components grow too large
- TypeScript strictness - Too many
any escapes
- Testing from start - No tests written yet (tech debt)
- Code reviews - Need refactoring before more features
- Documentation - Should have updated skills continuously
Migration Velocity
- Weeks 1-4: Core features (upload, parsing, basic metrics)
- Weeks 5-8: Charts, correlation, UI polish
- Weeks 9-12: Advanced features (Sortino, date filtering, sorting)
- Current: Maintenance, refactoring, optimization
Next Steps
Immediate (This Sprint)
- Remove Recharts dependency
- Add error boundaries to risky components
- Fix highest-impact TypeScript
any violations
Short Term (Next 2 Sprints)
- Refactor PortfolioSection into smaller components
- Implement Excel export
- Complete symbol/strategy filtering
Long Term (Next Quarter)
- Set up Vitest testing framework
- Add CI/CD with GitHub Actions
- Multi-period analysis UI
- Risk scenario modeling
Feature Parity Checklist
Comparing to old Portfolio Buddy v1:
| Feature |
Old App |
New App |
Notes |
| CSV Upload |
✅ |
✅ |
Improved error handling |
| Sharpe Ratio |
✅ |
✅ |
Same calculation |
| Sortino Ratio |
✅ |
✅ |
Fixed calculation (9f25040) |
| Max Drawdown |
✅ |
✅ |
Same calculation |
| CAGR |
✅ |
✅ |
Same calculation |
| Correlation Matrix |
✅ |
✅ |
Added Pearson + Spearman |
| Equity Curves |
✅ |
✅ |
Better charts with zoom/pan |
| Contract Multipliers |
❌ |
✅ |
New feature |
| Date Filtering |
❌ |
✅ |
New feature |
| Multi-column Sort |
✅ |
✅ |
Improved with useSorting |
| Export to CSV |
✅ |
✅ |
Same functionality |
| Export to Excel |
✅ |
❌ |
Regression - needs reimplementation |
| Export to PDF |
✅ |
❌ |
Regression - low priority |
| Symbol Filtering |
✅ |
❌ |
Regression - in progress |
| Historical Compare |
✅ |
❌ |
Regression - backend ready |
Parity Status: 85% (11/13 core features complete)
1---2name: migration-tracker3description: Context for ongoing migration from old Portfolio Buddy app. Use when: fixing bugs, adding migrated features, checking feature parity, or understanding why certain code exists. Contains list of 40 feat4---5
6---
7name: migration-tracker
8description: Context for ongoing migration from old Portfolio Buddy app. Use when: fixing bugs, adding migrated features, checking feature parity, or understanding why certain code exists. Contains list of 40 features being migrated and known issues.
9---
10
11# Portfolio Buddy 2 - Migration Tracker
12
13## Migration Status: 40 Features
14
15### ✅ Completed (36/40 - 90%)
16Core features migrated and working:
17- CSV upload and parsing with PapaParse
18- Supabase storage integration
19- Basic metrics calculation (Sharpe, Max DD, CAGR, Win Rate, etc.)
20- **Sortino Ratio** (completed commits 258ba3a, 9f25040)
21- **Risk-free rate input** (completed commit 258ba3a)
22- Asset correlation matrix (Spearman & Pearson)
23- Portfolio comparison charts (Chart.js)
24- Equity curve visualization
25- Responsive UI with Tailwind CSS
26- shadcn/ui color system integration
27- **Date range filtering** (completed commit 258ba3a)
28- **Contract multipliers for futures** (useContractMultipliers hook)
29- **Advanced multi-column sorting** (useSorting hook)
30- Error handling and validation
31- File upload progress tracking
32- Multiple file management
33
34- **Database Integration** (Nov 16, 2025) - PRODUCTION READY ✓
35 - Python script uploads trades automatically ✓
36 - New database schema (portfolios, strategies, trades) ✓
37 - Frontend database fetch ✓ (commits c4fa57c through ee7cec8)
38 - Dual CSV/Database support ✓
39 - Format auto-detection (1-row vs 2-row) ✓
40 - User tested and verified ✓
41 - Merged to main and deployed ✓
42 - **See:** `dev-docs/supabase-migration-plan.md`
43
44### 🚧 In Progress (3/40)
451. **Advanced filtering** - Partial implementation
46 - Date filtering complete ✓
47 - Symbol filtering needed
48 - Strategy filtering needed
492. **Export functionality** - CSV export only
50 - Excel export pending
51 - PDF reports pending
523. **Historical comparison** - Backend ready, UI pending
53 - Need UI for comparing multiple time periods
54
55### ❌ Not Started (2/40)
561. **Multi-period analysis** - Complex, low priority
57 - Compare performance across different time windows
58 - Requires significant UI work
592. **Risk scenario modeling** - Requires new backend logic
60 - Monte Carlo simulations
61 - Stress testing
62
63## Recent Completed Features
64
65### Database Fetch Implementation (Nov 16, 2025) ✅ COMPLETED
66**Status**: Production ready - Tested and deployed
67**Commits**: c4fa57c, a5ce0ec, 676de06, eba4c8d, ee7cec8, ae9202d
68**Merged to main**: d56497a (PR #1)
69
70**Implementation Journey** (6 commits):
71
721. **Initial Implementation** (c4fa57c)
73 - Added `calculateMetricsFromDatabase()` and `buildFilenameFromMetadata()` to dataUtils.ts
74 - Rewrote `fetchFromSupabase()` in App.tsx
75 - Changed from old `csv_files` table to new `strategies` + `trades` schema
76 - Added TypeScript interfaces: DatabaseTrade, StrategyMetadata
77
782. **Fix Query Syntax** (a5ce0ec)
79 - Fixed Supabase order clause syntax error
80 - Changed `order('trades.trade_date')` to `order('trade_date')` with foreignTable parameter
81 - Error: "failed to parse order (trades.trade_date.asc)"
82
833. **Fix Trade Count Limit** (676de06)
84 - Discovered Supabase embedded resource limit (~60 rows)
85 - Separated queries: fetch strategies first, then fetch trades separately
86 - Added explicit `.limit(10000)` to get all trades
87 - Fixed: 59 trades → 119 trades ✅
88
894. **Fix TypeScript Build Errors** (eba4c8d)
90 - Added StrategyFromDB interface with optional `trades?` property
91 - Added DatabaseTrade interface to App.tsx
92 - Fixed: "Property 'trades' does not exist" errors
93
945. **Fix Metrics Calculation** (ee7cec8) ⭐ **CRITICAL FIX**
95 - Auto-detect format: 2-row (Entry/Exit) vs 1-row (database)
96 - Modified `calculateMetrics()` to check for "Entry/Exit" column
97 - If present → loop by 2 (old CSV format)
98 - If absent → loop by 1 (new database format)
99 - Fixed: Metrics now calculated correctly for all 119 trades ✅
100
1016. **Update Documentation** (ae9202d)
102 - Updated migration-tracker skill with implementation details
103 - Documented all changes and line numbers
104
105**Final Results**:
106- ✅ 119 trades loaded from database (not 59)
107- ✅ All metrics calculated correctly (win rate, profit factor, etc.)
108- ✅ CSV upload backward compatibility preserved
109- ✅ Dual-mode support: both CSV and database work simultaneously
110- ✅ Format auto-detection works seamlessly
111- ✅ User tested and verified working
112- ✅ Deployed to production
113
114**Files Modified**:
115- `src/utils/dataUtils.ts`: +235 lines (functions, interfaces, auto-detection)
116- `src/App.tsx`: +145 lines (database fetch, TypeScript types)
117- `.claude/skills/migration-tracker/SKILL.md`: Documentation updates
118
119**How It Works**:
1201. User clicks "Load Data" button
1212. App fetches strategies from Supabase
1223. For each strategy, fetches ALL trades separately (no 60-row limit)
1234. Builds filename from metadata (e.g., SI_Long_Test_TestStrategy1.csv)
1245. Transforms to cleanedData format with 3 columns (no Entry/Exit column)
1256. `calculateMetrics()` auto-detects format and processes correctly
1267. Pre-populates contract multipliers from database
1278. Auto-selects strategies and displays metrics/charts
128
129**Backward Compatibility**:
130- ✅ CSV upload with 4 columns (includes Entry/Exit) → 2-row processing
131- ✅ Database with 3 columns (no Entry/Exit) → 1-row processing
132- ✅ Both formats work simultaneously
133- ✅ All existing components, hooks, charts unchanged
134
135### Database Integration Planning (Nov 16, 2025)
136**Status**: Planning complete, ready for implementation
137**What Changed**:
138- Created comprehensive migration plan (`dev-docs/supabase-migration-plan.md`)
139- Analyzed new Supabase database schema (portfolios, strategies, trades tables)
140- Designed dual-mode support (CSV upload + database fetch)
141- Planned data transformation strategy (single-row trades vs entry/exit pairs)
142
143**New Database Schema**:
144- `portfolios`: Portfolio definitions with is_master flag
145- `strategies`: Strategy metadata (market, direction, contract_multiplier, etc.)
146- `trades`: Individual trade records (trade_date, trade_time, profit)
147- `portfolio_strategies`: Links portfolios to strategies
148
149**Implementation Plan**:
1501. Add `calculateMetricsFromDatabase()` function in dataUtils.ts (~80 lines)
1512. Update `fetchFromSupabase()` query in App.tsx (~60 lines changed)
1523. Transform database data to match cleanedData format
1534. Pre-populate contract multipliers from database
1545. Test with 119 existing trades
155
156**Current State**:
157- Python script on Windows VPS uploads trades automatically ✓
158- Database contains 1 strategy with 119 trades ✓
159- Frontend still queries old `csv_files` table (needs update)
160
161**Next Steps**:
162- Implement Phase 1: New calculation function
163- Implement Phase 2: Update Supabase query
164- Test dual CSV/Database support
165- Deploy to production
166
167### Strategy Delete Feature (Nov 19, 2025) ✅
168**Commit:** c372ab7a92d267eda3e540b298872484ef09e38d
169**Files:** App.tsx (+47), MetricsTable.tsx (+18), PortfolioSection.tsx (+8)
170
171**What it does:**
172- Delete database strategies permanently (red trash icon with confirmation)
173- Remove CSV strategies from view (gray trash icon, immediate)
174- strategyIdMap tracks DB vs CSV (App.tsx line 67)
175- handleDeleteStrategy with Supabase deletion (App.tsx lines 423-458)
176- Trash2 icon in Actions column (MetricsTable.tsx lines 1, 239-246)
177
178### Git Forensic Recovery (Dec 2, 2025) ✅
179**Problem:** Delete feature was "lost" (local repo behind origin/main)
180
181**Solution:**
182```bash
183git fetch origin
184git merge origin/main # Fast-forward to c372ab7
185```
186
187**Key lesson:** Always check `git log origin/main` when work seems missing
188
189### Sortino Ratio (Oct 2025)
190**Commits**: 258ba3a, 9f25040
191**What Changed**:
192- Added risk-free rate input field in PortfolioSection (line 131: `useState<number>(0)`)
193- Implemented inline Sortino calculation in PortfolioSection (lines 133-158)
194- Fixed downside deviation calculation (now properly annualized using sqrt(365))
195- Corrected variance calculation (divides by total returns, not just negative returns)
196- Displays in portfolio stats section (line 535)
197
198**Files Modified**:
199- `PortfolioSection.tsx`: Added riskFreeRate state, downside deviation calculation, and display
200
201**Implementation Details**:
202- **NOT in dataUtils.ts** - Sortino is calculated inline in PortfolioSection using `useMemo`
203- **NOT in MetricsTable** - Only displayed in portfolio stats area
204- Kept in component due to portfolio-level context requirements:
205 - Needs user input (risk-free rate)
206 - Operates on portfolio daily returns (not trade-level metrics)
207 - Different calculation scope than win rate, profit factor, etc.
208
209### Date Range Filtering (Oct 2025)
210**Commit**: 258ba3a
211**What Changed**:
212- usePortfolio hook now accepts date range params
213- Filters trades by start/end date
214- Recalculates metrics for filtered period only
215- UI controls in PortfolioSection
216
217**Files Modified**:
218- `usePortfolio.ts`: Added date filtering logic
219- `PortfolioSection.tsx`: Added date picker controls
220
221### Enhanced Error Handling (Sept 2025)
222**Commit**: 9fb7fdb
223**What Changed**:
224- Better Supabase error messages
225- Client validation before upload
226- Error list component shows all errors
227- Toast notifications for user feedback
228
229**Files Modified**:
230- `UploadSection.tsx`: Enhanced error handling
231- `ErrorList.tsx`: New component for error display
232- `usePortfolio.ts`: Better error propagation
233
234## Current Tech Debt
235
236### High Priority
2371. **PortfolioSection.tsx is 591 lines** (3x the 200-line limit)
238 - Needs refactoring into:
239 - `EquityChartSection.tsx`
240 - `PortfolioStats.tsx`
241 - `ContractControls.tsx`
242 - Estimated effort: 4-6 hours
243
2442. **Remove unused Recharts dependency** (11.5KB waste)
245 - Currently using Chart.js
246 - Recharts never imported anywhere
247 - Run: `npm uninstall recharts`
248
2493. **Fix 15 TypeScript `any` violations**
250 - usePortfolio.ts: 11 instances
251 - useMetrics.ts: 4 instances
252 - dataUtils.ts: 1 instance
253 - Need proper interfaces for Trade and Metric types
254
255### Medium Priority
2564. **App.tsx is 351 lines** (175% of limit)
257 - Extract sections into components
258 - Estimated effort: 2-3 hours
259
2605. **MetricsTable.tsx is 242 lines** (121% of limit)
261 - Improved from 350 lines
262 - Still over limit, could extract more
263
2646. **No error boundaries implemented**
265 - Should wrap risky components
266 - Prevents full app crashes
267
268### Low Priority
2697. **No testing setup**
270 - Should test critical calculations
271 - Vitest recommended for Vite projects
272
2738. **No CI/CD pipeline**
274 - Manual Cloudflare deployments
275 - Could automate with GitHub Actions
276
277## Known Issues
278
279### Issue 1: Supabase 500 Errors
280**Status**: Partially fixed (commit 9fb7fdb)
281**Root cause**: Row limit exceeded on free tier
282**Current workaround**:
283- Enhanced error handling shows user-friendly messages
284- Batch uploads in smaller chunks recommended
285**Long-term fix**: Implement data aggregation before storage
286
287### Issue 2: Large Component Files
288**Status**: Documented but not fixed
289**Problem**: Components grew during migration
290**Affected**:
291- PortfolioSection.tsx: 591 lines (was 280, now worse!)
292- App.tsx: 351 lines
293- MetricsTable.tsx: 242 lines (improved from 350)
294**Fix needed**: Systematic refactoring into smaller components
295
296### Issue 3: No Select All Button
297**Status**: Feature doesn't exist
298**Note**: Previous skill version documented a "Select All bug" but this feature was either removed or never implemented. MetricsTable has individual selection but no "Select All" functionality.
299
300### Issue 4: Lost/Missing Code
301**Status**: Recoverable via git forensics
302**Problem**: Can't find recently added features or code seems to have disappeared
303**Solution**:
3041. Check remote: `git log origin/main --oneline -10`
3052. Search commits: `git log --all --grep="keyword"`
3063. Fast-forward if behind: `git merge origin/main`
3074. Use reflog to see recent HEAD positions: `git reflog`
308**Example**: On Dec 2, 2025, the delete feature was recovered by fast-forwarding from f4e752a to c372ab7
309
310## Migration Priorities (ICE Scored)
311
312| Feature | Impact | Confidence | Ease | ICE Score | Status |
313|---------|--------|------------|------|-----------|--------|
314| Refactor PortfolioSection | 6 | 8 | 4 | 19.2 | ❌ |
315| Remove Recharts | 3 | 10 | 10 | 30 | ❌ |
316| Fix TypeScript `any` | 5 | 9 | 6 | 27 | ❌ |
317| Export to Excel | 8 | 8 | 7 | 44.8 | 🚧 |
318| Advanced filters | 7 | 6 | 5 | 21 | 🚧 |
319| Historical comparison UI | 6 | 7 | 4 | 16.8 | 🚧 |
320| Error boundaries | 7 | 9 | 8 | 50.4 | ❌ |
321| Testing setup | 6 | 8 | 5 | 24 | ❌ |
322| Risk scenarios | 5 | 4 | 2 | 4 | ❌ |
323
324**Top Priorities by ICE Score**:
3251. Error boundaries (50.4) - High impact, easy to implement
3262. Export to Excel (44.8) - User-requested feature
3273. Remove Recharts (30) - Quick win, technical cleanup
3284. Fix TypeScript violations (27) - Code quality
3295. Testing setup (24) - Long-term maintainability
330
331## What Changed from Old App
332
333### Tech Stack Evolution
334| Component | Old App | New App | Reason |
335|-----------|---------|---------|--------|
336| React | 16.x | 19.x | Latest features, better performance |
337| Language | JavaScript | TypeScript | Type safety, better DX |
338| Build Tool | Create React App | Vite | 10x faster builds, modern |
339| Styling | Material-UI v4 | Tailwind + shadcn | More flexible, lighter |
340| Charts | Recharts | Chart.js | Better performance, more features |
341| State | Redux | Plain React hooks | Simpler, less boilerplate |
342| Backend | Custom Node.js | Supabase | Faster development, PostgreSQL |
343
344### State Management Migration
345- **Old**: Redux with actions, reducers, middleware (complex)
346- **New**: Plain React hooks (useState, useMemo, useCallback)
347- **Result**: 70% less boilerplate, easier to understand
348
349**Note**: Skills previously claimed migration to TanStack Query + Zustand, but actual implementation uses plain React hooks only.
350
351### Why No Global State Library?
352Portfolio Buddy 2 is simple enough to use React's built-in state:
353- Small component tree (14 components)
354- State rarely shared across distant components
355- Custom hooks encapsulate shared logic effectively
356- No complex async state management needed
357
358## Migration Lessons Learned
359
360### What Went Well
3611. **Vite adoption** - Build times dropped from 30s to 2s
3622. **TypeScript migration** - Caught many bugs early
3633. **Chart.js over Recharts** - Better performance with large datasets
3644. **Simplified state** - No Redux complexity
3655. **Supabase integration** - Fast backend setup
366
367### What Could Be Better
3681. **Component size discipline** - Let components grow too large
3692. **TypeScript strictness** - Too many `any` escapes
3703. **Testing from start** - No tests written yet (tech debt)
3714. **Code reviews** - Need refactoring before more features
3725. **Documentation** - Should have updated skills continuously
373
374### Migration Velocity
375- **Weeks 1-4**: Core features (upload, parsing, basic metrics)
376- **Weeks 5-8**: Charts, correlation, UI polish
377- **Weeks 9-12**: Advanced features (Sortino, date filtering, sorting)
378- **Current**: Maintenance, refactoring, optimization
379
380## Next Steps
381
382### Immediate (This Sprint)
3831. Remove Recharts dependency
3842. Add error boundaries to risky components
3853. Fix highest-impact TypeScript `any` violations
386
387### Short Term (Next 2 Sprints)
3881. Refactor PortfolioSection into smaller components
3892. Implement Excel export
3903. Complete symbol/strategy filtering
391
392### Long Term (Next Quarter)
3931. Set up Vitest testing framework
3942. Add CI/CD with GitHub Actions
3953. Multi-period analysis UI
3964. Risk scenario modeling
397
398## Feature Parity Checklist
399
400Comparing to old Portfolio Buddy v1:
401
402| Feature | Old App | New App | Notes |
403|---------|---------|---------|-------|
404| CSV Upload | ✅ | ✅ | Improved error handling |
405| Sharpe Ratio | ✅ | ✅ | Same calculation |
406| Sortino Ratio | ✅ | ✅ | **Fixed** calculation (9f25040) |
407| Max Drawdown | ✅ | ✅ | Same calculation |
408| CAGR | ✅ | ✅ | Same calculation |
409| Correlation Matrix | ✅ | ✅ | Added Pearson + Spearman |
410| Equity Curves | ✅ | ✅ | Better charts with zoom/pan |
411| Contract Multipliers | ❌ | ✅ | **New feature** |
412| Date Filtering | ❌ | ✅ | **New feature** |
413| Multi-column Sort | ✅ | ✅ | **Improved** with useSorting |
414| Export to CSV | ✅ | ✅ | Same functionality |
415| Export to Excel | ✅ | ❌ | **Regression** - needs reimplementation |
416| Export to PDF | ✅ | ❌ | **Regression** - low priority |
417| Symbol Filtering | ✅ | ❌ | **Regression** - in progress |
418| Historical Compare | ✅ | ❌ | **Regression** - backend ready |
419
420**Parity Status**: 85% (11/13 core features complete)