# Enhancement: Added Original Cost to Opportunity Cost Summary Boxes
## Overview
Enhanced the opportunity cost summary boxes to include the **original cost (investment)** for stocks in each category, providing better financial context.
**Date**: January 1, 2026
**Status**: ✅ Complete
---
## What Changed
### Visual Updates
#### Before (Without Original Cost)
```
┌─────────────────────────────┐
│ ⚠️ Missed Gains │
│ -₹45,000 │
│ 3 stocks sold too early │
└─────────────────────────────┘
```
#### After (With Original Cost)
```
┌─────────────────────────────┐
│ ⚠️ Missed Gains │
│ -₹45,000 │
│ 3 stocks sold too early │
│ ───────────────────────── │
│ Original Cost: ₹2,00,000 │
└─────────────────────────────┘
```
---
## Benefits
### Better Context
Now you can see:
- **What you missed**: ₹45,000 (opportunity cost)
- **Relative to what**: ₹2,00,000 (original investment)
- **Impact**: 22.5% additional return missed
### Decision Making
Helps answer questions like:
- "Is ₹45K a lot relative to my investment?"
- "What percentage return did I miss?"
- "Should I adjust my strategy for similar-sized positions?"
---
## Example Scenarios
### Scenario 1: Small Missed Gain on Large Investment
```
┌─────────────────────────────┐
│ ⚠️ Missed Gains │
│ -₹10,000 │
│ 2 stocks sold too early │
│ ───────────────────────── │
│ Original Cost: ₹5,00,000 │
└─────────────────────────────┘
```
**Interpretation**:
- Missed only 2% additional return (10K / 500K)
- Not too bad! Timing was reasonably good
- Strategy doesn't need major adjustment
---
### Scenario 2: Large Missed Gain on Small Investment
```
┌─────────────────────────────┐
│ ⚠️ Missed Gains │
│ -₹50,000 │
│ 1 stock sold too early │
│ ───────────────────────── │
│ Original Cost: ₹1,00,000 │
└─────────────────────────────┘
```
**Interpretation**:
- Missed 50% additional return! (50K / 100K)
- Significant timing miss
- Review exit strategy for high-growth stocks
- Could have 1.5x the profit
---
### Scenario 3: Avoided Large Loss
```
┌─────────────────────────────┐
│ ✅ Avoided Losses │
│ +₹80,000 │
│ 2 stocks sold at good timing│
│ ───────────────────────── │
│ Original Cost: ₹2,50,000 │
└─────────────────────────────┘
```
**Interpretation**:
- Avoided 32% loss! (80K / 250K)
- Excellent timing on exits
- Strategy worked well
- Preserved capital effectively
---
## Technical Implementation
### Backend Changes
**File**: `equity/app/api/tradebook/route.ts`
**Added Calculations**:
```typescript
// For stocks sold too early
const stocksSoldEarly = soldWithOpportunityCost.filter(g => g.opportunityCost! < 0);
const soldEarlyInvestment = stocksSoldEarly.reduce((sum, g) => sum + g.totalBuyValue, 0);
// For stocks sold at good timing
const stocksSoldWell = soldWithOpportunityCost.filter(g => g.opportunityCost! > 0);
const soldWellInvestment = stocksSoldWell.reduce((sum, g) => sum + g.totalBuyValue, 0);
```
**New Summary Fields**:
```typescript
summary: {
// ... existing fields ...
soldEarlyInvestment: number, // Original cost of stocks sold too early
soldWellInvestment: number, // Original cost of stocks sold at good timing
}
```
---
### Frontend Changes
**File**: `equity/app/tradebook/page.tsx`
**Interface Update**:
```typescript
interface TradebookData {
summary: {
// ... existing fields ...
soldEarlyInvestment: number;
soldWellInvestment: number;
};
}
```
**Visual Display**:
```tsx
<div className="text-xs text-gray-700 mt-1 pt-1 border-t border-gray-200">
Original Cost: {formatCurrency(data.summary.soldEarlyInvestment)}
</div>
```
---
## Visual Design
### Separator Line
- Added subtle border-top (`border-t border-gray-200`)
- Separates original cost from other info
- Maintains visual hierarchy
### Text Styling
- `text-xs` - Small font (12px)
- `text-gray-700` - Darker than count text (more important)
- `mt-1 pt-1` - Margin and padding for spacing
### Layout
```
Title (text-sm, gray-600)
Amount (text-lg, bold, orange/green)
Count (text-xs, gray-500)
───────── (separator line)
Original Cost (text-xs, gray-700) ← NEW
```
---
## Calculation Details
### What is "Original Cost"?
**Definition**: The `totalBuyValue` of all stocks in that category
**Formula**:
```
Original Cost = Sum of (Buy Quantity × Buy Price) for all stocks in category
```
### Example Calculation
**Stocks Sold Too Early**:
```
TCS: 100 shares × ₹3,000 = ₹3,00,000
RELIANCE: 50 shares × ₹2,000 = ₹1,00,000
INFY: 200 shares × ₹1,500 = ₹3,00,000
────────────────────────────────────────────
Original Cost (Sold Early): ₹7,00,000
```
**Stocks Sold at Good Timing**:
```
HDFC: 100 shares × ₹1,500 = ₹1,50,000
ICICI: 150 shares × ₹800 = ₹1,20,000
────────────────────────────────────────────
Original Cost (Good Timing): ₹2,70,000
```
---
## Use Cases
### 1. Risk Assessment
**Question**: "How much risk did I take that led to missed gains?"
**Answer**:
```
Missed Gains: -₹45,000
Original Cost: ₹2,00,000
Risk-adjusted impact: 22.5%
```
**Insight**: Moderate risk, moderate miss.
---
### 2. Strategy Evaluation
**Question**: "Are my exits too conservative for small positions?"
**Analysis**:
```
Missed Gains: -₹5,000 (small absolute)
Original Cost: ₹20,000 (small position)
Percentage: 25% (large relative!)
```
**Insight**: Even small positions show timing issues. Consider holding longer.
---
### 3. Portfolio Comparison
**Question**: "Did I do better timing exits on large or small positions?"
**Large Positions**:
```
Missed: -₹80,000
Cost: ₹10,00,000
Impact: 8%
```
**Small Positions**:
```
Missed: -₹20,000
Cost: ₹50,000
Impact: 40%
```
**Insight**: Better timing on large positions. Need to improve on small ones.
---
### 4. Validation of Good Exits
**Question**: "How good was my timing really?"
**Example**:
```
Avoided: +₹1,20,000
Cost: ₹5,00,000
Protected: 24% of capital
```
**Insight**: Excellent exits! Saved nearly a quarter of invested capital.
---
## Complete Box Examples
### Missed Gains Box (Full)
```
┌────────────────────────────────────────┐
│ ⚠️ Missed Gains │
│ │
│ -₹45,000 │ ← Opportunity cost
│ │
│ 3 stocks sold too early │ ← Count
│ ──────────────────────────────────────│ ← Separator
│ Original Cost: ₹2,00,000 │ ← Investment context
└────────────────────────────────────────┘
Calculation:
- Missed gain: ₹45,000
- Investment: ₹2,00,000
- Return missed: 22.5%
```
---
### Avoided Losses Box (Full)
```
┌────────────────────────────────────────┐
│ ✅ Avoided Losses │
│ │
│ +₹28,000 │ ← Avoided loss
│ │
│ 2 stocks sold at good timing │ ← Count
│ ──────────────────────────────────────│ ← Separator
│ Original Cost: ₹1,50,000 │ ← Investment context
└────────────────────────────────────────┘
Calculation:
- Avoided loss: ₹28,000
- Investment: ₹1,50,000
- Loss avoided: 18.7% of capital
```
---
## Real-World Comparison
### Before Enhancement
**User sees**: "-₹45,000 missed gains"
**Questions**:
- Is that a lot?
- How does it compare to my investment?
- Should I be concerned?
### After Enhancement
**User sees**: "-₹45,000 missed gains on ₹2,00,000 investment"
**Immediate understanding**:
- 22.5% additional return missed
- Moderate impact (not catastrophic)
- Room for timing improvement
- Context for decision-making
---
## Additional Insights Enabled
### ROI on Missed Opportunities
```
Missed Gains / Original Cost = Missed ROI %
Example:
₹45,000 / ₹2,00,000 = 22.5% additional return missed
```
### Efficiency of Exits
```
Avoided Losses / Original Cost = Protection %
Example:
₹28,000 / ₹1,50,000 = 18.7% of capital protected
```
### Net Opportunity Impact
```
(Avoided - Missed) / (Early Cost + Well Cost) = Net Impact %
Example:
(₹28,000 - ₹45,000) / (₹2,00,000 + ₹1,50,000)
= -₹17,000 / ₹3,50,000
= -4.86% net impact
```
**Interpretation**: Overall, timing cost you 4.86% across all sold positions.
---
## Testing Checklist
### Functional
- [ ] Original cost displays correctly for missed gains
- [ ] Original cost displays correctly for avoided losses
- [ ] Values match sum of totalBuyValue for respective stocks
- [ ] Formatting is consistent with other currency displays
### Visual
- [ ] Separator line visible and subtle
- [ ] Text size is readable (12px)
- [ ] Spacing is adequate (mt-1 pt-1)
- [ ] Color (gray-700) is appropriate
- [ ] Alignment matches other elements
### Edge Cases
- [ ] Single stock in category (singular "stock")
- [ ] Very large original cost (formatting works)
- [ ] Very small original cost (no display issues)
- [ ] Zero cost (shouldn't happen, but handle gracefully)
---
## Future Enhancements
### Phase 2
- [ ] Show percentage directly in box
```
Missed Gains: -₹45,000 (22.5%)
Original Cost: ₹2,00,000
```
- [ ] Breakdown by stock
```
Click to see:
- TCS: -₹20K (33%)
- RELIANCE: -₹25K (25%)
```
- [ ] Trend over time
```
This quarter: 22.5% missed
Last quarter: 15.2% missed
Trend: ↑ Getting worse
```
### Phase 3
- [ ] Comparative analysis
```
Your missed: 22.5%
Avg user: 18.3%
You're: 4.2% above average
```
- [ ] Actionable insights
```
💡 Tip: Your exits on tech stocks
are typically 30% early. Consider
holding 20% longer.
```
---
## Performance Impact
### Backend
- ✅ Minimal: Uses already-filtered arrays
- ✅ Simple reduce operation (O(n))
- ✅ No additional API calls
### Frontend
- ✅ Negligible: Just one additional line per box
- ✅ No state changes
- ✅ No re-render triggers
---
## Migration Notes
### Backward Compatibility
- ✅ No breaking changes
- ✅ New fields are additions, not replacements
- ✅ Old API clients will ignore new fields
- ✅ Frontend gracefully handles missing data
### Deployment
1. Deploy API changes first
2. Verify new fields in API response
3. Deploy frontend changes
4. Test end-to-end
5. Monitor for issues
---
## Summary
**Added**: Original cost context to opportunity cost boxes
**Benefits**:
- Better understanding of relative impact
- Improved decision-making context
- Ability to calculate missed/avoided percentages
- More meaningful portfolio insights
**Impact**:
- 2 new API summary fields
- 2 visual enhancements (one line each)
- No performance degradation
- Better user experience
**Status**: ✅ Ready for testing and deployment
---
**Last Updated**: January 1, 2026
**Version**: 1.1
**Component**: Opportunity Cost Summary Boxes