# Feature: Opportunity Cost Summary Boxes
## Overview
Added two new summary boxes that appear when viewing sold positions, showing:
1. **Missed Gains** (Potential Losses) - Stocks sold too early
2. **Avoided Losses** (Potential Profits) - Stocks sold at good timing
**Date**: January 1, 2026
**Status**: ✅ Complete
---
## What This Feature Does
### For Sold Holdings
When you view sold positions, you'll now see two additional summary boxes that help you understand the impact of your selling decisions:
#### 1. ⚠️ Missed Gains (Orange Box)
**Shows**: Total amount of gains you missed by selling too early
**Example**:
```
┌─────────────────────────────┐
│ ⚠️ Missed Gains │
│ -₹45,000 │
│ 3 stocks sold too early │
└─────────────────────────────┘
```
**Meaning**: If you had held these 3 stocks until today, you would have made an additional ₹45,000.
**When it appears**: Only when `statusFilter` is "Sold Holdings" or "All Positions" AND there are stocks with negative opportunity cost.
---
#### 2. ✅ Avoided Losses (Green Box)
**Shows**: Total amount of losses you avoided by selling at the right time
**Example**:
```
┌─────────────────────────────┐
│ ✅ Avoided Losses │
│ +₹28,000 │
│ 2 stocks sold at good timing│
└─────────────────────────────┘
```
**Meaning**: These 2 stocks fell after you sold them. By selling when you did, you avoided ₹28,000 in losses.
**When it appears**: Only when `statusFilter` is "Sold Holdings" or "All Positions" AND there are stocks with positive opportunity cost.
---
## Technical Implementation
### Backend API Changes
**File**: `equity/app/api/tradebook/route.ts`
**New Summary Fields**:
```typescript
summary: {
// ... existing fields ...
potentialLosses: number; // Total missed gains (absolute value)
potentialProfits: number; // Total avoided losses
soldEarlyCount: number; // Count of stocks sold too early
soldWellCount: number; // Count of stocks sold well
}
```
**Calculation Logic**:
```typescript
// Filter sold positions with opportunity cost data
const soldWithOpportunityCost = soldGroups.filter(g =>
g.opportunityCost !== undefined && g.currentPrice > 0
);
// Potential losses = Sum of negative opportunity costs (as absolute values)
const potentialLosses = soldWithOpportunityCost
.filter(g => g.opportunityCost! < 0)
.reduce((sum, g) => sum + Math.abs(g.opportunityCost!), 0);
// Potential profits = Sum of positive opportunity costs
const potentialProfits = soldWithOpportunityCost
.filter(g => g.opportunityCost! > 0)
.reduce((sum, g) => sum + g.opportunityCost!, 0);
// Count stocks in each category
const soldEarlyCount = soldWithOpportunityCost
.filter(g => g.opportunityCost! < 0).length;
const soldWellCount = soldWithOpportunityCost
.filter(g => g.opportunityCost! > 0).length;
```
---
### Frontend Changes
**File**: `equity/app/tradebook/page.tsx`
**Interface Update**:
```typescript
interface TradebookData {
groups: TradeGroup[];
summary: {
// ... existing fields ...
potentialLosses: number;
potentialProfits: number;
soldEarlyCount: number;
soldWellCount: number;
};
}
```
**UI Components**:
Two new conditional summary boxes added after the Unrealized P&L box.
---
## Visual Design
### Missed Gains Box
- **Border**: `border-orange-500` (orange left border)
- **Icon**: ⚠️ Warning emoji
- **Amount Color**: `text-orange-600` (orange for caution)
- **Format**: Shows as negative (e.g., `-₹45,000`)
- **Subtitle**: Shows count of stocks sold too early
### Avoided Losses Box
- **Border**: `border-green-500` (green left border)
- **Icon**: ✅ Checkmark emoji
- **Amount Color**: `text-green-600` (green for success)
- **Format**: Shows as positive (e.g., `+₹28,000`)
- **Subtitle**: Shows count of stocks sold at good timing
---
## Display Logic
### When Boxes Appear
| Status Filter | Missed Gains | Avoided Losses |
|--------------|--------------|----------------|
| Active Holdings | ❌ Hidden | ❌ Hidden |
| Sold Holdings | ✅ Shown (if > 0) | ✅ Shown (if > 0) |
| All Positions | ✅ Shown (if > 0) | ✅ Shown (if > 0) |
**Note**: Boxes only appear if the value is > 0. If there are no missed gains, the orange box won't show. Same for avoided losses.
---
## Example Scenarios
### Scenario 1: Mixed Results
**Portfolio**:
- TCS: Sold @ ₹3,000, Now ₹4,000 → Missed ₹20,000
- INFY: Sold @ ₹1,500, Now ₹1,200 → Avoided ₹10,000 loss
- RELIANCE: Sold @ ₹2,500, Now ₹3,000 → Missed ₹25,000
**Summary Boxes**:
```
┌─────────────────────────────┐ ┌─────────────────────────────┐
│ ⚠️ Missed Gains │ │ ✅ Avoided Losses │
│ -₹45,000 │ │ +₹10,000 │
│ 2 stocks sold too early │ │ 1 stock sold at good timing │
└─────────────────────────────┘ └─────────────────────────────┘
```
**Interpretation**:
- You missed out on ₹45K by selling TCS and RELIANCE early
- But you avoided ₹10K loss by selling INFY at the right time
- **Net opportunity cost**: -₹35K (could have been ₹35K better)
---
### Scenario 2: All Good Timing
**Portfolio**:
- HDFC: Sold @ ₹1,600, Now ₹1,400 → Avoided ₹15,000 loss
- ICICI: Sold @ ₹900, Now ₹800 → Avoided ₹8,000 loss
**Summary Boxes**:
```
┌─────────────────────────────┐
│ ✅ Avoided Losses │
│ +₹23,000 │
│ 2 stocks sold at good timing│
└─────────────────────────────┘
```
**Interpretation**:
- No orange box (no missed gains)
- You timed your exits perfectly
- Avoided ₹23K in losses by selling before prices fell
---
### Scenario 3: All Sold Too Early
**Portfolio**:
- SBIN: Sold @ ₹500, Now ₹600 → Missed ₹12,000
- PNB: Sold @ ₹80, Now ₹100 → Missed ₹18,000
**Summary Boxes**:
```
┌─────────────────────────────┐
│ ⚠️ Missed Gains │
│ -₹30,000 │
│ 2 stocks sold too early │
└─────────────────────────────┘
```
**Interpretation**:
- No green box (no avoided losses)
- You sold both stocks too early
- Missed ₹30K of additional gains
---
## Understanding the Numbers
### What is "Opportunity Cost"?
**Definition**: The difference between what you got by selling and what you would have if you kept holding.
**Formula**:
```
Opportunity Cost = Actual Sale Value - Current Value If Held
If negative: You sold too early (missed gains)
If positive: You sold well (avoided losses)
```
### Example Calculation
**Stock: RELIANCE**
- Bought: 100 shares @ ₹2,000 = ₹2,00,000
- Sold: 100 shares @ ₹2,500 = ₹2,50,000
- Realized Profit: ₹50,000 ✅
**But today**:
- Current Price: ₹3,000
- Value If Held: 100 × ₹3,000 = ₹3,00,000
**Opportunity Cost**:
```
₹2,50,000 (what you got) - ₹3,00,000 (what it's worth now)
= -₹50,000
Interpretation: You made ₹50K profit, but missed another ₹50K
```
This -₹50,000 contributes to the **"Missed Gains"** box.
---
## User Benefits
### 1. Learning from Past Decisions
- See which exits were timed well vs poorly
- Identify patterns in your selling behavior
- Improve future exit strategies
### 2. Emotional Context
- **Orange box large?** Don't feel too bad—hindsight is 20/20
- **Green box large?** Celebrate your good timing!
- **Both present?** Mixed results are normal
### 3. Portfolio Review
- Understand total impact of selling decisions
- Compare to realized profits
- Decide if you need to adjust exit strategy
---
## Important Notes
### 1. Hindsight is 20/20
**Don't beat yourself up over missed gains!**
You may have sold for good reasons:
- Needed the cash
- Risk management (concentration)
- Portfolio rebalancing
- Lock in profits before volatility
**The orange box doesn't mean you made a mistake.** It's just data.
---
### 2. Context Matters
**Example**:
```
Missed Gains: -₹50,000
Realized P&L: +₹2,00,000
```
**Interpretation**: You made ₹2L profit but could have made ₹2.5L. That's still a GREAT result!
---
### 3. Not All Stocks Have Data
The boxes only include sold positions where:
- ✅ Current price is available
- ✅ Opportunity cost was calculated
Stocks without current prices are excluded from these calculations.
---
## Use Cases
### Tax Planning Review
**Question**: "Were my tax-loss harvesting sales well-timed?"
**Answer**: Check the boxes:
- Large green box = Good timing, losses avoided
- Large orange box = May want to reconsider strategy
---
### Performance Analysis
**Question**: "How good am I at timing exits?"
**Answer**: Compare the two boxes:
- Green > Orange = Generally good timing
- Orange > Green = May need to hold longer
- Both small = Timing is okay, not much impact
---
### Learning & Improvement
**Question**: "What can I learn from past sales?"
**Steps**:
1. Sort by "Opportunity Cost" (ascending)
2. Review stocks with largest missed gains
3. Ask: "Why did I sell?" "What signals did I miss?"
4. Adjust exit strategy accordingly
---
## Configuration
### Show/Hide Boxes
Currently controlled by data presence. Boxes auto-hide if:
- Value is 0 or undefined
- Viewing Active Holdings only
### Thresholds
No minimum threshold currently. Even ₹1 will show the box.
**Future Enhancement**: Add minimum threshold setting (e.g., only show if > ₹5,000)
---
## Performance Impact
### Backend
- ✅ Minimal: Simple filter and reduce operations
- ✅ Uses already-calculated opportunity cost values
- ✅ No additional API calls
### Frontend
- ✅ Negligible: Just two conditional div elements
- ✅ No impact on render performance
- ✅ No additional state management
---
## Testing Checklist
### Functional
- [ ] Orange box appears when there are stocks sold too early
- [ ] Green box appears when there are stocks sold at good timing
- [ ] Boxes hidden when viewing Active Holdings only
- [ ] Count values are correct
- [ ] Amount calculations are accurate
- [ ] Boxes hide when values are 0
### Visual
- [ ] Orange box has warning emoji and orange styling
- [ ] Green box has checkmark emoji and green styling
- [ ] Text is readable and aligned properly
- [ ] Responsive on mobile (may need scroll)
### Edge Cases
- [ ] No sold positions (boxes don't appear)
- [ ] All sold positions missing current prices (boxes don't appear)
- [ ] Mixed active and sold positions (boxes show correctly)
- [ ] Very large numbers (formatting works)
---
## Future Enhancements
### Phase 2
- [ ] Minimum threshold setting
- [ ] Percentage view (% of total realized P&L)
- [ ] Drill-down: Click box to see contributing stocks
- [ ] Historical tracking: Show trend over time
### Phase 3
- [ ] Comparison to market index (was it worth selling?)
- [ ] Notification if opportunity cost > certain threshold
- [ ] Export opportunity cost data
- [ ] Machine learning: Suggest optimal exit timing
---
## Feedback Questions
1. Are these boxes helpful for your decision-making?
2. Should we add more details (e.g., top 3 contributors)?
3. Is the wording clear ("Missed Gains" vs "Avoided Losses")?
4. Would you like filters to hide/show these boxes?
---
**Status**: ✅ Ready for Testing
**Files Modified**: 2
**New API Fields**: 4
**New UI Components**: 2 summary boxes