Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

portfolio tab update

tilakpatel2252b22205f914
diff --git a/fincept-terminal-desktop/src/components/tabs/PortfolioTab.tsx b/fincept-terminal-desktop/src/components/tabs/PortfolioTab.tsx
index b61d7660d..53420a29b 100644
--- a/fincept-terminal-desktop/src/components/tabs/PortfolioTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/PortfolioTab.tsx
@@ -1,39 +1,69 @@
import React, { useState, useEffect } from 'react';
-
-interface Position {
- ticker: string;
- name: string;
- quantity: number;
- avgPrice: number;
- currentPrice: number;
- marketValue: number;
- costBasis: number;
- unrealizedPnL: number;
- unrealizedPnLPercent: number;
- dayChange: number;
- dayChangePercent: number;
- weight: number;
- sector: string;
-}
+import { Plus, Download, RefreshCw, Trash2, BarChart3, PieChart } from 'lucide-react';
+import {
+ portfolioService,
+ Portfolio,
+ PortfolioSummary,
+ Transaction
+} from '../../services/portfolioService';
+import PositionsView from './portfolio/PositionsView';
+import HistoryView from './portfolio/HistoryView';
+import AnalyticsView from './portfolio/AnalyticsView';
+import SectorsView from './portfolio/SectorsView';
+import PerformanceView from './portfolio/PerformanceView';
+import RiskMetricsView from './portfolio/RiskMetricsView';
+import ReportsView from './portfolio/ReportsView';
+import AlertsView from './portfolio/AlertsView';
+import { BLOOMBERG_COLORS, formatCurrency, formatPercent, formatNumber } from './portfolio/utils';
const PortfolioTab: React.FC = () => {
const [currentTime, setCurrentTime] = useState(new Date());
+ const [portfolios, setPortfolios] = useState<Portfolio[]>([]);
+ const [selectedPortfolio, setSelectedPortfolio] = useState<Portfolio | null>(null);
+ const [portfolioSummary, setPortfolioSummary] = useState<PortfolioSummary | null>(null);
+ const [transactions, setTransactions] = useState<Transaction[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [refreshing, setRefreshing] = useState(false);
const [selectedView, setSelectedView] = useState('POSITIONS');
- const [sortBy, setSortBy] = useState('WEIGHT');
-
- // Bloomberg color scheme
- const BLOOMBERG_ORANGE = '#FFA500';
- const BLOOMBERG_WHITE = '#FFFFFF';
- const BLOOMBERG_RED = '#FF0000';
- const BLOOMBERG_GREEN = '#00C800';
- const BLOOMBERG_YELLOW = '#FFFF00';
- const BLOOMBERG_GRAY = '#787878';
- const BLOOMBERG_BLUE = '#6496FA';
- const BLOOMBERG_PURPLE = '#C864FF';
- const BLOOMBERG_CYAN = '#00FFFF';
- const BLOOMBERG_DARK_BG = '#000000';
- const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ // Modal states
+ const [showCreatePortfolio, setShowCreatePortfolio] = useState(false);
+ const [showAddAsset, setShowAddAsset] = useState(false);
+ const [showSellAsset, setShowSellAsset] = useState(false);
+
+ // Form states
+ const [newPortfolioName, setNewPortfolioName] = useState('');
+ const [newPortfolioOwner, setNewPortfolioOwner] = useState('');
+ const [newPortfolioCurrency, setNewPortfolioCurrency] = useState('USD');
+
+ const [addAssetSymbol, setAddAssetSymbol] = useState('');
+ const [addAssetQuantity, setAddAssetQuantity] = useState('');
+ const [addAssetPrice, setAddAssetPrice] = useState('');
+
+ const [sellAssetSymbol, setSellAssetSymbol] = useState('');
+ const [sellAssetQuantity, setSellAssetQuantity] = useState('');
+ const [sellAssetPrice, setSellAssetPrice] = useState('');
+
+ // Bloomberg colors from utils
+ const { ORANGE, WHITE, RED, GREEN, GRAY, DARK_BG, PANEL_BG, CYAN, YELLOW } = BLOOMBERG_COLORS;
+
+ // Initialize service and load portfolios
+ useEffect(() => {
+ const initService = async () => {
+ setLoading(true);
+ try {
+ await portfolioService.initialize();
+ await loadPortfolios();
+ } catch (error) {
+ console.error('[PortfolioTab] Initialization error:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+ initService();
+ }, []);
+
+ // Update time
useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(new Date());
@@ -41,572 +71,941 @@ const PortfolioTab: React.FC = () => {
return () => clearInterval(timer);
}, []);
- const positions: Position[] = [
- {
- ticker: 'AAPL',
- name: 'Apple Inc.',
- quantity: 250,
- avgPrice: 165.50,
- currentPrice: 184.92,
- marketValue: 46230.00,
- costBasis: 41375.00,
- unrealizedPnL: 4855.00,
- unrealizedPnLPercent: 11.73,
- dayChange: 462.30,
- dayChangePercent: 1.01,
- weight: 28.5,
- sector: 'Technology'
- },
- {
- ticker: 'MSFT',
- name: 'Microsoft Corporation',
- quantity: 120,
- avgPrice: 340.00,
- currentPrice: 378.45,
- marketValue: 45414.00,
- costBasis: 40800.00,
- unrealizedPnL: 4614.00,
- unrealizedPnLPercent: 11.31,
- dayChange: 454.14,
- dayChangePercent: 1.01,
- weight: 28.0,
- sector: 'Technology'
- },
- {
- ticker: 'NVDA',
- name: 'NVIDIA Corporation',
- quantity: 75,
- avgPrice: 450.00,
- currentPrice: 501.23,
- marketValue: 37592.25,
- costBasis: 33750.00,
- unrealizedPnL: 3842.25,
- unrealizedPnLPercent: 11.39,
- dayChange: 375.92,
- dayChangePercent: 1.01,
- weight: 23.2,
- sector: 'Semiconductors'
- },
- {
- ticker: 'GOOGL',
- name: 'Alphabet Inc.',
- quantity: 150,
- avgPrice: 125.00,
- currentPrice: 134.56,
- marketValue: 20184.00,
- costBasis: 18750.00,
- unrealizedPnL: 1434.00,
- unrealizedPnLPercent: 7.65,
- dayChange: 201.84,
- dayChangePercent: 1.01,
- weight: 12.4,
- sector: 'Technology'
- },
- {
- ticker: 'TSLA',
- name: 'Tesla Inc.',
- quantity: 50,
- avgPrice: 225.00,
- currentPrice: 251.78,
- marketValue: 12589.00,
- costBasis: 11250.00,
- unrealizedPnL: 1339.00,
- unrealizedPnLPercent: 11.90,
- dayChange: 125.89,
- dayChangePercent: 1.01,
- weight: 7.8,
- sector: 'Automotive'
+ // Auto-refresh portfolio data
+ useEffect(() => {
+ if (selectedPortfolio) {
+ const refreshTimer = setInterval(() => {
+ refreshPortfolioData();
+ }, 60000); // Refresh every minute
+ return () => clearInterval(refreshTimer);
+ }
+ }, [selectedPortfolio]);
+
+ // Load portfolios
+ const loadPortfolios = async () => {
+ try {
+ const result = await portfolioService.getPortfolios();
+ setPortfolios(result);
+
+ // Select first portfolio if none selected
+ if (result.length > 0 && !selectedPortfolio) {
+ setSelectedPortfolio(result[0]);
+ }
+ } catch (error) {
+ console.error('[PortfolioTab] Error loading portfolios:', error);
+ }
+ };
+
+ // Load portfolio summary
+ const loadPortfolioSummary = async (portfolioId: string) => {
+ try {
+ setRefreshing(true);
+ const summary = await portfolioService.getPortfolioSummary(portfolioId);
+ setPortfolioSummary(summary);
+
+ const txns = await portfolioService.getPortfolioTransactions(portfolioId, 20);
+ setTransactions(txns);
+ } catch (error) {
+ console.error('[PortfolioTab] Error loading portfolio summary:', error);
+ } finally {
+ setRefreshing(false);
+ }
+ };
+
+ // Refresh portfolio data
+ const refreshPortfolioData = () => {
+ if (selectedPortfolio) {
+ loadPortfolioSummary(selectedPortfolio.id);
+ }
+ };
+
+ // Handle portfolio selection
+ useEffect(() => {
+ if (selectedPortfolio) {
+ loadPortfolioSummary(selectedPortfolio.id);
+ }
+ }, [selectedPortfolio]);
+
+ // Create new portfolio
+ const handleCreatePortfolio = async () => {
+ if (!newPortfolioName || !newPortfolioOwner) {
+ alert('Please fill in all required fields');
+ return;
+ }
+
+ try {
+ const portfolio = await portfolioService.createPortfolio(
+ newPortfolioName,
+ newPortfolioOwner,
+ newPortfolioCurrency
+ );
+
+ await loadPortfolios();
+ setSelectedPortfolio(portfolio);
+ setShowCreatePortfolio(false);
+
+ // Reset form
+ setNewPortfolioName('');
+ setNewPortfolioOwner('');
+ setNewPortfolioCurrency('USD');
+ } catch (error) {
+ console.error('[PortfolioTab] Error creating portfolio:', error);
+ alert('Failed to create portfolio');
+ }
+ };
+
+ // Add asset to portfolio
+ const handleAddAsset = async () => {
+ if (!selectedPortfolio || !addAssetSymbol || !addAssetQuantity || !addAssetPrice) {
+ alert('Please fill in all required fields');
+ return;
}
- ];
-
- const totalMarketValue = positions.reduce((sum, pos) => sum + pos.marketValue, 0);
- const totalCostBasis = positions.reduce((sum, pos) => sum + pos.costBasis, 0);
- const totalUnrealizedPnL = totalMarketValue - totalCostBasis;
- const totalUnrealizedPnLPercent = (totalUnrealizedPnL / totalCostBasis) * 100;
- const totalDayChange = positions.reduce((sum, pos) => sum + pos.dayChange, 0);
- const totalDayChangePercent = (totalDayChange / (totalMarketValue - totalDayChange)) * 100;
-
- const sectorAllocation = positions.reduce((acc, pos) => {
- if (!acc[pos.sector]) {
- acc[pos.sector] = { value: 0, weight: 0 };
+
+ try {
+ await portfolioService.addAsset(
+ selectedPortfolio.id,
+ addAssetSymbol.toUpperCase(),
+ parseFloat(addAssetQuantity),
+ parseFloat(addAssetPrice)
+ );
+
+ await refreshPortfolioData();
+ setShowAddAsset(false);
+
+ // Reset form
+ setAddAssetSymbol('');
+ setAddAssetQuantity('');
+ setAddAssetPrice('');
+ } catch (error) {
+ console.error('[PortfolioTab] Error adding asset:', error);
+ alert('Failed to add asset');
+ }
+ };
+
+ // Sell asset
+ const handleSellAsset = async () => {
+ if (!selectedPortfolio || !sellAssetSymbol || !sellAssetQuantity || !sellAssetPrice) {
+ alert('Please fill in all required fields');
+ return;
+ }
+
+ try {
+ await portfolioService.sellAsset(
+ selectedPortfolio.id,
+ sellAssetSymbol.toUpperCase(),
+ parseFloat(sellAssetQuantity),
+ parseFloat(sellAssetPrice)
+ );
+
+ await refreshPortfolioData();
+ setShowSellAsset(false);
+
+ // Reset form
+ setSellAssetSymbol('');
+ setSellAssetQuantity('');
+ setSellAssetPrice('');
+ } catch (error) {
+ console.error('[PortfolioTab] Error selling asset:', error);
+ alert(error instanceof Error ? error.message : 'Failed to sell asset');
}
- acc[pos.sector].value += pos.marketValue;
- acc[pos.sector].weight += pos.weight;
- return acc;
- }, {} as Record<string, { value: number; weight: number }>);
-
- const performanceMetrics = [
- { label: 'YTD Return', value: '+18.45%', color: BLOOMBERG_GREEN },
- { label: '1M Return', value: '+5.23%', color: BLOOMBERG_GREEN },
- { label: '3M Return', value: '+12.67%', color: BLOOMBERG_GREEN },
- { label: '1Y Return', value: '+34.89%', color: BLOOMBERG_GREEN },
- { label: 'Sharpe Ratio', value: '1.87', color: BLOOMBERG_CYAN },
- { label: 'Beta', value: '1.12', color: BLOOMBERG_CYAN },
- { label: 'Max Drawdown', value: '-8.23%', color: BLOOMBERG_RED },
- { label: 'Volatility', value: '18.5%', color: BLOOMBERG_YELLOW }
- ];
-
- const recentTransactions = [
- { date: '2024-01-22', ticker: 'AAPL', type: 'BUY', quantity: 50, price: 182.50, total: 9125.00 },
- { date: '2024-01-20', ticker: 'NVDA', type: 'BUY', quantity: 25, price: 495.00, total: 12375.00 },
- { date: '2024-01-18', ticker: 'GOOGL', type: 'SELL', quantity: 30, price: 138.20, total: 4146.00 },
- { date: '2024-01-15', ticker: 'MSFT', type: 'BUY', quantity: 40, price: 365.00, total: 14600.00 }
- ];
+ };
+
+ // Delete portfolio
+ const handleDeletePortfolio = async (portfolioId: string) => {
+ if (!confirm('Are you sure you want to delete this portfolio? This action cannot be undone.')) {
+ return;
+ }
+
+ try {
+ await portfolioService.deletePortfolio(portfolioId);
+ await loadPortfolios();
+
+ if (selectedPortfolio?.id === portfolioId) {
+ setSelectedPortfolio(portfolios.length > 1 ? portfolios[0] : null);
+ setPortfolioSummary(null);
+ }
+ } catch (error) {
+ console.error('[PortfolioTab] Error deleting portfolio:', error);
+ alert('Failed to delete portfolio');
+ }
+ };
+
+ // Export to CSV
+ const handleExportCSV = async () => {
+ if (!selectedPortfolio) return;
+
+ try {
+ const csv = await portfolioService.exportPortfolioCSV(selectedPortfolio.id);
+ const blob = new Blob([csv], { type: 'text/csv' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `${selectedPortfolio.name}_${new Date().toISOString().split('T')[0]}.csv`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ } catch (error) {
+ console.error('[PortfolioTab] Error exporting CSV:', error);
+ alert('Failed to export CSV');
+ }
+ };
+
+ // Get current portfolio currency
+ const currency = selectedPortfolio?.currency || 'USD';
return (
<div style={{
height: '100%',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
+ backgroundColor: DARK_BG,
+ color: WHITE,
fontFamily: 'Consolas, monospace',
overflow: 'hidden',
display: 'flex',
- flexDirection: 'column',
- fontSize: '12px'
+ flexDirection: 'column'
}}>
- {/* Header */}
+ <style>{`
+ *::-webkit-scrollbar { width: 8px; height: 8px; }
+ *::-webkit-scrollbar-track { background: #1a1a1a; }
+ *::-webkit-scrollbar-thumb { background: #404040; border-radius: 4px; }
+ *::-webkit-scrollbar-thumb:hover { background: #525252; }
+ `}</style>
+
+ {/* Header Bar */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
- padding: '4px 8px',
+ backgroundColor: PANEL_BG,
+ borderBottom: `1px solid ${GRAY}`,
+ padding: '8px 12px',
flexShrink: 0
}}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>FINCEPT PORTFOLIO MANAGER</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GREEN }}>● LIVE TRACKING</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_CYAN }}>POSITIONS: {positions.length}</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_YELLOW }}>TOTAL VALUE: ${totalMarketValue.toLocaleString(undefined, {minimumFractionDigits: 2})}</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_WHITE }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
- </div>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <span style={{ color: ORANGE, fontWeight: 'bold', fontSize: '14px' }}>
+ FINCEPT PORTFOLIO MANAGER
+ </span>
+ <span style={{ color: WHITE }}>|</span>
+ <span style={{ color: refreshing ? ORANGE : GREEN, fontSize: '10px' }}>
+ ● {refreshing ? 'UPDATING' : 'LIVE'}
+ </span>
+ <span style={{ color: WHITE }}>|</span>
+ <span style={{ color: CYAN, fontSize: '11px' }}>
+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC
+ </span>
+ </div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>DAY P&L:</span>
- <span style={{ color: totalDayChange >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
- ${totalDayChange >= 0 ? '+' : ''}{totalDayChange.toFixed(2)} ({totalDayChangePercent >= 0 ? '+' : ''}{totalDayChangePercent.toFixed(2)}%)
- </span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY }}>TOTAL P&L:</span>
- <span style={{ color: totalUnrealizedPnL >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
- ${totalUnrealizedPnL >= 0 ? '+' : ''}{totalUnrealizedPnL.toFixed(2)} ({totalUnrealizedPnLPercent >= 0 ? '+' : ''}{totalUnrealizedPnLPercent.toFixed(2)}%)
- </span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY }}>COST BASIS:</span>
- <span style={{ color: BLOOMBERG_CYAN }}>${totalCostBasis.toLocaleString(undefined, {minimumFractionDigits: 2})}</span>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <button
+ onClick={() => setShowCreatePortfolio(true)}
+ style={{
+ background: ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Plus size={12} />
+ NEW PORTFOLIO
+ </button>
+ <button
+ onClick={refreshPortfolioData}
+ disabled={!selectedPortfolio || refreshing}
+ style={{
+ background: selectedPortfolio && !refreshing ? GREEN : GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: selectedPortfolio && !refreshing ? 'pointer' : 'not-allowed',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ opacity: selectedPortfolio && !refreshing ? 1 : 0.5
+ }}
+ >
+ <RefreshCw size={12} />
+ REFRESH
+ </button>
+ <button
+ onClick={handleExportCSV}
+ disabled={!selectedPortfolio}
+ style={{
+ background: selectedPortfolio ? CYAN : GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: selectedPortfolio ? 'pointer' : 'not-allowed',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ opacity: selectedPortfolio ? 1 : 0.5
+ }}
+ >
+ <Download size={12} />
+ EXPORT CSV
+ </button>
+ </div>
</div>
+
+ {/* Portfolio Summary Bar */}
+ {portfolioSummary && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '11px', marginTop: '8px' }}>
+ <span style={{ color: GRAY }}>TOTAL VALUE:</span>
+ <span style={{ color: YELLOW, fontWeight: 'bold' }}>
+ {formatCurrency(portfolioSummary.total_market_value, currency)}
+ </span>
+ <span style={{ color: WHITE }}>|</span>
+ <span style={{ color: GRAY }}>DAY P&L:</span>
+ <span style={{
+ color: portfolioSummary.total_day_change >= 0 ? GREEN : RED,
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(portfolioSummary.total_day_change, currency)} ({formatPercent(portfolioSummary.total_day_change_percent)})
+ </span>
+ <span style={{ color: WHITE }}>|</span>
+ <span style={{ color: GRAY }}>TOTAL P&L:</span>
+ <span style={{
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? GREEN : RED,
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(portfolioSummary.total_unrealized_pnl, currency)} ({formatPercent(portfolioSummary.total_unrealized_pnl_percent)})
+ </span>
+ <span style={{ color: WHITE }}>|</span>
+ <span style={{ color: GRAY }}>POSITIONS:</span>
+ <span style={{ color: CYAN }}>{portfolioSummary.total_positions}</span>
+ </div>
+ )}
</div>
- {/* Function Keys */}
+ {/* Function Keys Bar */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
- padding: '2px 4px',
+ backgroundColor: PANEL_BG,
+ borderBottom: `1px solid ${GRAY}`,
+ padding: '4px 8px',
flexShrink: 0
}}>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '2px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '4px' }}>
{[
{ key: "F1", label: "POSITIONS", view: "POSITIONS" },
- { key: "F2", label: "SECTORS", view: "SECTORS" },
- { key: "F3", label: "PERFORMANCE", view: "PERFORMANCE" },
+ { key: "F2", label: "ADD ASSET", action: () => setShowAddAsset(true) },
+ { key: "F3", label: "SELL ASSET", action: () => setShowSellAsset(true) },
{ key: "F4", label: "ANALYTICS", view: "ANALYTICS" },
- { key: "F5", label: "ORDERS", view: "ORDERS" },
- { key: "F6", label: "HISTORY", view: "HISTORY" },
- { key: "F7", label: "ALERTS", view: "ALERTS" },
- { key: "F8", label: "REPORTS", view: "REPORTS" },
- { key: "F9", label: "IMPORT", view: "IMPORT" },
- { key: "F10", label: "EXPORT", view: "EXPORT" },
+ { key: "F5", label: "HISTORY", view: "HISTORY" },
+ { key: "F6", label: "SECTORS", view: "SECTORS" },
+ { key: "F7", label: "PERFORMANCE", view: "PERFORMANCE" },
+ { key: "F8", label: "REBALANCE", view: "REBALANCE" },
+ { key: "F9", label: "REPORTS", view: "REPORTS" },
+ { key: "F10", label: "ALERTS", view: "ALERTS" },
{ key: "F11", label: "SETTINGS", view: "SETTINGS" },
{ key: "F12", label: "HELP", view: "HELP" }
].map(item => (
- <button key={item.key}
- onClick={() => setSelectedView(item.view)}
+ <button
+ key={item.key}
+ onClick={() => {
+ if (item.action) {
+ if (selectedPortfolio) item.action();
+ } else if (item.view) {
+ setSelectedView(item.view);
+ }
+ }}
+ disabled={!selectedPortfolio && !item.view}
style={{
- backgroundColor: selectedView === item.view ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: selectedView === item.view ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,
- padding: '2px 4px',
+ backgroundColor: selectedView === item.view ? ORANGE : DARK_BG,
+ border: `1px solid ${GRAY}`,
+ color: selectedView === item.view ? 'black' : WHITE,
+ padding: '4px 6px',
fontSize: '9px',
- height: '16px',
+ cursor: selectedPortfolio || item.view ? 'pointer' : 'not-allowed',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- fontWeight: selectedView === item.view ? 'bold' : 'normal',
- cursor: 'pointer'
- }}>
- <span style={{ color: BLOOMBERG_YELLOW }}>{item.key}:</span>
- <span style={{ marginLeft: '2px' }}>{item.label}</span>
+ gap: '2px',
+ opacity: !selectedPortfolio && !item.view ? 0.5 : 1
+ }}
+ >
+ <span style={{ color: YELLOW }}>{item.key}:</span>
+ <span>{item.label}</span>
</button>
))}
</div>
</div>
{/* Main Content */}
- <div style={{ flex: 1, overflow: 'auto', padding: '4px', backgroundColor: '#050505' }}>
- <div style={{ display: 'flex', gap: '4px', height: '100%' }}>
-
- {/* Left Panel - Portfolio Summary */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Sidebar - Portfolio List */}
+ <div style={{
+ width: '250px',
+ backgroundColor: PANEL_BG,
+ borderRight: `1px solid ${GRAY}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
<div style={{
- width: '320px',
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- padding: '4px',
- overflow: 'auto'
+ padding: '8px',
+ backgroundColor: DARK_BG,
+ borderBottom: `1px solid ${GRAY}`,
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
- PORTFOLIO SUMMARY
- </div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '8px' }}></div>
+ PORTFOLIOS ({portfolios.length})
+ </div>
- {/* Key Metrics */}
- <div style={{ marginBottom: '12px' }}>
- <div style={{ padding: '6px', backgroundColor: 'rgba(255,165,0,0.1)', marginBottom: '4px' }}>
- <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginBottom: '2px' }}>TOTAL MARKET VALUE</div>
- <div style={{ color: BLOOMBERG_WHITE, fontSize: '16px', fontWeight: 'bold' }}>
- ${totalMarketValue.toLocaleString(undefined, {minimumFractionDigits: 2})}
- </div>
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {loading ? (
+ <div style={{ padding: '16px', textAlign: 'center', color: GRAY, fontSize: '10px' }}>
+ Loading portfolios...
</div>
-
- <div style={{ padding: '6px', backgroundColor: totalDayChange >= 0 ? 'rgba(0,200,0,0.05)' : 'rgba(255,0,0,0.05)', marginBottom: '4px' }}>
- <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginBottom: '2px' }}>TODAY'S CHANGE</div>
- <div style={{ color: totalDayChange >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '14px', fontWeight: 'bold' }}>
- ${totalDayChange >= 0 ? '+' : ''}{totalDayChange.toFixed(2)}
- </div>
- <div style={{ color: totalDayChange >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '10px' }}>
- ({totalDayChangePercent >= 0 ? '+' : ''}{totalDayChangePercent.toFixed(2)}%)
- </div>
+ ) : portfolios.length === 0 ? (
+ <div style={{ padding: '16px', textAlign: 'center', color: GRAY, fontSize: '10px' }}>
+ No portfolios yet.
+ <br />
+ Click NEW PORTFOLIO to create one.
</div>
-
- <div style={{ padding: '6px', backgroundColor: totalUnrealizedPnL >= 0 ? 'rgba(0,200,0,0.05)' : 'rgba(255,0,0,0.05)' }}>
- <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginBottom: '2px' }}>UNREALIZED P&L</div>
- <div style={{ color: totalUnrealizedPnL >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '14px', fontWeight: 'bold' }}>
- ${totalUnrealizedPnL >= 0 ? '+' : ''}{totalUnrealizedPnL.toFixed(2)}
- </div>
- <div style={{ color: totalUnrealizedPnL >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '10px' }}>
- ({totalUnrealizedPnLPercent >= 0 ? '+' : ''}{totalUnrealizedPnLPercent.toFixed(2)}%)
+ ) : (
+ portfolios.map(portfolio => (
+ <div
+ key={portfolio.id}
+ onClick={() => setSelectedPortfolio(portfolio)}
+ style={{
+ padding: '12px',
+ backgroundColor: selectedPortfolio?.id === portfolio.id ? 'rgba(255,165,0,0.1)' : 'transparent',
+ borderLeft: selectedPortfolio?.id === portfolio.id ? `3px solid ${ORANGE}` : '3px solid transparent',
+ cursor: 'pointer',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`,
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (selectedPortfolio?.id !== portfolio.id) {
+ e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.05)';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (selectedPortfolio?.id !== portfolio.id) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
+ <div style={{
+ color: selectedPortfolio?.id === portfolio.id ? ORANGE : WHITE,
+ fontSize: '11px',
+ fontWeight: 'bold'
+ }}>
+ {portfolio.name}
+ </div>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handleDeletePortfolio(portfolio.id);
+ }}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ color: RED,
+ cursor: 'pointer',
+ padding: '2px',
+ display: 'flex'
+ }}
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ <div style={{ fontSize: '9px', color: GRAY }}>
+ Owner: {portfolio.owner}
+ </div>
+ <div style={{ fontSize: '9px', color: CYAN }}>
+ Currency: {portfolio.currency}
+ </div>
</div>
- </div>
- </div>
+ ))
+ )}
+ </div>
+ </div>
- {/* Additional Metrics */}
- <div style={{ fontSize: '9px', lineHeight: '1.5', marginBottom: '12px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>Cost Basis:</span>
- <span style={{ color: BLOOMBERG_WHITE }}>${totalCostBasis.toLocaleString()}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>Cash Available:</span>
- <span style={{ color: BLOOMBERG_CYAN }}>$25,432.18</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>Buying Power:</span>
- <span style={{ color: BLOOMBERG_CYAN }}>$50,864.36</span>
- </div>
- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, marginTop: '4px', paddingTop: '4px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: BLOOMBERG_CYAN }}>Total Equity:</span>
- <span style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>
- ${(totalMarketValue + 25432.18).toLocaleString(undefined, {minimumFractionDigits: 2})}
- </span>
- </div>
+ {/* Center Content - Portfolio Details */}
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ {!selectedPortfolio ? (
+ <div style={{
+ flex: 1,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '16px'
+ }}>
+ <BarChart3 size={64} color={GRAY} />
+ <div style={{ color: GRAY, fontSize: '14px' }}>
+ Select a portfolio or create a new one to get started
</div>
</div>
+ ) : !portfolioSummary ? (
+ <div style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: GRAY,
+ fontSize: '12px'
+ }}>
+ Loading portfolio data...
+ </div>
+ ) : (
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
+ {/* Positions View */}
+ {selectedView === 'POSITIONS' && (
+ <PositionsView portfolioSummary={portfolioSummary} />
+ )}
- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, paddingTop: '8px', marginBottom: '8px' }}>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
- SECTOR ALLOCATION
- </div>
- {Object.entries(sectorAllocation).map(([sector, data], index) => (
- <div key={index} style={{
- marginBottom: '3px',
- padding: '3px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- fontSize: '9px'
+ {/* History View */}
+ {selectedView === 'HISTORY' && (
+ <HistoryView transactions={transactions} currency={currency} />
+ )}
+
+ {/* Analytics View */}
+ {selectedView === 'ANALYTICS' && (
+ <AnalyticsView portfolioSummary={portfolioSummary} />
+ )}
+
+ {/* Sectors View */}
+ {selectedView === 'SECTORS' && (
+ <SectorsView portfolioSummary={portfolioSummary} />
+ )}
+
+ {/* Performance View */}
+ {selectedView === 'PERFORMANCE' && (
+ <PerformanceView portfolioSummary={portfolioSummary} />
+ )}
+
+ {/* Risk Metrics View (for REBALANCE button - shows risk metrics) */}
+ {selectedView === 'REBALANCE' && (
+ <RiskMetricsView portfolioSummary={portfolioSummary} />
+ )}
+
+ {/* Reports View */}
+ {selectedView === 'REPORTS' && (
+ <ReportsView portfolioSummary={portfolioSummary} transactions={transactions} />
+ )}
+
+ {/* Alerts View */}
+ {selectedView === 'ALERTS' && (
+ <AlertsView portfolioSummary={portfolioSummary} />
+ )}
+
+ {/* Other views placeholder */}
+ {!['POSITIONS', 'HISTORY', 'ANALYTICS', 'SECTORS', 'PERFORMANCE', 'REBALANCE', 'REPORTS', 'ALERTS'].includes(selectedView) && (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ gap: '16px'
}}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: BLOOMBERG_WHITE }}>{sector}</span>
- <span style={{ color: BLOOMBERG_CYAN }}>{data.weight.toFixed(1)}%</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', color: BLOOMBERG_GRAY }}>
- <span>${data.value.toLocaleString()}</span>
+ <PieChart size={64} color={GRAY} />
+ <div style={{ color: GRAY, fontSize: '12px' }}>
+ {selectedView} view coming soon...
</div>
</div>
- ))}
+ )}
</div>
+ )}
+ </div>
+ </div>
- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, paddingTop: '8px' }}>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
- PERFORMANCE METRICS
- </div>
- <div style={{ fontSize: '9px', lineHeight: '1.5' }}>
- {performanceMetrics.map((metric, index) => (
- <div key={index} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>{metric.label}:</span>
- <span style={{ color: metric.color }}>{metric.value}</span>
- </div>
- ))}
- </div>
- </div>
- </div>
+ {/* Status Bar */}
+ <div style={{
+ borderTop: `1px solid ${GRAY}`,
+ backgroundColor: PANEL_BG,
+ padding: '4px 12px',
+ fontSize: '9px',
+ color: GRAY,
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <span>Fincept Portfolio Manager v2.1.0 | Real-time tracking with yfinance integration</span>
+ {portfolioSummary && (
+ <span>
+ Last Updated: {new Date(portfolioSummary.last_updated).toLocaleTimeString()} |
+ Status: <span style={{ color: GREEN }}>CONNECTED</span>
+ </span>
+ )}
+ </div>
+ </div>
- {/* Center Panel - Positions Table */}
+ {/* Create Portfolio Modal */}
+ {showCreatePortfolio && (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.8)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
<div style={{
- flex: 1,
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- padding: '4px',
- overflow: 'auto'
+ backgroundColor: DARK_BG,
+ border: `2px solid ${ORANGE}`,
+ padding: '24px',
+ minWidth: '400px'
}}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
- CURRENT POSITIONS
- </div>
- <div style={{ display: 'flex', gap: '4px', fontSize: '9px' }}>
- <button onClick={() => setSortBy('WEIGHT')} style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'WEIGHT' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,
- color: sortBy === 'WEIGHT' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- cursor: 'pointer'
- }}>WEIGHT</button>
- <button onClick={() => setSortBy('PNL')} style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'PNL' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,
- color: sortBy === 'PNL' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- cursor: 'pointer'
- }}>P&L</button>
- <button onClick={() => setSortBy('VALUE')} style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'VALUE' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,
- color: sortBy === 'VALUE' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- cursor: 'pointer'
- }}>VALUE</button>
- </div>
+ <div style={{ color: ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '16px' }}>
+ CREATE NEW PORTFOLIO
</div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '8px' }}></div>
- {/* Table Header */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: '80px 180px 80px 90px 90px 100px 100px 120px 120px 80px',
- gap: '4px',
- padding: '4px',
- backgroundColor: 'rgba(255,255,255,0.05)',
- fontSize: '9px',
- fontWeight: 'bold',
- marginBottom: '2px'
- }}>
- <div style={{ color: BLOOMBERG_GRAY }}>TICKER</div>
- <div style={{ color: BLOOMBERG_GRAY }}>NAME</div>
- <div style={{ color: BLOOMBERG_GRAY }}>QTY</div>
- <div style={{ color: BLOOMBERG_GRAY }}>AVG PRICE</div>
- <div style={{ color: BLOOMBERG_GRAY }}>CURRENT</div>
- <div style={{ color: BLOOMBERG_GRAY }}>MKT VALUE</div>
- <div style={{ color: BLOOMBERG_GRAY }}>COST BASIS</div>
- <div style={{ color: BLOOMBERG_GRAY }}>UNREALIZED P&L</div>
- <div style={{ color: BLOOMBERG_GRAY }}>DAY CHANGE</div>
- <div style={{ color: BLOOMBERG_GRAY }}>WEIGHT</div>
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ PORTFOLIO NAME *
+ </label>
+ <input
+ type="text"
+ value={newPortfolioName}
+ onChange={(e) => setNewPortfolioName(e.target.value)}
+ style={{
+ width: '100%',
+ background: PANEL_BG,
+ border: `1px solid ${GRAY}`,
+ color: WHITE,
+ padding: '8px',
+ fontSize: '11px'
+ }}
+ placeholder="My Portfolio"
+ />
</div>
- {/* Position Rows */}
- {positions.map((pos, index) => (
- <div key={index} style={{
- display: 'grid',
- gridTemplateColumns: '80px 180px 80px 90px 90px 100px 100px 120px 120px 80px',
- gap: '4px',
- padding: '6px 4px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- borderLeft: `3px solid ${pos.unrealizedPnL >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED}`,
- fontSize: '10px',
- marginBottom: '1px'
- }}>
- <div style={{ color: BLOOMBERG_CYAN, fontWeight: 'bold' }}>{pos.ticker}</div>
- <div style={{ color: BLOOMBERG_WHITE, overflow: 'hidden', textOverflow: 'ellipsis' }}>{pos.name}</div>
- <div style={{ color: BLOOMBERG_WHITE }}>{pos.quantity.toLocaleString()}</div>
- <div style={{ color: BLOOMBERG_GRAY }}>${pos.avgPrice.toFixed(2)}</div>
- <div style={{ color: BLOOMBERG_WHITE }}>${pos.currentPrice.toFixed(2)}</div>
- <div style={{ color: BLOOMBERG_WHITE }}>${pos.marketValue.toLocaleString()}</div>
- <div style={{ color: BLOOMBERG_GRAY }}>${pos.costBasis.toLocaleString()}</div>
- <div>
- <div style={{ color: pos.unrealizedPnL >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
- ${pos.unrealizedPnL >= 0 ? '+' : ''}{pos.unrealizedPnL.toFixed(2)}
- </div>
- <div style={{ color: pos.unrealizedPnL >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '8px' }}>
- ({pos.unrealizedPnLPercent >= 0 ? '+' : ''}{pos.unrealizedPnLPercent.toFixed(2)}%)
- </div>
- </div>
- <div>
- <div style={{ color: pos.dayChange >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
- ${pos.dayChange >= 0 ? '+' : ''}{pos.dayChange.toFixed(2)}
- </div>
- <div style={{ color: pos.dayChange >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '8px' }}>
- ({pos.dayChangePercent >= 0 ? '+' : ''}{pos.dayChangePercent.toFixed(2)}%)
- </div>
- </div>
- <div style={{ color: BLOOMBERG_YELLOW }}>{pos.weight.toFixed(1)}%</div>
- </div>
- ))}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ OWNER *
+ </label>
+ <input
+ type="text"
+ value={newPortfolioOwner}
+ onChange={(e) => setNewPortfolioOwner(e.target.value)}
+ style={{
+ width: '100%',
+ background: PANEL_BG,
+ border: `1px solid ${GRAY}`,
+ color: WHITE,
+ padding: '8px',
+ fontSize: '11px'
+ }}
+ placeholder="John Doe"
+ />
+ </div>
- {/* Totals Row */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: '80px 180px 80px 90px 90px 100px 100px 120px 120px 80px',
- gap: '4px',
- padding: '6px 4px',
- backgroundColor: 'rgba(255,165,0,0.1)',
- borderTop: `2px solid ${BLOOMBERG_ORANGE}`,
- fontSize: '10px',
- fontWeight: 'bold',
- marginTop: '4px'
- }}>
- <div style={{ color: BLOOMBERG_ORANGE }}>TOTAL</div>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- <div style={{ color: BLOOMBERG_WHITE }}>${totalMarketValue.toLocaleString()}</div>
- <div style={{ color: BLOOMBERG_GRAY }}>${totalCostBasis.toLocaleString()}</div>
- <div>
- <div style={{ color: totalUnrealizedPnL >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
- ${totalUnrealizedPnL >= 0 ? '+' : ''}{totalUnrealizedPnL.toFixed(2)}
- </div>
- <div style={{ color: totalUnrealizedPnL >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '8px' }}>
- ({totalUnrealizedPnLPercent >= 0 ? '+' : ''}{totalUnrealizedPnLPercent.toFixed(2)}%)
- </div>
- </div>
- <div>
- <div style={{ color: totalDayChange >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
- ${totalDayChange >= 0 ? '+' : ''}{totalDayChange.toFixed(2)}
- </div>
- <div style={{ color: totalDayChange >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '8px' }}>
- ({totalDayChangePercent >= 0 ? '+' : ''}{totalDayChangePercent.toFixed(2)}%)
- </div>
- </div>
- <div style={{ color: BLOOMBERG_YELLOW }}>100.0%</div>
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ CURRENCY
+ </label>
+ <select
+ value={newPortfolioCurrency}
+ onChange={(e) => setNewPortfolioCurrency(e.target.value)}
+ style={{
+ width: '100%',
+ background: PANEL_BG,
+ border: `1px solid ${GRAY}`,
+ color: WHITE,
+ padding: '8px',
+ fontSize: '11px'
+ }}
+ >
+ <option value="USD">USD - US Dollar</option>
+ <option value="EUR">EUR - Euro</option>
+ <option value="GBP">GBP - British Pound</option>
+ <option value="INR">INR - Indian Rupee</option>
+ </select>
+ </div>
+
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
+ <button
+ onClick={() => setShowCreatePortfolio(false)}
+ style={{
+ background: GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
+ <button
+ onClick={handleCreatePortfolio}
+ style={{
+ background: ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CREATE
+ </button>
</div>
</div>
+ </div>
+ )}
- {/* Right Panel - Activity & Transactions */}
+ {/* Add Asset Modal */}
+ {showAddAsset && (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.8)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
<div style={{
- width: '320px',
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- padding: '4px',
- overflow: 'auto'
+ backgroundColor: DARK_BG,
+ border: `2px solid ${GREEN}`,
+ padding: '24px',
+ minWidth: '400px'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
- RECENT TRANSACTIONS
+ <div style={{ color: GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '16px' }}>
+ ADD ASSET TO PORTFOLIO
</div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '8px' }}></div>
-
- {recentTransactions.map((txn, index) => (
- <div key={index} style={{
- marginBottom: '6px',
- padding: '6px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- borderLeft: `3px solid ${txn.type === 'BUY' ? BLOOMBERG_GREEN : BLOOMBERG_RED}`,
- fontSize: '9px'
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>{txn.date}</span>
- <span style={{ color: txn.type === 'BUY' ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontWeight: 'bold' }}>
- {txn.type}
- </span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_CYAN, fontWeight: 'bold' }}>{txn.ticker}</span>
- <span style={{ color: BLOOMBERG_WHITE }}>{txn.quantity} @ ${txn.price.toFixed(2)}</span>
- </div>
- <div style={{ color: BLOOMBERG_GRAY, textAlign: 'right' }}>
- Total: ${txn.total.toLocaleString()}
- </div>
- </div>
- ))}
- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, paddingTop: '8px', marginTop: '12px' }}>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
- MARKET INDICATORS
- </div>
- {[
- { name: 'S&P 500', value: '4,850.25', change: '+0.87%', color: BLOOMBERG_GREEN },
- { name: 'NASDAQ', value: '15,234.56', change: '+1.23%', color: BLOOMBERG_GREEN },
- { name: 'DOW JONES', value: '38,742.18', change: '+0.56%', color: BLOOMBERG_GREEN },
- { name: 'VIX', value: '13.45', change: '-5.23%', color: BLOOMBERG_GREEN },
- { name: '10Y YIELD', value: '4.12%', change: '+0.03', color: BLOOMBERG_RED }
- ].map((indicator, index) => (
- <div key={index} style={{
- display: 'flex',
- justifyContent: 'space-between',
- padding: '3px',
- marginBottom: '2px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- fontSize: '9px'
- }}>
- <span style={{ color: BLOOMBERG_WHITE }}>{indicator.name}</span>
- <div style={{ textAlign: 'right' }}>
- <div style={{ color: BLOOMBERG_CYAN }}>{indicator.value}</div>
- <div style={{ color: indicator.color, fontSize: '8px' }}>{indicator.change}</div>
- </div>
- </div>
- ))}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ SYMBOL *
+ </label>
+ <input
+ type="text"
+ value={addAssetSymbol}
+ onChange={(e) => setAddAssetSymbol(e.target.value.toUpperCase())}
+ style={{
+ width: '100%',
+ background: PANEL_BG,
+ border: `1px solid ${GRAY}`,
+ color: WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ textTransform: 'uppercase'
+ }}
+ placeholder="AAPL"
+ />
</div>
- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, paddingTop: '8px', marginTop: '12px' }}>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
- PORTFOLIO ALERTS
- </div>
- {[
- { type: 'TARGET', message: 'AAPL reached target price $185', time: '2h ago', color: BLOOMBERG_GREEN },
- { type: 'STOP', message: 'GOOGL approaching stop loss', time: '5h ago', color: BLOOMBERG_RED },
- { type: 'NEWS', message: 'NVDA earnings report tomorrow', time: '1d ago', color: BLOOMBERG_YELLOW }
- ].map((alert, index) => (
- <div key={index} style={{
- marginBottom: '4px',
- padding: '4px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- borderLeft: `2px solid ${alert.color}`,
- fontSize: '8px',
- lineHeight: '1.3'
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: alert.color, fontWeight: 'bold' }}>[{alert.type}]</span>
- <span style={{ color: BLOOMBERG_GRAY }}>{alert.time}</span>
- </div>
- <div style={{ color: BLOOMBERG_WHITE }}>{alert.message}</div>
- </div>
- ))}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ QUANTITY *
+ </label>
+ <input
+ type="number"
+ value={addAssetQuantity}
+ onChange={(e) => setAddAssetQuantity(e.target.value)}
+ style={{
+ width: '100%',
+ background: PANEL_BG,
+ border: `1px solid ${GRAY}`,
+ color: WHITE,
+ padding: '8px',
+ fontSize: '11px'
+ }}
+ placeholder="100"
+ step="0.0001"
+ />
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ BUY PRICE *
+ </label>
+ <input
+ type="number"
+ value={addAssetPrice}
+ onChange={(e) => setAddAssetPrice(e.target.value)}
+ style={{
+ width: '100%',
+ background: PANEL_BG,
+ border: `1px solid ${GRAY}`,
+ color: WHITE,
+ padding: '8px',
+ fontSize: '11px'
+ }}
+ placeholder="150.00"
+ step="0.01"
+ />
+ </div>
+
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
+ <button
+ onClick={() => setShowAddAsset(false)}
+ style={{
+ background: GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
+ <button
+ onClick={handleAddAsset}
+ style={{
+ background: GREEN,
+ color: 'black',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ ADD
+ </button>
</div>
</div>
</div>
- </div>
+ )}
- {/* Status Bar */}
- <div style={{
- borderTop: `1px solid ${BLOOMBERG_GRAY}`,
- backgroundColor: BLOOMBERG_PANEL_BG,
- padding: '2px 8px',
- fontSize: '10px',
- color: BLOOMBERG_GRAY,
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <div style={{ display: 'flex', gap: '16px' }}>
- <span>Fincept Portfolio Manager v2.1.0 | Real-time position tracking</span>
- <span>Positions: {positions.length} | Market Value: ${totalMarketValue.toLocaleString()}</span>
- </div>
- <div style={{ display: 'flex', gap: '16px' }}>
- <span>View: {selectedView}</span>
- <span>Sort: {sortBy}</span>
- <span style={{ color: BLOOMBERG_GREEN }}>STATUS: LIVE</span>
+ {/* Sell Asset Modal */}
+ {showSellAsset && (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.8)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `2px solid ${RED}`,
+ padding: '24px',
+ minWidth: '400px'
+ }}>
+ <div style={{ color: RED, fontSize: '14px', fontWeight: 'bold', marginBottom: '16px' }}>
+ SELL ASSET FROM PORTFOLIO
+ </div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ SYMBOL *
+ </label>
+ <input
+ type="text"
+ value={sellAssetSymbol}
+ onChange={(e) => setSellAssetSymbol(e.target.value.toUpperCase())}
+ style={{
+ width: '100%',
+ background: PANEL_BG,
+ border: `1px solid ${GRAY}`,
+ color: WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ textTransform: 'uppercase'
+ }}
+ placeholder="AAPL"
+ />
+ </div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ QUANTITY *
+ </label>
+ <input
+ type="number"
+ value={sellAssetQuantity}
+ onChange={(e) => setSellAssetQuantity(e.target.value)}
+ style={{
+ width: '100%',
+ background: PANEL_BG,
+ border: `1px solid ${GRAY}`,
+ color: WHITE,
+ padding: '8px',
+ fontSize: '11px'
+ }}
+ placeholder="50"
+ step="0.0001"
+ />
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: GRAY, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ SELL PRICE *
+ </label>
+ <input
+ type="number"
+ value={sellAssetPrice}
+ onChange={(e) => setSellAssetPrice(e.target.value)}
+ style={{
+ width: '100%',
+ background: PANEL_BG,
+ border: `1px solid ${GRAY}`,
+ color: WHITE,
+ padding: '8px',
+ fontSize: '11px'
+ }}
+ placeholder="180.00"
+ step="0.01"
+ />
+ </div>
+
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
+ <button
+ onClick={() => setShowSellAsset(false)}
+ style={{
+ background: GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
+ <button
+ onClick={handleSellAsset}
+ style={{
+ background: RED,
+ color: 'white',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ SELL
+ </button>
+ </div>
</div>
</div>
- </div>
+ )}
</div>
);
};
-export default PortfolioTab;
\ No newline at end of file
+export default PortfolioTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/AlertsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio/AlertsView.tsx
new file mode 100644
index 000000000..1e7cf35de
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/AlertsView.tsx
@@ -0,0 +1,468 @@
+import React, { useState, useEffect } from 'react';
+import { PortfolioSummary } from '../../../services/portfolioService';
+import { BLOOMBERG_COLORS, formatCurrency } from './utils';
+import { Bell, TrendingUp, TrendingDown, Target } from 'lucide-react';
+import { alertsService, PriceAlert } from '../../../services/alertsService';
+
+interface AlertsViewProps {
+ portfolioSummary: PortfolioSummary;
+}
+
+const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
+ const { ORANGE, WHITE, RED, GREEN, GRAY, CYAN, YELLOW } = BLOOMBERG_COLORS;
+ const currency = portfolioSummary.portfolio.currency;
+
+ const [alerts, setAlerts] = useState<PriceAlert[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [stats, setStats] = useState({ total: 0, active: 0, triggered: 0, byType: {} as Record<string, number> });
+
+ useEffect(() => {
+ const loadAlerts = async () => {
+ try {
+ await alertsService.initialize();
+ const portfolioAlerts = await alertsService.getPortfolioAlerts(portfolioSummary.portfolio.id, false);
+ const alertStats = await alertsService.getAlertStats(portfolioSummary.portfolio.id);
+
+ setAlerts(portfolioAlerts);
+ setStats(alertStats);
+ } catch (error) {
+ console.error('Failed to load alerts:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ loadAlerts();
+ }, [portfolioSummary.portfolio.id]);
+
+ const handleDeleteAlert = async (alertId: string) => {
+ try {
+ await alertsService.deleteAlert(alertId);
+ setAlerts(prev => prev.filter(a => a.id !== alertId));
+ // Refresh stats
+ const alertStats = await alertsService.getAlertStats(portfolioSummary.portfolio.id);
+ setStats(alertStats);
+ } catch (error) {
+ console.error('Failed to delete alert:', error);
+ }
+ };
+
+ const getAlertIcon = (type: string) => {
+ switch (type) {
+ case 'PRICE_TARGET':
+ return <Target size={14} />;
+ case 'STOP_LOSS':
+ return <TrendingDown size={14} />;
+ case 'TAKE_PROFIT':
+ return <TrendingUp size={14} />;
+ default:
+ return <Bell size={14} />;
+ }
+ };
+
+ const getAlertColor = (type: string) => {
+ switch (type) {
+ case 'PRICE_TARGET':
+ return CYAN;
+ case 'STOP_LOSS':
+ return RED;
+ case 'TAKE_PROFIT':
+ return GREEN;
+ default:
+ return YELLOW;
+ }
+ };
+
+ return (
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '16px'
+ }}>
+ PRICE ALERTS & NOTIFICATIONS
+ </div>
+
+ {/* Alert Statistics */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '12px',
+ marginBottom: '20px'
+ }}>
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>TOTAL ALERTS</div>
+ <div style={{ color: ORANGE, fontSize: '16px', fontWeight: 'bold' }}>
+ {stats.total}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(0,200,0,0.1)',
+ border: `1px solid ${GREEN}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>ACTIVE</div>
+ <div style={{ color: GREEN, fontSize: '16px', fontWeight: 'bold' }}>
+ {stats.active}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(255,0,0,0.1)',
+ border: `1px solid ${RED}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>TRIGGERED</div>
+ <div style={{ color: RED, fontSize: '16px', fontWeight: 'bold' }}>
+ {stats.triggered}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(0,255,255,0.1)',
+ border: `1px solid ${CYAN}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>POSITIONS TRACKED</div>
+ <div style={{ color: CYAN, fontSize: '16px', fontWeight: 'bold' }}>
+ {new Set(alerts.map(a => a.symbol)).size}
+ </div>
+ </div>
+ </div>
+
+ {/* Create Alert Button */}
+ <div style={{ marginBottom: '20px' }}>
+ <button style={{
+ padding: '12px 20px',
+ backgroundColor: ORANGE,
+ color: 'black',
+ border: 'none',
+ borderRadius: '4px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <Bell size={14} />
+ CREATE NEW ALERT
+ </button>
+ </div>
+
+ {/* Active Alerts */}
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ ACTIVE ALERTS
+ </div>
+
+ {loading ? (
+ <div style={{
+ padding: '32px',
+ textAlign: 'center',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px',
+ marginBottom: '20px'
+ }}>
+ <div style={{ color: ORANGE, fontSize: '11px' }}>
+ Loading alerts...
+ </div>
+ </div>
+ ) : alerts.filter(a => !a.is_triggered).length === 0 ? (
+ <div style={{
+ padding: '32px',
+ textAlign: 'center',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px',
+ marginBottom: '20px'
+ }}>
+ <Bell size={48} color={GRAY} style={{ margin: '0 auto 12px' }} />
+ <div style={{ color: GRAY, fontSize: '11px' }}>
+ No active alerts. Create one to get notified about price movements.
+ </div>
+ </div>
+ ) : (
+ <div style={{ marginBottom: '20px' }}>
+ {alerts.filter(a => !a.is_triggered).map(alert => {
+ // Find current price from portfolio holdings
+ const holding = portfolioSummary.holdings.find(h => h.symbol === alert.symbol);
+ const currentPrice = holding?.current_price || 0;
+
+ return (
+ <div
+ key={alert.id}
+ style={{
+ padding: '12px',
+ marginBottom: '8px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${getAlertColor(alert.type)}`,
+ borderLeft: `4px solid ${getAlertColor(alert.type)}`,
+ borderRadius: '4px',
+ display: 'grid',
+ gridTemplateColumns: '40px 100px 1fr 150px 150px 80px',
+ gap: '12px',
+ alignItems: 'center'
+ }}
+ >
+ <div style={{ color: getAlertColor(alert.type), display: 'flex', justifyContent: 'center' }}>
+ {getAlertIcon(alert.type)}
+ </div>
+
+ <div>
+ <div style={{ color: CYAN, fontSize: '11px', fontWeight: 'bold' }}>
+ {alert.symbol}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px' }}>
+ {alert.type.replace('_', ' ')}
+ </div>
+ </div>
+
+ <div>
+ <div style={{ color: WHITE, fontSize: '10px' }}>
+ Alert when price {alert.condition.toLowerCase().replace('_', ' ')}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Created: {alert.created_at.split('T')[0]}
+ </div>
+ </div>
+
+ <div>
+ <div style={{ color: GRAY, fontSize: '8px' }}>TARGET PRICE</div>
+ <div style={{ color: getAlertColor(alert.type), fontSize: '12px', fontWeight: 'bold' }}>
+ {formatCurrency(alert.target_value, currency)}
+ </div>
+ </div>
+
+ <div>
+ <div style={{ color: GRAY, fontSize: '8px' }}>CURRENT PRICE</div>
+ <div style={{ color: WHITE, fontSize: '12px', fontWeight: 'bold' }}>
+ {currentPrice > 0 ? formatCurrency(currentPrice, currency) : 'N/A'}
+ </div>
+ </div>
+
+ <div style={{ display: 'flex', gap: '4px', justifyContent: 'flex-end' }}>
+ <button
+ onClick={() => handleDeleteAlert(alert.id)}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: RED,
+ color: 'white',
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}>
+ DELETE
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Position-Based Alert Suggestions */}
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ SUGGESTED ALERTS FOR YOUR POSITIONS
+ </div>
+
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, 1fr)',
+ gap: '12px',
+ marginBottom: '20px'
+ }}>
+ {portfolioSummary.holdings.slice(0, 4).map(holding => {
+ const stopLoss = holding.avg_buy_price * 0.9; // 10% below buy price
+ const takeProfit = holding.avg_buy_price * 1.2; // 20% above buy price
+
+ return (
+ <div
+ key={holding.id}
+ style={{
+ padding: '12px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}
+ >
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginBottom: '8px'
+ }}>
+ <div style={{ color: CYAN, fontSize: '11px', fontWeight: 'bold' }}>
+ {holding.symbol}
+ </div>
+ <div style={{ color: WHITE, fontSize: '10px' }}>
+ {formatCurrency(holding.current_price, currency)}
+ </div>
+ </div>
+
+ <div style={{ fontSize: '9px', marginBottom: '8px' }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginBottom: '4px',
+ color: GRAY
+ }}>
+ <span>Stop Loss (10%):</span>
+ <span style={{ color: RED }}>{formatCurrency(stopLoss, currency)}</span>
+ </div>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ color: GRAY
+ }}>
+ <span>Take Profit (20%):</span>
+ <span style={{ color: GREEN }}>{formatCurrency(takeProfit, currency)}</span>
+ </div>
+ </div>
+
+ <button style={{
+ width: '100%',
+ padding: '6px',
+ backgroundColor: ORANGE,
+ color: 'black',
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}>
+ CREATE ALERTS
+ </button>
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Alert Settings */}
+ <div style={{
+ padding: '16px',
+ backgroundColor: 'rgba(255,165,0,0.05)',
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px'
+ }}>
+ NOTIFICATION SETTINGS
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
+ <div>
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '8px',
+ cursor: 'pointer'
+ }}>
+ <input type="checkbox" defaultChecked />
+ <span style={{ color: WHITE, fontSize: '10px' }}>
+ Desktop notifications
+ </span>
+ </label>
+
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '8px',
+ cursor: 'pointer'
+ }}>
+ <input type="checkbox" defaultChecked />
+ <span style={{ color: WHITE, fontSize: '10px' }}>
+ Email notifications
+ </span>
+ </label>
+
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ cursor: 'pointer'
+ }}>
+ <input type="checkbox" />
+ <span style={{ color: WHITE, fontSize: '10px' }}>
+ SMS notifications (Premium)
+ </span>
+ </label>
+ </div>
+
+ <div>
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '8px',
+ cursor: 'pointer'
+ }}>
+ <input type="checkbox" defaultChecked />
+ <span style={{ color: WHITE, fontSize: '10px' }}>
+ Daily portfolio summary
+ </span>
+ </label>
+
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '8px',
+ cursor: 'pointer'
+ }}>
+ <input type="checkbox" />
+ <span style={{ color: WHITE, fontSize: '10px' }}>
+ Weekly performance report
+ </span>
+ </label>
+
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ cursor: 'pointer'
+ }}>
+ <input type="checkbox" defaultChecked />
+ <span style={{ color: WHITE, fontSize: '10px' }}>
+ Large position movements (&gt;5%)
+ </span>
+ </label>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default AlertsView;
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/AnalyticsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio/AnalyticsView.tsx
new file mode 100644
index 000000000..706504413
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/AnalyticsView.tsx
@@ -0,0 +1,348 @@
+import React from 'react';
+import { PortfolioSummary } from '../../../services/portfolioService';
+import { BLOOMBERG_COLORS, formatCurrency, formatPercent, formatLargeNumber } from './utils';
+
+interface AnalyticsViewProps {
+ portfolioSummary: PortfolioSummary;
+}
+
+const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
+ const { ORANGE, WHITE, RED, GREEN, GRAY, CYAN, YELLOW, BLUE } = BLOOMBERG_COLORS;
+ const currency = portfolioSummary.portfolio.currency;
+
+ // Calculate key metrics
+ const totalValue = portfolioSummary.total_market_value;
+ const totalPnL = portfolioSummary.total_unrealized_pnl;
+ const totalPnLPercent = portfolioSummary.total_unrealized_pnl_percent;
+ const dayChange = portfolioSummary.total_day_change;
+ const dayChangePercent = portfolioSummary.total_day_change_percent;
+ const positionsCount = portfolioSummary.total_positions;
+
+ // Find top performers
+ const topGainers = [...portfolioSummary.holdings]
+ .sort((a, b) => b.unrealized_pnl_percent - a.unrealized_pnl_percent)
+ .slice(0, 5);
+
+ const topLosers = [...portfolioSummary.holdings]
+ .sort((a, b) => a.unrealized_pnl_percent - b.unrealized_pnl_percent)
+ .slice(0, 5);
+
+ // Largest positions by value
+ const largestPositions = [...portfolioSummary.holdings]
+ .sort((a, b) => b.market_value - a.market_value)
+ .slice(0, 5);
+
+ return (
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '16px'
+ }}>
+ PORTFOLIO ANALYTICS DASHBOARD
+ </div>
+
+ {/* Key Metrics Grid */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '12px',
+ marginBottom: '20px'
+ }}>
+ {/* Total Value Card */}
+ <div style={{
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ border: `1px solid ${ORANGE}`,
+ padding: '12px',
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>TOTAL VALUE</div>
+ <div style={{ color: YELLOW, fontSize: '16px', fontWeight: 'bold' }}>
+ {formatLargeNumber(totalValue, currency)}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ {formatCurrency(totalValue, currency)}
+ </div>
+ </div>
+
+ {/* Total P&L Card */}
+ <div style={{
+ backgroundColor: totalPnL >= 0 ? 'rgba(0,200,0,0.1)' : 'rgba(255,0,0,0.1)',
+ border: `1px solid ${totalPnL >= 0 ? GREEN : RED}`,
+ padding: '12px',
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>TOTAL P&L</div>
+ <div style={{ color: totalPnL >= 0 ? GREEN : RED, fontSize: '16px', fontWeight: 'bold' }}>
+ {formatLargeNumber(totalPnL, currency)}
+ </div>
+ <div style={{ color: totalPnL >= 0 ? GREEN : RED, fontSize: '10px', marginTop: '2px' }}>
+ {formatPercent(totalPnLPercent)}
+ </div>
+ </div>
+
+ {/* Day Change Card */}
+ <div style={{
+ backgroundColor: dayChange >= 0 ? 'rgba(0,200,0,0.1)' : 'rgba(255,0,0,0.1)',
+ border: `1px solid ${dayChange >= 0 ? GREEN : RED}`,
+ padding: '12px',
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>DAY CHANGE</div>
+ <div style={{ color: dayChange >= 0 ? GREEN : RED, fontSize: '16px', fontWeight: 'bold' }}>
+ {formatLargeNumber(dayChange, currency)}
+ </div>
+ <div style={{ color: dayChange >= 0 ? GREEN : RED, fontSize: '10px', marginTop: '2px' }}>
+ {formatPercent(dayChangePercent)}
+ </div>
+ </div>
+
+ {/* Positions Card */}
+ <div style={{
+ backgroundColor: 'rgba(0,255,255,0.1)',
+ border: `1px solid ${CYAN}`,
+ padding: '12px',
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>POSITIONS</div>
+ <div style={{ color: CYAN, fontSize: '16px', fontWeight: 'bold' }}>
+ {positionsCount}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Active Holdings
+ </div>
+ </div>
+ </div>
+
+ {/* Performance Section */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px' }}>
+ {/* Top Gainers */}
+ <div>
+ <div style={{
+ color: GREEN,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${GREEN}`
+ }}>
+ TOP GAINERS
+ </div>
+ {topGainers.length === 0 ? (
+ <div style={{ color: GRAY, fontSize: '10px', padding: '8px' }}>No data</div>
+ ) : (
+ topGainers.map(holding => (
+ <div
+ key={holding.id}
+ style={{
+ padding: '8px',
+ marginBottom: '4px',
+ backgroundColor: 'rgba(0,200,0,0.05)',
+ borderLeft: `3px solid ${GREEN}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}
+ >
+ <div>
+ <div style={{ color: CYAN, fontSize: '10px', fontWeight: 'bold' }}>
+ {holding.symbol}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px' }}>
+ {formatCurrency(holding.market_value, currency)}
+ </div>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{ color: GREEN, fontSize: '10px', fontWeight: 'bold' }}>
+ {formatPercent(holding.unrealized_pnl_percent)}
+ </div>
+ <div style={{ color: GREEN, fontSize: '8px' }}>
+ {formatCurrency(holding.unrealized_pnl, currency)}
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Top Losers */}
+ <div>
+ <div style={{
+ color: RED,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${RED}`
+ }}>
+ TOP LOSERS
+ </div>
+ {topLosers.length === 0 ? (
+ <div style={{ color: GRAY, fontSize: '10px', padding: '8px' }}>No data</div>
+ ) : (
+ topLosers.map(holding => (
+ <div
+ key={holding.id}
+ style={{
+ padding: '8px',
+ marginBottom: '4px',
+ backgroundColor: 'rgba(255,0,0,0.05)',
+ borderLeft: `3px solid ${RED}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}
+ >
+ <div>
+ <div style={{ color: CYAN, fontSize: '10px', fontWeight: 'bold' }}>
+ {holding.symbol}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px' }}>
+ {formatCurrency(holding.market_value, currency)}
+ </div>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{ color: RED, fontSize: '10px', fontWeight: 'bold' }}>
+ {formatPercent(holding.unrealized_pnl_percent)}
+ </div>
+ <div style={{ color: RED, fontSize: '8px' }}>
+ {formatCurrency(holding.unrealized_pnl, currency)}
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Largest Positions */}
+ <div>
+ <div style={{
+ color: BLUE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${BLUE}`
+ }}>
+ LARGEST POSITIONS
+ </div>
+ {largestPositions.length === 0 ? (
+ <div style={{ color: GRAY, fontSize: '10px', padding: '8px' }}>No data</div>
+ ) : (
+ largestPositions.map(holding => (
+ <div
+ key={holding.id}
+ style={{
+ padding: '8px',
+ marginBottom: '4px',
+ backgroundColor: 'rgba(100,150,250,0.05)',
+ borderLeft: `3px solid ${BLUE}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}
+ >
+ <div>
+ <div style={{ color: CYAN, fontSize: '10px', fontWeight: 'bold' }}>
+ {holding.symbol}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px' }}>
+ Weight: {holding.weight.toFixed(1)}%
+ </div>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{ color: WHITE, fontSize: '10px', fontWeight: 'bold' }}>
+ {formatLargeNumber(holding.market_value, currency)}
+ </div>
+ <div style={{
+ color: holding.unrealized_pnl >= 0 ? GREEN : RED,
+ fontSize: '8px'
+ }}>
+ {formatPercent(holding.unrealized_pnl_percent)}
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+
+ {/* Allocation Summary */}
+ <div style={{ marginTop: '20px' }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ ALLOCATION BREAKDOWN
+ </div>
+
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',
+ gap: '8px'
+ }}>
+ {portfolioSummary.holdings.map(holding => (
+ <div
+ key={holding.id}
+ style={{
+ padding: '8px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid rgba(120,120,120,0.3)`,
+ borderRadius: '2px'
+ }}
+ >
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '4px'
+ }}>
+ <span style={{ color: CYAN, fontSize: '10px', fontWeight: 'bold' }}>
+ {holding.symbol}
+ </span>
+ <span style={{ color: YELLOW, fontSize: '10px', fontWeight: 'bold' }}>
+ {holding.weight.toFixed(1)}%
+ </span>
+ </div>
+ <div style={{
+ width: '100%',
+ height: '4px',
+ backgroundColor: 'rgba(120,120,120,0.3)',
+ borderRadius: '2px',
+ overflow: 'hidden'
+ }}>
+ <div style={{
+ width: `${holding.weight}%`,
+ height: '100%',
+ backgroundColor: YELLOW,
+ transition: 'width 0.3s'
+ }} />
+ </div>
+ <div style={{
+ marginTop: '4px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ fontSize: '8px',
+ color: GRAY
+ }}>
+ <span>{formatLargeNumber(holding.market_value, currency)}</span>
+ <span style={{
+ color: holding.unrealized_pnl >= 0 ? GREEN : RED
+ }}>
+ {formatPercent(holding.unrealized_pnl_percent)}
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default AnalyticsView;
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/HistoryView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio/HistoryView.tsx
new file mode 100644
index 000000000..5e69e83de
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/HistoryView.tsx
@@ -0,0 +1,88 @@
+import React from 'react';
+import { Transaction } from '../../../services/portfolioService';
+import { BLOOMBERG_COLORS, formatCurrency, formatNumber, formatDateTime } from './utils';
+
+interface HistoryViewProps {
+ transactions: Transaction[];
+ currency: string;
+}
+
+const HistoryView: React.FC<HistoryViewProps> = ({ transactions, currency }) => {
+ const { ORANGE, WHITE, RED, GREEN, GRAY, CYAN, YELLOW } = BLOOMBERG_COLORS;
+
+ return (
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '12px'
+ }}>
+ TRANSACTION HISTORY
+ </div>
+
+ {transactions.length === 0 ? (
+ <div style={{ padding: '32px', textAlign: 'center', color: GRAY, fontSize: '11px' }}>
+ No transactions yet
+ </div>
+ ) : (
+ <div>
+ {/* Table Header */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1.5fr 1fr 0.8fr 1fr 1fr 1fr 2fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ <div style={{ color: WHITE }}>DATE</div>
+ <div style={{ color: WHITE }}>SYMBOL</div>
+ <div style={{ color: WHITE }}>TYPE</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>QTY</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>PRICE</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>TOTAL</div>
+ <div style={{ color: WHITE }}>NOTES</div>
+ </div>
+
+ {transactions.map((txn, index) => (
+ <div
+ key={txn.id}
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1.5fr 1fr 0.8fr 1fr 1fr 1fr 2fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ borderLeft: `3px solid ${txn.transaction_type === 'BUY' ? GREEN : RED}`,
+ fontSize: '10px',
+ marginBottom: '2px'
+ }}
+ >
+ <div style={{ color: GRAY }}>
+ {formatDateTime(txn.transaction_date)}
+ </div>
+ <div style={{ color: CYAN }}>{txn.symbol}</div>
+ <div style={{
+ color: txn.transaction_type === 'BUY' ? GREEN : RED,
+ fontWeight: 'bold'
+ }}>
+ {txn.transaction_type}
+ </div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>{formatNumber(txn.quantity, 4)}</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>{formatCurrency(txn.price, currency)}</div>
+ <div style={{ color: YELLOW, textAlign: 'right', fontWeight: 'bold' }}>
+ {formatCurrency(txn.total_value, currency)}
+ </div>
+ <div style={{ color: GRAY, fontSize: '9px' }}>{txn.notes || '-'}</div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default HistoryView;
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/PerformanceView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio/PerformanceView.tsx
new file mode 100644
index 000000000..7807ac2ce
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/PerformanceView.tsx
@@ -0,0 +1,459 @@
+import React, { useState, useEffect } from 'react';
+import { PortfolioSummary, portfolioService, PortfolioSnapshot } from '../../../services/portfolioService';
+import { BLOOMBERG_COLORS, formatCurrency, formatPercent } from './utils';
+
+interface PerformanceViewProps {
+ portfolioSummary: PortfolioSummary;
+}
+
+interface PerformanceDataPoint {
+ date: string;
+ value: number;
+ change: number;
+ changePercent: number;
+}
+
+const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) => {
+ const { ORANGE, WHITE, RED, GREEN, GRAY, CYAN, YELLOW } = BLOOMBERG_COLORS;
+ const currency = portfolioSummary.portfolio.currency;
+ const [performanceData, setPerformanceData] = useState<PerformanceDataPoint[]>([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ const loadPerformanceData = async () => {
+ try {
+ // Fetch portfolio snapshots from database
+ const snapshots = await portfolioService.getPortfolioPerformanceHistory(
+ portfolioSummary.portfolio.id,
+ 30
+ );
+
+ if (snapshots.length === 0) {
+ // No historical data, use current value only
+ setPerformanceData([{
+ date: new Date().toISOString().split('T')[0],
+ value: portfolioSummary.total_market_value,
+ change: portfolioSummary.total_unrealized_pnl,
+ changePercent: portfolioSummary.total_unrealized_pnl_percent
+ }]);
+ } else {
+ // Convert snapshots to performance data points
+ const data = snapshots
+ .reverse() // Oldest first
+ .map(snapshot => ({
+ date: snapshot.snapshot_date.split('T')[0],
+ value: snapshot.total_value,
+ change: snapshot.total_pnl,
+ changePercent: snapshot.total_pnl_percent
+ }));
+
+ // Add current value as latest data point if not already present
+ const latestDate = new Date().toISOString().split('T')[0];
+ const hasToday = data.some(d => d.date === latestDate);
+
+ if (!hasToday) {
+ data.push({
+ date: latestDate,
+ value: portfolioSummary.total_market_value,
+ change: portfolioSummary.total_unrealized_pnl,
+ changePercent: portfolioSummary.total_unrealized_pnl_percent
+ });
+ }
+
+ setPerformanceData(data);
+ }
+ } catch (error) {
+ console.error('Failed to load performance data:', error);
+ // Fallback to current value
+ setPerformanceData([{
+ date: new Date().toISOString().split('T')[0],
+ value: portfolioSummary.total_market_value,
+ change: portfolioSummary.total_unrealized_pnl,
+ changePercent: portfolioSummary.total_unrealized_pnl_percent
+ }]);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ loadPerformanceData();
+ }, [portfolioSummary.portfolio.id, portfolioSummary.total_market_value]);
+
+ if (loading) {
+ return (
+ <div style={{
+ padding: '40px',
+ textAlign: 'center',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: ORANGE, fontSize: '14px', marginBottom: '8px' }}>
+ Loading performance data...
+ </div>
+ <div style={{ color: GRAY, fontSize: '10px' }}>
+ Fetching portfolio snapshots from database
+ </div>
+ </div>
+ );
+ }
+
+ if (performanceData.length === 0) {
+ return (
+ <div style={{
+ padding: '40px',
+ textAlign: 'center',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '14px', marginBottom: '8px' }}>
+ No performance data available
+ </div>
+ <div style={{ color: GRAY, fontSize: '10px' }}>
+ Portfolio snapshots will be created automatically as you use the application
+ </div>
+ </div>
+ );
+ }
+
+ // Calculate chart dimensions
+ const chartWidth = 800;
+ const chartHeight = 300;
+ const padding = { top: 20, right: 40, bottom: 40, left: 60 };
+ const innerWidth = chartWidth - padding.left - padding.right;
+ const innerHeight = chartHeight - padding.top - padding.bottom;
+
+ // Scale functions
+ const maxValue = Math.max(...performanceData.map(d => d.value));
+ const minValue = Math.min(...performanceData.map(d => d.value));
+ const valueRange = maxValue - minValue;
+
+ const xScale = (index: number) => {
+ return (index / (performanceData.length - 1)) * innerWidth + padding.left;
+ };
+
+ const yScale = (value: number) => {
+ return chartHeight - padding.bottom - ((value - minValue) / valueRange) * innerHeight;
+ };
+
+ // Create path for line chart
+ const linePath = performanceData
+ .map((d, i) => {
+ const x = xScale(i);
+ const y = yScale(d.value);
+ return `${i === 0 ? 'M' : 'L'} ${x} ${y}`;
+ })
+ .join(' ');
+
+ // Create area path
+ const areaPath = linePath +
+ ` L ${xScale(performanceData.length - 1)} ${chartHeight - padding.bottom}` +
+ ` L ${padding.left} ${chartHeight - padding.bottom} Z`;
+
+ // Performance metrics
+ const latestValue = performanceData[performanceData.length - 1].value;
+ const earliestValue = performanceData[0].value;
+ const periodReturn = ((latestValue - earliestValue) / earliestValue) * 100;
+ const periodGain = latestValue - earliestValue;
+
+ return (
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '16px'
+ }}>
+ PERFORMANCE CHART ({performanceData.length} DAY{performanceData.length > 1 ? 'S' : ''})
+ </div>
+
+ {/* Performance Metrics Bar */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(5, 1fr)',
+ gap: '12px',
+ marginBottom: '20px'
+ }}>
+ <div style={{
+ padding: '10px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>PERIOD RETURN</div>
+ <div style={{
+ color: periodReturn >= 0 ? GREEN : RED,
+ fontSize: '14px',
+ fontWeight: 'bold'
+ }}>
+ {formatPercent(periodReturn)}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '10px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>PERIOD GAIN</div>
+ <div style={{
+ color: periodGain >= 0 ? GREEN : RED,
+ fontSize: '14px',
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(periodGain, currency)}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '10px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>CURRENT VALUE</div>
+ <div style={{ color: YELLOW, fontSize: '14px', fontWeight: 'bold' }}>
+ {formatCurrency(latestValue, currency)}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '10px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>START VALUE</div>
+ <div style={{ color: CYAN, fontSize: '14px', fontWeight: 'bold' }}>
+ {formatCurrency(earliestValue, currency)}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '10px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>VOLATILITY</div>
+ <div style={{ color: ORANGE, fontSize: '14px', fontWeight: 'bold' }}>
+ {((valueRange / earliestValue) * 100).toFixed(2)}%
+ </div>
+ </div>
+ </div>
+
+ {/* Chart */}
+ <div style={{
+ backgroundColor: 'rgba(0,0,0,0.3)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px',
+ padding: '16px',
+ marginBottom: '20px'
+ }}>
+ <svg width={chartWidth} height={chartHeight}>
+ {/* Grid lines */}
+ {[0, 0.25, 0.5, 0.75, 1].map((ratio, i) => {
+ const y = chartHeight - padding.bottom - (innerHeight * ratio);
+ const value = minValue + (valueRange * ratio);
+ return (
+ <g key={i}>
+ <line
+ x1={padding.left}
+ y1={y}
+ x2={chartWidth - padding.right}
+ y2={y}
+ stroke={GRAY}
+ strokeWidth="0.5"
+ strokeDasharray="4,4"
+ opacity="0.3"
+ />
+ <text
+ x={padding.left - 10}
+ y={y + 4}
+ textAnchor="end"
+ fill={GRAY}
+ fontSize="9"
+ fontFamily="Consolas, monospace"
+ >
+ {formatCurrency(value, currency)}
+ </text>
+ </g>
+ );
+ })}
+
+ {/* Date labels */}
+ {performanceData.filter((_, i) => i % 5 === 0).map((d, i) => {
+ const originalIndex = i * 5;
+ const x = xScale(originalIndex);
+ return (
+ <text
+ key={i}
+ x={x}
+ y={chartHeight - padding.bottom + 20}
+ textAnchor="middle"
+ fill={GRAY}
+ fontSize="8"
+ fontFamily="Consolas, monospace"
+ >
+ {d.date.substring(5)}
+ </text>
+ );
+ })}
+
+ {/* Area fill */}
+ <path
+ d={areaPath}
+ fill={periodReturn >= 0 ? GREEN : RED}
+ opacity="0.1"
+ />
+
+ {/* Line */}
+ <path
+ d={linePath}
+ fill="none"
+ stroke={periodReturn >= 0 ? GREEN : RED}
+ strokeWidth="2"
+ />
+
+ {/* Data points */}
+ {performanceData.map((d, i) => (
+ <circle
+ key={i}
+ cx={xScale(i)}
+ cy={yScale(d.value)}
+ r="3"
+ fill={d.changePercent >= 0 ? GREEN : RED}
+ stroke="#000"
+ strokeWidth="1"
+ />
+ ))}
+
+ {/* Cost basis line */}
+ <line
+ x1={padding.left}
+ y1={yScale(portfolioSummary.total_cost_basis)}
+ x2={chartWidth - padding.right}
+ y2={yScale(portfolioSummary.total_cost_basis)}
+ stroke={YELLOW}
+ strokeWidth="2"
+ strokeDasharray="8,4"
+ />
+ <text
+ x={chartWidth - padding.right - 10}
+ y={yScale(portfolioSummary.total_cost_basis) - 8}
+ textAnchor="end"
+ fill={YELLOW}
+ fontSize="10"
+ fontWeight="bold"
+ fontFamily="Consolas, monospace"
+ >
+ COST BASIS
+ </text>
+
+ {/* Chart title */}
+ <text
+ x={chartWidth / 2}
+ y={15}
+ textAnchor="middle"
+ fill={ORANGE}
+ fontSize="12"
+ fontWeight="bold"
+ fontFamily="Consolas, monospace"
+ >
+ PORTFOLIO VALUE OVER TIME
+ </text>
+ </svg>
+ </div>
+
+ {/* Performance Table */}
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ DAILY PERFORMANCE DATA
+ </div>
+
+ <div style={{ maxHeight: '300px', overflow: 'auto' }}>
+ {/* Table Header */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1.2fr 1fr 1fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ position: 'sticky',
+ top: 0,
+ zIndex: 1
+ }}>
+ <div style={{ color: WHITE }}>DATE</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>VALUE</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>CHANGE</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>CHANGE %</div>
+ </div>
+
+ {/* Table Rows */}
+ {performanceData.slice().reverse().map((d, index) => (
+ <div
+ key={d.date}
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1.2fr 1fr 1fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ borderLeft: `3px solid ${d.changePercent >= 0 ? GREEN : RED}`,
+ fontSize: '10px',
+ marginBottom: '2px'
+ }}
+ >
+ <div style={{ color: GRAY }}>{d.date}</div>
+ <div style={{ color: WHITE, textAlign: 'right', fontWeight: 'bold' }}>
+ {formatCurrency(d.value, currency)}
+ </div>
+ <div style={{
+ color: d.change >= 0 ? GREEN : RED,
+ textAlign: 'right',
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(d.change, currency)}
+ </div>
+ <div style={{
+ color: d.changePercent >= 0 ? GREEN : RED,
+ textAlign: 'right',
+ fontWeight: 'bold'
+ }}>
+ {formatPercent(d.changePercent)}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Info Note */}
+ {performanceData.length < 7 && (
+ <div style={{
+ marginTop: '16px',
+ padding: '12px',
+ backgroundColor: 'rgba(255,165,0,0.05)',
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px',
+ fontSize: '9px',
+ color: GRAY
+ }}>
+ <strong style={{ color: ORANGE }}>TIP:</strong> Portfolio snapshots are created automatically.
+ More historical data will be available as you continue to use the application.
+ Current data points: {performanceData.length}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default PerformanceView;
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/PositionsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio/PositionsView.tsx
new file mode 100644
index 000000000..edd64a744
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/PositionsView.tsx
@@ -0,0 +1,169 @@
+import React from 'react';
+import { PortfolioSummary } from '../../../services/portfolioService';
+import { BLOOMBERG_COLORS, formatCurrency, formatNumber, formatPercent } from './utils';
+
+interface PositionsViewProps {
+ portfolioSummary: PortfolioSummary;
+}
+
+const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
+ const { ORANGE, WHITE, RED, GREEN, GRAY, CYAN, YELLOW } = BLOOMBERG_COLORS;
+ const currency = portfolioSummary.portfolio.currency;
+
+ return (
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '12px'
+ }}>
+ CURRENT POSITIONS
+ </div>
+
+ {/* Table Header */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr 1fr 1.2fr 1fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ <div style={{ color: WHITE }}>SYMBOL</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>QTY</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>AVG PRICE</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>CURRENT</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>MKT VALUE</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>COST BASIS</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>P&L</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>DAY CHANGE</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>WEIGHT</div>
+ </div>
+
+ {/* Position Rows */}
+ {portfolioSummary.holdings.length === 0 ? (
+ <div style={{
+ padding: '32px',
+ textAlign: 'center',
+ color: GRAY,
+ fontSize: '11px'
+ }}>
+ No positions yet. Click F2 or "ADD ASSET" to add your first position.
+ </div>
+ ) : (
+ portfolioSummary.holdings.map((holding, index) => (
+ <div
+ key={holding.id}
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr 1fr 1.2fr 1fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ borderLeft: `3px solid ${holding.unrealized_pnl >= 0 ? GREEN : RED}`,
+ fontSize: '10px',
+ marginBottom: '2px'
+ }}
+ >
+ <div style={{ color: CYAN, fontWeight: 'bold' }}>{holding.symbol}</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>{formatNumber(holding.quantity, 4)}</div>
+ <div style={{ color: GRAY, textAlign: 'right' }}>{formatCurrency(holding.avg_buy_price, currency)}</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>{formatCurrency(holding.current_price, currency)}</div>
+ <div style={{ color: WHITE, textAlign: 'right', fontWeight: 'bold' }}>
+ {formatCurrency(holding.market_value, currency)}
+ </div>
+ <div style={{ color: GRAY, textAlign: 'right' }}>{formatCurrency(holding.cost_basis, currency)}</div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{
+ color: holding.unrealized_pnl >= 0 ? GREEN : RED,
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(holding.unrealized_pnl, currency)}
+ </div>
+ <div style={{
+ color: holding.unrealized_pnl >= 0 ? GREEN : RED,
+ fontSize: '9px'
+ }}>
+ {formatPercent(holding.unrealized_pnl_percent)}
+ </div>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{
+ color: holding.day_change >= 0 ? GREEN : RED
+ }}>
+ {formatCurrency(holding.day_change, currency)}
+ </div>
+ <div style={{
+ color: holding.day_change >= 0 ? GREEN : RED,
+ fontSize: '9px'
+ }}>
+ {formatPercent(holding.day_change_percent)}
+ </div>
+ </div>
+ <div style={{ color: YELLOW, textAlign: 'right', fontWeight: 'bold' }}>
+ {formatNumber(holding.weight)}%
+ </div>
+ </div>
+ ))
+ )}
+
+ {/* Totals Row */}
+ {portfolioSummary.holdings.length > 0 && (
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr 1fr 1.2fr 1fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: 'rgba(255,165,0,0.15)',
+ borderTop: `2px solid ${ORANGE}`,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginTop: '8px'
+ }}>
+ <div style={{ color: ORANGE }}>TOTAL</div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>
+ {formatCurrency(portfolioSummary.total_market_value, currency)}
+ </div>
+ <div style={{ color: GRAY, textAlign: 'right' }}>
+ {formatCurrency(portfolioSummary.total_cost_basis, currency)}
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? GREEN : RED
+ }}>
+ {formatCurrency(portfolioSummary.total_unrealized_pnl, currency)}
+ </div>
+ <div style={{
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? GREEN : RED,
+ fontSize: '9px'
+ }}>
+ {formatPercent(portfolioSummary.total_unrealized_pnl_percent)}
+ </div>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{
+ color: portfolioSummary.total_day_change >= 0 ? GREEN : RED
+ }}>
+ {formatCurrency(portfolioSummary.total_day_change, currency)}
+ </div>
+ <div style={{
+ color: portfolioSummary.total_day_change >= 0 ? GREEN : RED,
+ fontSize: '9px'
+ }}>
+ {formatPercent(portfolioSummary.total_day_change_percent)}
+ </div>
+ </div>
+ <div style={{ color: YELLOW, textAlign: 'right' }}>100.0%</div>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default PositionsView;
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/README.md b/fincept-terminal-desktop/src/components/tabs/portfolio/README.md
new file mode 100644
index 000000000..48f3567d0
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/README.md
@@ -0,0 +1,63 @@
+# Fincept Portfolio Tab - Modular Implementation
+
+## ✅ Completed Files
+
+### 1. utils.ts
+- Currency formatting for USD, EUR, GBP, INR, JPY, etc.
+- All calculation functions (Sharpe, Beta, Volatility, etc.)
+- Tax calculations (FIFO-based capital gains)
+- Formatting helpers
+
+### 2. PositionsView.tsx
+- Displays current holdings with live prices
+- Shows P&L, day change, portfolio weights
+- **Fixed: Now respects portfolio currency (INR, USD, etc.)**
+
+### 3. HistoryView.tsx
+- Transaction history with full details
+- Buy/Sell indicators
+- **Fixed: Currency formatting**
+
+## 🚀 Quick Start
+
+The main PortfolioTab.tsx now imports from this modular structure:
+
+```typescript
+import PositionsView from './portfolio/PositionsView';
+import HistoryView from './portfolio/HistoryView';
+import { formatCurrency } from './portfolio/utils';
+```
+
+## 📊 Remaining Views to Create (Optional)
+
+Create these files in `src/components/tabs/portfolio/`:
+
+1. **SectorsView.tsx** - Pie chart of sector allocation
+2. **AnalyticsView.tsx** - Dashboard with multiple charts
+3. **PerformanceView.tsx** - Time-series performance
+4. **RiskMetricsView.tsx** - Sharpe, Beta, Volatility display
+5. **AlertsView.tsx** - Price alerts management
+6. **ReportsView.tsx** - Tax reports and PDF export
+
+## 💡 Currency Support
+
+The system now properly handles multiple currencies:
+
+```typescript
+// utils.ts provides
+formatCurrency(1000, 'USD') // → "$1,000.00"
+formatCurrency(1000, 'INR') // → "₹1,000.00"
+formatCurrency(1000, 'EUR') // → "€1,000.00"
+```
+
+All views automatically use the portfolio's currency setting.
+
+## 🔧 Integration Status
+
+✅ Currency formatting fixed
+✅ Modular structure created
+✅ PositionsView with proper INR/USD support
+✅ HistoryView with currency support
+⏳ Advanced charts (optional enhancements)
+
+The portfolio system is now **fully functional** with proper currency support!
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/ReportsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio/ReportsView.tsx
new file mode 100644
index 000000000..3360534a3
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/ReportsView.tsx
@@ -0,0 +1,384 @@
+import React from 'react';
+import { PortfolioSummary, Transaction } from '../../../services/portfolioService';
+import { BLOOMBERG_COLORS, formatCurrency, formatPercent, calculateTaxLiability } from './utils';
+
+interface ReportsViewProps {
+ portfolioSummary: PortfolioSummary;
+ transactions: Transaction[];
+}
+
+const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transactions }) => {
+ const { ORANGE, WHITE, RED, GREEN, GRAY, CYAN, YELLOW } = BLOOMBERG_COLORS;
+ const currency = portfolioSummary.portfolio.currency;
+
+ // Calculate tax liability
+ const taxCalculation = calculateTaxLiability(transactions, 0.15, 0.20, 365);
+
+ // Calculate dividend info (mock data)
+ const totalDividends = 0; // Would come from dividend_transactions table
+ const dividendYield = 0;
+
+ return (
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '16px'
+ }}>
+ TAX REPORTS & STATEMENTS
+ </div>
+
+ {/* Summary Cards */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '12px',
+ marginBottom: '24px'
+ }}>
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>TOTAL TAX LIABILITY</div>
+ <div style={{ color: ORANGE, fontSize: '16px', fontWeight: 'bold' }}>
+ {formatCurrency(taxCalculation.totalTax, currency)}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(0,200,0,0.1)',
+ border: `1px solid ${GREEN}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>LONG-TERM GAINS</div>
+ <div style={{ color: GREEN, fontSize: '16px', fontWeight: 'bold' }}>
+ {formatCurrency(taxCalculation.longTermGains, currency)}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Tax: {formatCurrency(taxCalculation.longTermTax, currency)}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(255,255,0,0.1)',
+ border: `1px solid ${YELLOW}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>SHORT-TERM GAINS</div>
+ <div style={{ color: YELLOW, fontSize: '16px', fontWeight: 'bold' }}>
+ {formatCurrency(taxCalculation.shortTermGains, currency)}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Tax: {formatCurrency(taxCalculation.shortTermTax, currency)}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(0,255,255,0.1)',
+ border: `1px solid ${CYAN}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>UNREALIZED GAINS</div>
+ <div style={{
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? GREEN : RED,
+ fontSize: '16px',
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(portfolioSummary.total_unrealized_pnl, currency)}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Not taxable until sold
+ </div>
+ </div>
+ </div>
+
+ {/* Tax Breakdown */}
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ TAX BREAKDOWN (FIFO METHOD)
+ </div>
+
+ <div style={{
+ padding: '16px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px',
+ marginBottom: '24px'
+ }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: '12px', marginBottom: '12px' }}>
+ <div style={{ color: WHITE, fontSize: '10px', fontWeight: 'bold' }}>CATEGORY</div>
+ <div style={{ color: WHITE, fontSize: '10px', fontWeight: 'bold', textAlign: 'right' }}>GAINS</div>
+ <div style={{ color: WHITE, fontSize: '10px', fontWeight: 'bold', textAlign: 'right' }}>TAX RATE</div>
+ <div style={{ color: WHITE, fontSize: '10px', fontWeight: 'bold', textAlign: 'right' }}>TAX DUE</div>
+ </div>
+
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr 1fr',
+ gap: '12px',
+ padding: '12px',
+ backgroundColor: 'rgba(255,255,0,0.05)',
+ borderLeft: `3px solid ${YELLOW}`,
+ marginBottom: '8px'
+ }}>
+ <div style={{ color: YELLOW, fontSize: '10px', fontWeight: 'bold' }}>
+ Short-Term Capital Gains (&lt; 1 year)
+ </div>
+ <div style={{ color: WHITE, fontSize: '10px', textAlign: 'right' }}>
+ {formatCurrency(taxCalculation.shortTermGains, currency)}
+ </div>
+ <div style={{ color: GRAY, fontSize: '10px', textAlign: 'right' }}>15%</div>
+ <div style={{ color: ORANGE, fontSize: '10px', textAlign: 'right', fontWeight: 'bold' }}>
+ {formatCurrency(taxCalculation.shortTermTax, currency)}
+ </div>
+ </div>
+
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr 1fr',
+ gap: '12px',
+ padding: '12px',
+ backgroundColor: 'rgba(0,200,0,0.05)',
+ borderLeft: `3px solid ${GREEN}`,
+ marginBottom: '8px'
+ }}>
+ <div style={{ color: GREEN, fontSize: '10px', fontWeight: 'bold' }}>
+ Long-Term Capital Gains (&gt; 1 year)
+ </div>
+ <div style={{ color: WHITE, fontSize: '10px', textAlign: 'right' }}>
+ {formatCurrency(taxCalculation.longTermGains, currency)}
+ </div>
+ <div style={{ color: GRAY, fontSize: '10px', textAlign: 'right' }}>20%</div>
+ <div style={{ color: ORANGE, fontSize: '10px', textAlign: 'right', fontWeight: 'bold' }}>
+ {formatCurrency(taxCalculation.longTermTax, currency)}
+ </div>
+ </div>
+
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr 1fr',
+ gap: '12px',
+ padding: '12px',
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ borderTop: `2px solid ${ORANGE}`,
+ marginTop: '8px'
+ }}>
+ <div style={{ color: ORANGE, fontSize: '11px', fontWeight: 'bold' }}>TOTAL TAX DUE</div>
+ <div></div>
+ <div></div>
+ <div style={{ color: ORANGE, fontSize: '12px', textAlign: 'right', fontWeight: 'bold' }}>
+ {formatCurrency(taxCalculation.totalTax, currency)}
+ </div>
+ </div>
+ </div>
+
+ {/* Additional Information */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
+ {/* Transaction Summary */}
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ TRANSACTION SUMMARY
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`
+ }}>
+ <span style={{ color: GRAY, fontSize: '10px' }}>Total Transactions:</span>
+ <span style={{ color: WHITE, fontSize: '10px', fontWeight: 'bold' }}>
+ {transactions.length}
+ </span>
+ </div>
+
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`
+ }}>
+ <span style={{ color: GRAY, fontSize: '10px' }}>Buy Transactions:</span>
+ <span style={{ color: GREEN, fontSize: '10px', fontWeight: 'bold' }}>
+ {transactions.filter(t => t.transaction_type === 'BUY').length}
+ </span>
+ </div>
+
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`
+ }}>
+ <span style={{ color: GRAY, fontSize: '10px' }}>Sell Transactions:</span>
+ <span style={{ color: RED, fontSize: '10px', fontWeight: 'bold' }}>
+ {transactions.filter(t => t.transaction_type === 'SELL').length}
+ </span>
+ </div>
+
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between'
+ }}>
+ <span style={{ color: GRAY, fontSize: '10px' }}>Current Positions:</span>
+ <span style={{ color: CYAN, fontSize: '10px', fontWeight: 'bold' }}>
+ {portfolioSummary.holdings.length}
+ </span>
+ </div>
+ </div>
+ </div>
+
+ {/* Dividend Information */}
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ DIVIDEND INCOME
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`
+ }}>
+ <span style={{ color: GRAY, fontSize: '10px' }}>Total Dividends (YTD):</span>
+ <span style={{ color: GREEN, fontSize: '10px', fontWeight: 'bold' }}>
+ {formatCurrency(totalDividends, currency)}
+ </span>
+ </div>
+
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`
+ }}>
+ <span style={{ color: GRAY, fontSize: '10px' }}>Portfolio Yield:</span>
+ <span style={{ color: CYAN, fontSize: '10px', fontWeight: 'bold' }}>
+ {dividendYield.toFixed(2)}%
+ </span>
+ </div>
+
+ <div style={{
+ padding: '8px',
+ backgroundColor: 'rgba(120,120,120,0.1)',
+ borderRadius: '2px',
+ marginTop: '8px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', textAlign: 'center' }}>
+ Dividend tracking coming soon...
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Export Options */}
+ <div style={{
+ marginTop: '24px',
+ padding: '16px',
+ backgroundColor: 'rgba(255,165,0,0.05)',
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px'
+ }}>
+ EXPORT OPTIONS
+ </div>
+
+ <div style={{ display: 'flex', gap: '12px' }}>
+ <button style={{
+ padding: '10px 16px',
+ backgroundColor: ORANGE,
+ color: 'black',
+ border: 'none',
+ borderRadius: '4px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}>
+ EXPORT TAX REPORT (PDF)
+ </button>
+
+ <button style={{
+ padding: '10px 16px',
+ backgroundColor: GREEN,
+ color: 'black',
+ border: 'none',
+ borderRadius: '4px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}>
+ EXPORT TRANSACTIONS (CSV)
+ </button>
+
+ <button style={{
+ padding: '10px 16px',
+ backgroundColor: CYAN,
+ color: 'black',
+ border: 'none',
+ borderRadius: '4px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}>
+ EXPORT HOLDINGS (XLSX)
+ </button>
+ </div>
+
+ <div style={{ marginTop: '12px', fontSize: '8px', color: GRAY }}>
+ Reports are generated for the current tax year. Consult with a tax professional for accurate filing.
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default ReportsView;
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/RiskMetricsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio/RiskMetricsView.tsx
new file mode 100644
index 000000000..e11e3ea9c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/RiskMetricsView.tsx
@@ -0,0 +1,486 @@
+import React, { useState, useEffect } from 'react';
+import { PortfolioSummary, portfolioService } from '../../../services/portfolioService';
+import {
+ BLOOMBERG_COLORS,
+ formatPercent,
+ calculateSharpeRatio,
+ calculateBeta,
+ calculateVolatility,
+ calculateMaxDrawdown,
+ calculateVaR
+} from './utils';
+
+interface RiskMetricsViewProps {
+ portfolioSummary: PortfolioSummary;
+}
+
+const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) => {
+ const { ORANGE, WHITE, RED, GREEN, GRAY, CYAN, YELLOW, BLUE } = BLOOMBERG_COLORS;
+ const [loading, setLoading] = useState(true);
+ const [portfolioReturns, setPortfolioReturns] = useState<number[]>([]);
+ const [portfolioValues, setPortfolioValues] = useState<number[]>([]);
+
+ useEffect(() => {
+ const loadRiskData = async () => {
+ try {
+ // Fetch portfolio snapshots for risk calculations
+ const snapshots = await portfolioService.getPortfolioPerformanceHistory(
+ portfolioSummary.portfolio.id,
+ 252 // Last ~1 year of data
+ );
+
+ if (snapshots.length > 1) {
+ // Calculate daily returns from snapshots
+ const returns: number[] = [];
+ const values: number[] = [];
+
+ for (let i = snapshots.length - 1; i >= 0; i--) {
+ values.push(snapshots[i].total_value);
+
+ if (i < snapshots.length - 1) {
+ const prevValue = snapshots[i + 1].total_value;
+ const currentValue = snapshots[i].total_value;
+ const dailyReturn = (currentValue - prevValue) / prevValue;
+ returns.push(dailyReturn);
+ }
+ }
+
+ setPortfolioReturns(returns);
+ setPortfolioValues(values);
+ } else {
+ // Not enough historical data
+ setPortfolioReturns([]);
+ setPortfolioValues([portfolioSummary.total_market_value]);
+ }
+ } catch (error) {
+ console.error('Failed to load risk metrics data:', error);
+ setPortfolioReturns([]);
+ setPortfolioValues([portfolioSummary.total_market_value]);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ loadRiskData();
+ }, [portfolioSummary.portfolio.id]);
+
+ // Calculate risk metrics from real data
+ const sharpeRatio = portfolioReturns.length > 0 ? calculateSharpeRatio(portfolioReturns) : 0;
+ const beta = portfolioReturns.length > 0 ? calculateBeta(portfolioReturns, portfolioReturns) : 1; // Using portfolio returns as market proxy until we have real market data
+ const volatility = portfolioReturns.length > 0 ? calculateVolatility(portfolioReturns) : 0;
+ const maxDrawdown = portfolioValues.length > 1 ? calculateMaxDrawdown(portfolioValues) : 0;
+ const var95 = portfolioReturns.length > 0 ? calculateVaR(portfolioReturns, 0.95) : 0;
+
+ const hasInsufficientData = portfolioReturns.length < 5;
+
+ // Risk level determination
+ const getRiskLevel = (sharpe: number) => {
+ if (sharpe > 2) return { level: 'LOW', color: GREEN };
+ if (sharpe > 1) return { level: 'MODERATE', color: YELLOW };
+ if (sharpe > 0) return { level: 'HIGH', color: ORANGE };
+ return { level: 'VERY HIGH', color: RED };
+ };
+
+ const riskLevel = getRiskLevel(sharpeRatio);
+
+ const getBetaRating = (beta: number) => {
+ if (beta < 0.8) return { rating: 'DEFENSIVE', color: BLUE };
+ if (beta < 1.2) return { rating: 'NEUTRAL', color: CYAN };
+ return { rating: 'AGGRESSIVE', color: ORANGE };
+ };
+
+ const betaRating = getBetaRating(beta);
+
+ const getVolatilityRating = (vol: number) => {
+ if (vol < 10) return { rating: 'LOW', color: GREEN };
+ if (vol < 20) return { rating: 'MODERATE', color: YELLOW };
+ if (vol < 30) return { rating: 'HIGH', color: ORANGE };
+ return { rating: 'VERY HIGH', color: RED };
+ };
+
+ const volatilityRating = getVolatilityRating(volatility);
+
+ if (loading) {
+ return (
+ <div style={{
+ padding: '40px',
+ textAlign: 'center',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: ORANGE, fontSize: '14px', marginBottom: '8px' }}>
+ Loading risk metrics...
+ </div>
+ <div style={{ color: GRAY, fontSize: '10px' }}>
+ Calculating portfolio risk from historical data
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '16px'
+ }}>
+ RISK METRICS & ANALYTICS {hasInsufficientData && '(LIMITED DATA)'}
+ </div>
+
+ {hasInsufficientData && (
+ <div style={{
+ padding: '12px',
+ marginBottom: '16px',
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px',
+ fontSize: '10px',
+ color: ORANGE
+ }}>
+ ⚠️ <strong>INSUFFICIENT HISTORICAL DATA:</strong> Risk metrics require at least 5 days of portfolio snapshots for accurate calculations.
+ Current data points: {portfolioReturns.length}. Metrics shown are preliminary.
+ </div>
+ )}
+
+ {/* Risk Overview Cards */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: '12px',
+ marginBottom: '24px'
+ }}>
+ {/* Overall Risk Level */}
+ <div style={{
+ padding: '16px',
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ border: `2px solid ${riskLevel.color}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '8px' }}>OVERALL RISK</div>
+ <div style={{
+ color: riskLevel.color,
+ fontSize: '20px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ {riskLevel.level}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px' }}>
+ Based on Sharpe Ratio: {sharpeRatio.toFixed(2)}
+ </div>
+ </div>
+
+ {/* Beta Rating */}
+ <div style={{
+ padding: '16px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `2px solid ${betaRating.color}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '8px' }}>MARKET SENSITIVITY</div>
+ <div style={{
+ color: betaRating.color,
+ fontSize: '20px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ {betaRating.rating}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px' }}>
+ Beta: {beta.toFixed(2)}
+ </div>
+ </div>
+
+ {/* Volatility Rating */}
+ <div style={{
+ padding: '16px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `2px solid ${volatilityRating.color}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '8px' }}>VOLATILITY</div>
+ <div style={{
+ color: volatilityRating.color,
+ fontSize: '20px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ {volatilityRating.rating}
+ </div>
+ <div style={{ color: GRAY, fontSize: '8px' }}>
+ Annualized: {volatility.toFixed(2)}%
+ </div>
+ </div>
+ </div>
+
+ {/* Detailed Metrics Grid */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '24px' }}>
+ {/* Left Column - Return Metrics */}
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ RISK-ADJUSTED RETURNS
+ </div>
+
+ {/* Sharpe Ratio */}
+ <div style={{
+ padding: '12px',
+ marginBottom: '12px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={{ color: CYAN, fontSize: '11px', fontWeight: 'bold' }}>SHARPE RATIO</div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Risk-adjusted return measure
+ </div>
+ </div>
+ <div style={{
+ color: sharpeRatio > 1 ? GREEN : sharpeRatio > 0 ? YELLOW : RED,
+ fontSize: '18px',
+ fontWeight: 'bold'
+ }}>
+ {sharpeRatio.toFixed(3)}
+ </div>
+ </div>
+ <div style={{ marginTop: '8px', fontSize: '8px', color: GRAY }}>
+ {'> 2: Excellent | 1-2: Good | 0-1: Fair | < 0: Poor'}
+ </div>
+ </div>
+
+ {/* Beta */}
+ <div style={{
+ padding: '12px',
+ marginBottom: '12px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={{ color: CYAN, fontSize: '11px', fontWeight: 'bold' }}>BETA (β)</div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Market correlation coefficient
+ </div>
+ </div>
+ <div style={{ color: betaRating.color, fontSize: '18px', fontWeight: 'bold' }}>
+ {beta.toFixed(3)}
+ </div>
+ </div>
+ <div style={{ marginTop: '8px', fontSize: '8px', color: GRAY }}>
+ {'< 1: Less volatile | 1: Market neutral | > 1: More volatile'}
+ </div>
+ </div>
+
+ {/* Volatility */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={{ color: CYAN, fontSize: '11px', fontWeight: 'bold' }}>VOLATILITY</div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Annualized standard deviation
+ </div>
+ </div>
+ <div style={{ color: volatilityRating.color, fontSize: '18px', fontWeight: 'bold' }}>
+ {volatility.toFixed(2)}%
+ </div>
+ </div>
+ <div style={{ marginTop: '8px', fontSize: '8px', color: GRAY }}>
+ Lower volatility indicates more stable returns
+ </div>
+ </div>
+ </div>
+
+ {/* Right Column - Risk Metrics */}
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ DOWNSIDE RISK METRICS
+ </div>
+
+ {/* Maximum Drawdown */}
+ <div style={{
+ padding: '12px',
+ marginBottom: '12px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={{ color: CYAN, fontSize: '11px', fontWeight: 'bold' }}>MAX DRAWDOWN</div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Largest peak-to-trough decline
+ </div>
+ </div>
+ <div style={{
+ color: maxDrawdown > 20 ? RED : maxDrawdown > 10 ? ORANGE : GREEN,
+ fontSize: '18px',
+ fontWeight: 'bold'
+ }}>
+ -{maxDrawdown.toFixed(2)}%
+ </div>
+ </div>
+ <div style={{ marginTop: '8px', fontSize: '8px', color: GRAY }}>
+ Maximum loss from peak value
+ </div>
+ </div>
+
+ {/* Value at Risk */}
+ <div style={{
+ padding: '12px',
+ marginBottom: '12px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={{ color: CYAN, fontSize: '11px', fontWeight: 'bold' }}>VALUE AT RISK (95%)</div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Expected loss at 95% confidence
+ </div>
+ </div>
+ <div style={{
+ color: var95 < -0.03 ? RED : var95 < -0.02 ? ORANGE : YELLOW,
+ fontSize: '18px',
+ fontWeight: 'bold'
+ }}>
+ {(var95 * 100).toFixed(2)}%
+ </div>
+ </div>
+ <div style={{ marginTop: '8px', fontSize: '8px', color: GRAY }}>
+ 5% chance of losing more than this in a day
+ </div>
+ </div>
+
+ {/* Risk Score */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: 'rgba(255,0,0,0.05)',
+ border: `2px solid ${riskLevel.color}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={{ color: riskLevel.color, fontSize: '11px', fontWeight: 'bold' }}>COMPOSITE RISK SCORE</div>
+ <div style={{ color: GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Weighted risk assessment
+ </div>
+ </div>
+ <div style={{ color: riskLevel.color, fontSize: '18px', fontWeight: 'bold' }}>
+ {((1 / (sharpeRatio + 1)) * 100).toFixed(0)}/100
+ </div>
+ </div>
+ <div style={{ marginTop: '8px' }}>
+ <div style={{
+ width: '100%',
+ height: '8px',
+ backgroundColor: 'rgba(120,120,120,0.3)',
+ borderRadius: '4px',
+ overflow: 'hidden'
+ }}>
+ <div style={{
+ width: `${(1 / (sharpeRatio + 1)) * 100}%`,
+ height: '100%',
+ backgroundColor: riskLevel.color,
+ transition: 'width 0.3s'
+ }} />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Risk Recommendations */}
+ <div style={{
+ padding: '16px',
+ backgroundColor: 'rgba(255,165,0,0.05)',
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '12px'
+ }}>
+ RISK MANAGEMENT RECOMMENDATIONS
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ {sharpeRatio < 1 && (
+ <div style={{ fontSize: '9px', color: WHITE, padding: '8px', backgroundColor: 'rgba(255,0,0,0.1)', borderRadius: '2px' }}>
+ ⚠️ <strong>LOW SHARPE RATIO:</strong> Consider diversifying to improve risk-adjusted returns
+ </div>
+ )}
+ {beta > 1.5 && (
+ <div style={{ fontSize: '9px', color: WHITE, padding: '8px', backgroundColor: 'rgba(255,165,0,0.1)', borderRadius: '2px' }}>
+ ⚠️ <strong>HIGH BETA:</strong> Portfolio is more volatile than market. Consider defensive assets
+ </div>
+ )}
+ {volatility > 25 && (
+ <div style={{ fontSize: '9px', color: WHITE, padding: '8px', backgroundColor: 'rgba(255,0,0,0.1)', borderRadius: '2px' }}>
+ ⚠️ <strong>HIGH VOLATILITY:</strong> Consider adding bonds or stable assets to reduce swings
+ </div>
+ )}
+ {maxDrawdown > 20 && (
+ <div style={{ fontSize: '9px', color: WHITE, padding: '8px', backgroundColor: 'rgba(255,0,0,0.1)', borderRadius: '2px' }}>
+ ⚠️ <strong>LARGE DRAWDOWN:</strong> Review stop-loss strategies and position sizing
+ </div>
+ )}
+ {sharpeRatio > 2 && (
+ <div style={{ fontSize: '9px', color: WHITE, padding: '8px', backgroundColor: 'rgba(0,200,0,0.1)', borderRadius: '2px' }}>
+ ✓ <strong>EXCELLENT SHARPE:</strong> Portfolio shows strong risk-adjusted performance
+ </div>
+ )}
+ {beta >= 0.8 && beta <= 1.2 && (
+ <div style={{ fontSize: '9px', color: WHITE, padding: '8px', backgroundColor: 'rgba(0,255,255,0.1)', borderRadius: '2px' }}>
+ ✓ <strong>BALANCED BETA:</strong> Good market correlation, neither too aggressive nor defensive
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Disclaimer */}
+ <div style={{
+ marginTop: '16px',
+ padding: '12px',
+ backgroundColor: 'rgba(120,120,120,0.1)',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px',
+ fontSize: '8px',
+ color: GRAY
+ }}>
+ <strong style={{ color: ORANGE }}>DISCLAIMER:</strong> Risk metrics are calculated from portfolio snapshot history.
+ {hasInsufficientData && ' More data points are needed for statistically significant results.'}
+ {' '}Beta calculations use portfolio returns as market proxy until real market benchmarks are integrated.
+ Past performance does not guarantee future results. Consult a financial advisor before making investment decisions.
+ </div>
+ </div>
+ );
+};
+
+export default RiskMetricsView;
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/SectorsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio/SectorsView.tsx
new file mode 100644
index 000000000..4fc8f6a3a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/SectorsView.tsx
@@ -0,0 +1,364 @@
+import React, { useMemo } from 'react';
+import { PortfolioSummary, PortfolioHolding } from '../../../services/portfolioService';
+import { BLOOMBERG_COLORS, formatCurrency, formatPercent } from './utils';
+import { sectorService } from '../../../services/sectorService';
+
+interface SectorsViewProps {
+ portfolioSummary: PortfolioSummary;
+}
+
+interface SectorAllocation {
+ sector: string;
+ value: number;
+ weight: number;
+ holdings: PortfolioHolding[];
+ color: string;
+}
+
+const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
+ const { ORANGE, WHITE, RED, GREEN, GRAY, CYAN, YELLOW, BLUE, PURPLE } = BLOOMBERG_COLORS;
+ const currency = portfolioSummary.portfolio.currency;
+
+ // Group holdings by sector using real sector classification
+ const sectorAllocations = useMemo((): SectorAllocation[] => {
+ const sectorMap = new Map<string, { value: number; holdings: PortfolioHolding[] }>();
+ const totalValue = portfolioSummary.total_market_value;
+
+ portfolioSummary.holdings.forEach(holding => {
+ const sectorInfo = sectorService.getSectorInfo(holding.symbol);
+ const sector = sectorInfo.sector;
+
+ const existing = sectorMap.get(sector) || { value: 0, holdings: [] };
+ sectorMap.set(sector, {
+ value: existing.value + holding.market_value,
+ holdings: [...existing.holdings, holding]
+ });
+ });
+
+ const colors = [BLUE, GREEN, ORANGE, PURPLE, CYAN, YELLOW, RED];
+
+ return Array.from(sectorMap.entries())
+ .map(([sector, data], index) => ({
+ sector,
+ value: data.value,
+ weight: totalValue > 0 ? (data.value / totalValue) * 100 : 0,
+ holdings: data.holdings,
+ color: colors[index % colors.length]
+ }))
+ .sort((a, b) => b.weight - a.weight);
+ }, [portfolioSummary.holdings, portfolioSummary.total_market_value]);
+
+ // Calculate pie chart angles
+ let currentAngle = 0;
+ const pieData = sectorAllocations.map(sector => {
+ const startAngle = currentAngle;
+ const angleSize = (sector.weight / 100) * 360;
+ currentAngle += angleSize;
+ return {
+ ...sector,
+ startAngle,
+ endAngle: currentAngle
+ };
+ });
+
+ // SVG Pie Chart
+ const radius = 120;
+ const centerX = 150;
+ const centerY = 150;
+
+ const polarToCartesian = (angle: number) => {
+ const radian = (angle - 90) * Math.PI / 180;
+ return {
+ x: centerX + radius * Math.cos(radian),
+ y: centerY + radius * Math.sin(radian)
+ };
+ };
+
+ const createArc = (startAngle: number, endAngle: number) => {
+ const start = polarToCartesian(startAngle);
+ const end = polarToCartesian(endAngle);
+ const largeArc = endAngle - startAngle > 180 ? 1 : 0;
+
+ return `M ${centerX} ${centerY} L ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArc} 1 ${end.x} ${end.y} Z`;
+ };
+
+ return (
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '16px'
+ }}>
+ SECTOR ALLOCATION
+ </div>
+
+ {sectorAllocations.length === 0 ? (
+ <div style={{ padding: '32px', textAlign: 'center', color: GRAY, fontSize: '11px' }}>
+ No sector data available. Add holdings with sector information.
+ </div>
+ ) : (
+ <div style={{ display: 'grid', gridTemplateColumns: '400px 1fr', gap: '24px' }}>
+ {/* Pie Chart */}
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center'
+ }}>
+ <svg width="300" height="300" style={{ marginBottom: '16px' }}>
+ {/* Pie segments */}
+ {pieData.map((sector, index) => (
+ <g key={sector.sector}>
+ <path
+ d={createArc(sector.startAngle, sector.endAngle)}
+ fill={sector.color}
+ stroke="#000000"
+ strokeWidth="2"
+ opacity="0.8"
+ />
+ {/* Label */}
+ {sector.weight > 5 && (
+ <text
+ x={centerX + (radius * 0.7) * Math.cos((((sector.startAngle + sector.endAngle) / 2) - 90) * Math.PI / 180)}
+ y={centerY + (radius * 0.7) * Math.sin((((sector.startAngle + sector.endAngle) / 2) - 90) * Math.PI / 180)}
+ textAnchor="middle"
+ fill="#FFFFFF"
+ fontSize="11"
+ fontWeight="bold"
+ fontFamily="Consolas, monospace"
+ >
+ {sector.weight.toFixed(1)}%
+ </text>
+ )}
+ </g>
+ ))}
+ {/* Center circle for donut effect */}
+ <circle
+ cx={centerX}
+ cy={centerY}
+ r={radius * 0.4}
+ fill="#1a1a1a"
+ stroke="#FFA500"
+ strokeWidth="2"
+ />
+ <text
+ x={centerX}
+ y={centerY - 10}
+ textAnchor="middle"
+ fill="#FFA500"
+ fontSize="12"
+ fontWeight="bold"
+ fontFamily="Consolas, monospace"
+ >
+ SECTORS
+ </text>
+ <text
+ x={centerX}
+ y={centerY + 10}
+ textAnchor="middle"
+ fill="#FFFFFF"
+ fontSize="14"
+ fontWeight="bold"
+ fontFamily="Consolas, monospace"
+ >
+ {sectorAllocations.length}
+ </text>
+ </svg>
+
+ {/* Legend */}
+ <div style={{ width: '100%' }}>
+ {sectorAllocations.map(sector => (
+ <div
+ key={sector.sector}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ marginBottom: '6px',
+ padding: '6px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ borderLeft: `4px solid ${sector.color}`
+ }}
+ >
+ <div style={{
+ width: '12px',
+ height: '12px',
+ backgroundColor: sector.color,
+ marginRight: '8px',
+ border: '1px solid #000'
+ }} />
+ <div style={{ flex: 1 }}>
+ <span style={{ color: WHITE, fontSize: '10px', fontWeight: 'bold' }}>
+ {sector.sector}
+ </span>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <span style={{ color: YELLOW, fontSize: '10px', fontWeight: 'bold' }}>
+ {sector.weight.toFixed(1)}%
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Sector Details Table */}
+ <div>
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${ORANGE}`
+ }}>
+ SECTOR BREAKDOWN
+ </div>
+
+ {/* Table Header */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1.5fr 1fr 1fr 1fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: 'rgba(255,165,0,0.1)',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ <div style={{ color: WHITE }}>SECTOR</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>VALUE</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>WEIGHT</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>HOLDINGS</div>
+ </div>
+
+ {/* Sector Rows */}
+ {sectorAllocations.map((sector, index) => {
+ return (
+ <div key={sector.sector} style={{ marginBottom: '12px' }}>
+ {/* Sector Summary Row */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1.5fr 1fr 1fr 1fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ borderLeft: `3px solid ${sector.color}`,
+ fontSize: '10px',
+ marginBottom: '4px'
+ }}>
+ <div style={{ color: sector.color, fontWeight: 'bold' }}>
+ {sector.sector}
+ </div>
+ <div style={{ color: YELLOW, textAlign: 'right', fontWeight: 'bold' }}>
+ {formatCurrency(sector.value, currency)}
+ </div>
+ <div style={{ color: YELLOW, textAlign: 'right', fontWeight: 'bold' }}>
+ {sector.weight.toFixed(2)}%
+ </div>
+ <div style={{ color: CYAN, textAlign: 'right' }}>
+ {sector.holdings.length}
+ </div>
+ </div>
+
+ {/* Holdings in Sector */}
+ {sector.holdings.map(holding => (
+ <div
+ key={holding.id}
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1.5fr 1fr 1fr 1fr',
+ gap: '8px',
+ padding: '6px 8px 6px 20px',
+ backgroundColor: 'rgba(255,255,255,0.01)',
+ fontSize: '9px',
+ borderLeft: `1px solid ${sector.color}`,
+ marginLeft: '8px'
+ }}
+ >
+ <div style={{ color: CYAN }}>└─ {holding.symbol}</div>
+ <div style={{ color: WHITE, textAlign: 'right' }}>
+ {formatCurrency(holding.market_value, currency)}
+ </div>
+ <div style={{ color: GRAY, textAlign: 'right' }}>
+ {holding.weight.toFixed(2)}%
+ </div>
+ <div style={{
+ color: holding.unrealized_pnl >= 0 ? GREEN : RED,
+ textAlign: 'right',
+ fontWeight: 'bold'
+ }}>
+ {formatPercent(holding.unrealized_pnl_percent)}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+ })}
+
+ {/* Sector Statistics */}
+ <div style={{
+ marginTop: '16px',
+ padding: '12px',
+ backgroundColor: 'rgba(255,165,0,0.05)',
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}>
+ DIVERSIFICATION METRICS
+ </div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <div>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '2px' }}>
+ Total Sectors
+ </div>
+ <div style={{ color: CYAN, fontSize: '14px', fontWeight: 'bold' }}>
+ {sectorAllocations.length}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '2px' }}>
+ Largest Sector
+ </div>
+ <div style={{ color: YELLOW, fontSize: '14px', fontWeight: 'bold' }}>
+ {sectorAllocations[0]?.sector || 'N/A'} ({sectorAllocations[0]?.weight.toFixed(1)}%)
+ </div>
+ </div>
+ <div>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '2px' }}>
+ Concentration Risk
+ </div>
+ <div style={{
+ color: sectorAllocations[0]?.weight > 40 ? RED : sectorAllocations[0]?.weight > 25 ? YELLOW : GREEN,
+ fontSize: '14px',
+ fontWeight: 'bold'
+ }}>
+ {sectorAllocations[0]?.weight > 40 ? 'HIGH' : sectorAllocations[0]?.weight > 25 ? 'MEDIUM' : 'LOW'}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '2px' }}>
+ Diversification
+ </div>
+ <div style={{
+ color: sectorAllocations.length >= 5 ? GREEN : sectorAllocations.length >= 3 ? YELLOW : RED,
+ fontSize: '14px',
+ fontWeight: 'bold'
+ }}>
+ {sectorAllocations.length >= 5 ? 'GOOD' : sectorAllocations.length >= 3 ? 'MODERATE' : 'POOR'}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default SectorsView;
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/utils.ts b/fincept-terminal-desktop/src/components/tabs/portfolio/utils.ts
new file mode 100644
index 000000000..d7c4fcba5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/utils.ts
@@ -0,0 +1,343 @@
+// Portfolio Utility Functions
+// Formatting, calculations, and helper functions
+
+export const BLOOMBERG_COLORS = {
+ ORANGE: '#FFA500',
+ WHITE: '#FFFFFF',
+ RED: '#FF0000',
+ GREEN: '#00C800',
+ GRAY: '#787878',
+ DARK_BG: '#1a1a1a',
+ PANEL_BG: '#000000',
+ CYAN: '#00FFFF',
+ YELLOW: '#FFFF00',
+ BLUE: '#6496FA',
+ PURPLE: '#C864FF'
+};
+
+// Currency symbols and formatting
+const CURRENCY_SYMBOLS: Record<string, string> = {
+ USD: '$',
+ EUR: '€',
+ GBP: '£',
+ INR: '₹',
+ JPY: '¥',
+ CNY: '¥',
+ AUD: 'A$',
+ CAD: 'C$',
+ CHF: 'CHF'
+};
+
+const CURRENCY_LOCALES: Record<string, string> = {
+ USD: 'en-US',
+ EUR: 'de-DE',
+ GBP: 'en-GB',
+ INR: 'en-IN',
+ JPY: 'ja-JP',
+ CNY: 'zh-CN',
+ AUD: 'en-AU',
+ CAD: 'en-CA',
+ CHF: 'de-CH'
+};
+
+/**
+ * Format currency value with proper symbol and locale
+ */
+export const formatCurrency = (value: number, currency: string = 'USD'): string => {
+ const locale = CURRENCY_LOCALES[currency] || 'en-US';
+
+ return new Intl.NumberFormat(locale, {
+ style: 'currency',
+ currency: currency,
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ }).format(value);
+};
+
+/**
+ * Get currency symbol
+ */
+export const getCurrencySymbol = (currency: string): string => {
+ return CURRENCY_SYMBOLS[currency] || currency;
+};
+
+/**
+ * Format number with specified decimals
+ */
+export const formatNumber = (value: number, decimals: number = 2): string => {
+ return value.toFixed(decimals);
+};
+
+/**
+ * Format percentage with sign
+ */
+export const formatPercent = (value: number): string => {
+ return `${value >= 0 ? '+' : ''}${value.toFixed(2)}%`;
+};
+
+/**
+ * Format large numbers (millions, billions)
+ */
+export const formatLargeNumber = (value: number, currency?: string): string => {
+ const absValue = Math.abs(value);
+ const symbol = currency ? getCurrencySymbol(currency) : '';
+
+ if (absValue >= 1e9) {
+ return `${symbol}${(value / 1e9).toFixed(2)}B`;
+ } else if (absValue >= 1e6) {
+ return `${symbol}${(value / 1e6).toFixed(2)}M`;
+ } else if (absValue >= 1e3) {
+ return `${symbol}${(value / 1e3).toFixed(2)}K`;
+ }
+
+ return currency ? formatCurrency(value, currency) : value.toFixed(2);
+};
+
+/**
+ * Calculate percentage change
+ */
+export const calculatePercentChange = (current: number, previous: number): number => {
+ if (previous === 0) return 0;
+ return ((current - previous) / previous) * 100;
+};
+
+/**
+ * Calculate annualized return
+ */
+export const calculateAnnualizedReturn = (totalReturn: number, days: number): number => {
+ if (days === 0) return 0;
+ const years = days / 365;
+ return (Math.pow(1 + totalReturn / 100, 1 / years) - 1) * 100;
+};
+
+/**
+ * Calculate Sharpe Ratio
+ */
+export const calculateSharpeRatio = (returns: number[], riskFreeRate: number = 0.03): number => {
+ if (returns.length === 0) return 0;
+
+ const avgReturn = returns.reduce((sum, r) => sum + r, 0) / returns.length;
+ const variance = returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / returns.length;
+ const stdDev = Math.sqrt(variance);
+
+ if (stdDev === 0) return 0;
+
+ return (avgReturn - riskFreeRate) / stdDev;
+};
+
+/**
+ * Calculate Beta (market sensitivity)
+ */
+export const calculateBeta = (portfolioReturns: number[], marketReturns: number[]): number => {
+ if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length === 0) {
+ return 1; // Default beta
+ }
+
+ const n = portfolioReturns.length;
+ const avgPortfolio = portfolioReturns.reduce((sum, r) => sum + r, 0) / n;
+ const avgMarket = marketReturns.reduce((sum, r) => sum + r, 0) / n;
+
+ let covariance = 0;
+ let marketVariance = 0;
+
+ for (let i = 0; i < n; i++) {
+ covariance += (portfolioReturns[i] - avgPortfolio) * (marketReturns[i] - avgMarket);
+ marketVariance += Math.pow(marketReturns[i] - avgMarket, 2);
+ }
+
+ if (marketVariance === 0) return 1;
+
+ return covariance / marketVariance;
+};
+
+/**
+ * Calculate Volatility (annualized standard deviation)
+ */
+export const calculateVolatility = (returns: number[]): number => {
+ if (returns.length === 0) return 0;
+
+ const avgReturn = returns.reduce((sum, r) => sum + r, 0) / returns.length;
+ const variance = returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / returns.length;
+ const stdDev = Math.sqrt(variance);
+
+ // Annualize (assuming daily returns)
+ return stdDev * Math.sqrt(252) * 100;
+};
+
+/**
+ * Calculate Maximum Drawdown
+ */
+export const calculateMaxDrawdown = (values: number[]): number => {
+ if (values.length === 0) return 0;
+
+ let maxDrawdown = 0;
+ let peak = values[0];
+
+ for (const value of values) {
+ if (value > peak) {
+ peak = value;
+ }
+
+ const drawdown = ((peak - value) / peak) * 100;
+ if (drawdown > maxDrawdown) {
+ maxDrawdown = drawdown;
+ }
+ }
+
+ return maxDrawdown;
+};
+
+/**
+ * Calculate Value at Risk (VaR) - 95% confidence
+ */
+export const calculateVaR = (returns: number[], confidenceLevel: number = 0.95): number => {
+ if (returns.length === 0) return 0;
+
+ const sortedReturns = [...returns].sort((a, b) => a - b);
+ const index = Math.floor(sortedReturns.length * (1 - confidenceLevel));
+
+ return sortedReturns[index] || 0;
+};
+
+/**
+ * Group holdings by sector
+ * DEPRECATED: Use sectorService.getSectorInfo() for real sector classification
+ */
+export interface SectorAllocation {
+ sector: string;
+ value: number;
+ weight: number;
+ color: string;
+}
+
+// Removed groupBySector - use sectorService instead
+
+/**
+ * Calculate tax liability (simple capital gains)
+ */
+export interface TaxCalculation {
+ shortTermGains: number;
+ longTermGains: number;
+ shortTermTax: number;
+ longTermTax: number;
+ totalTax: number;
+}
+
+export const calculateTaxLiability = (
+ transactions: any[],
+ shortTermRate: number = 0.15,
+ longTermRate: number = 0.20,
+ holdingPeriodDays: number = 365
+): TaxCalculation => {
+ let shortTermGains = 0;
+ let longTermGains = 0;
+
+ // Group by symbol and calculate FIFO gains
+ const symbolTransactions = new Map<string, any[]>();
+
+ transactions.forEach(txn => {
+ if (!symbolTransactions.has(txn.symbol)) {
+ symbolTransactions.set(txn.symbol, []);
+ }
+ symbolTransactions.get(txn.symbol)!.push(txn);
+ });
+
+ symbolTransactions.forEach((txns, symbol) => {
+ const buys = txns.filter(t => t.transaction_type === 'BUY').sort((a, b) =>
+ new Date(a.transaction_date).getTime() - new Date(b.transaction_date).getTime()
+ );
+ const sells = txns.filter(t => t.transaction_type === 'SELL').sort((a, b) =>
+ new Date(a.transaction_date).getTime() - new Date(b.transaction_date).getTime()
+ );
+
+ sells.forEach(sell => {
+ let remainingQuantity = sell.quantity;
+ const sellDate = new Date(sell.transaction_date);
+
+ for (const buy of buys) {
+ if (remainingQuantity <= 0) break;
+
+ const quantityToMatch = Math.min(remainingQuantity, buy.quantity);
+ const buyDate = new Date(buy.transaction_date);
+ const daysDiff = Math.floor((sellDate.getTime() - buyDate.getTime()) / (1000 * 60 * 60 * 24));
+
+ const gain = (sell.price - buy.price) * quantityToMatch;
+
+ if (daysDiff > holdingPeriodDays) {
+ longTermGains += gain;
+ } else {
+ shortTermGains += gain;
+ }
+
+ remainingQuantity -= quantityToMatch;
+ }
+ });
+ });
+
+ return {
+ shortTermGains,
+ longTermGains,
+ shortTermTax: shortTermGains * shortTermRate,
+ longTermTax: longTermGains * longTermRate,
+ totalTax: (shortTermGains * shortTermRate) + (longTermGains * longTermRate)
+ };
+};
+
+/**
+ * Format date
+ */
+export const formatDate = (date: string | Date): string => {
+ return new Date(date).toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric'
+ });
+};
+
+/**
+ * Format time
+ */
+export const formatTime = (date: string | Date): string => {
+ return new Date(date).toLocaleTimeString('en-US', {
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit'
+ });
+};
+
+/**
+ * Format datetime
+ */
+export const formatDateTime = (date: string | Date): string => {
+ return `${formatDate(date)} ${formatTime(date)}`;
+};
+
+/**
+ * Get color for P&L
+ */
+export const getPnLColor = (value: number): string => {
+ return value >= 0 ? BLOOMBERG_COLORS.GREEN : BLOOMBERG_COLORS.RED;
+};
+
+/**
+ * Debounce function
+ */
+export const debounce = <T extends (...args: any[]) => any>(
+ func: T,
+ wait: number
+): ((...args: Parameters<T>) => void) => {
+ let timeout: NodeJS.Timeout;
+
+ return (...args: Parameters<T>) => {
+ clearTimeout(timeout);
+ timeout = setTimeout(() => func(...args), wait);
+ };
+};
+
+/**
+ * Calculate compound annual growth rate (CAGR)
+ */
+export const calculateCAGR = (initialValue: number, finalValue: number, years: number): number => {
+ if (initialValue === 0 || years === 0) return 0;
+ return (Math.pow(finalValue / initialValue, 1 / years) - 1) * 100;
+};
diff --git a/fincept-terminal-desktop/src/services/alertsService.ts b/fincept-terminal-desktop/src/services/alertsService.ts
new file mode 100644
index 000000000..8a3aa3f6b
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/alertsService.ts
@@ -0,0 +1,241 @@
+// Portfolio Alerts Service
+// Manages price alerts and notifications for portfolio holdings
+
+import Database from '@tauri-apps/plugin-sql';
+
+export interface PriceAlert {
+ id: string;
+ portfolio_id: string;
+ symbol: string;
+ type: 'PRICE_TARGET' | 'STOP_LOSS' | 'TAKE_PROFIT' | 'PRICE_CHANGE';
+ condition: 'ABOVE' | 'BELOW' | 'PERCENT_UP' | 'PERCENT_DOWN';
+ target_value: number;
+ is_triggered: boolean;
+ created_at: string;
+ triggered_at?: string;
+ notes?: string;
+}
+
+class AlertsService {
+ private db: Database | null = null;
+ private dbPath = 'sqlite:fincept_terminal.db';
+ private isInitialized = false;
+
+ async initialize(): Promise<void> {
+ if (this.isInitialized && this.db) {
+ return;
+ }
+
+ try {
+ this.db = await Database.load(this.dbPath);
+ await this.createTable();
+ this.isInitialized = true;
+ console.log('[AlertsService] Initialized successfully');
+ } catch (error) {
+ console.error('[AlertsService] Initialization failed:', error);
+ throw error;
+ }
+ }
+
+ private async createTable(): Promise<void> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS portfolio_alerts (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ type TEXT NOT NULL,
+ condition TEXT NOT NULL,
+ target_value REAL NOT NULL,
+ is_triggered INTEGER DEFAULT 0,
+ created_at TEXT DEFAULT (datetime('now')),
+ triggered_at TEXT,
+ notes TEXT,
+ FOREIGN KEY (portfolio_id) REFERENCES portfolios(id) ON DELETE CASCADE
+ )
+ `);
+
+ await this.db.execute(`
+ CREATE INDEX IF NOT EXISTS idx_alerts_portfolio ON portfolio_alerts(portfolio_id)
+ `);
+
+ await this.db.execute(`
+ CREATE INDEX IF NOT EXISTS idx_alerts_symbol ON portfolio_alerts(symbol)
+ `);
+ }
+
+ private ensureInitialized(): void {
+ if (!this.db || !this.isInitialized) {
+ throw new Error('AlertsService not initialized. Call initialize() first.');
+ }
+ }
+
+ /**
+ * Create a new price alert
+ */
+ async createAlert(
+ portfolioId: string,
+ symbol: string,
+ type: PriceAlert['type'],
+ condition: PriceAlert['condition'],
+ targetValue: number,
+ notes?: string
+ ): Promise<PriceAlert> {
+ this.ensureInitialized();
+
+ const id = crypto.randomUUID();
+ await this.db!.execute(
+ `INSERT INTO portfolio_alerts (id, portfolio_id, symbol, type, condition, target_value, notes)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,
+ [id, portfolioId, symbol, type, condition, targetValue, notes || null]
+ );
+
+ const result = await this.db!.select<PriceAlert[]>(
+ 'SELECT * FROM portfolio_alerts WHERE id = $1',
+ [id]
+ );
+
+ return this.mapAlert(result[0]);
+ }
+
+ /**
+ * Get all alerts for a portfolio
+ */
+ async getPortfolioAlerts(portfolioId: string, includeTriggered: boolean = false): Promise<PriceAlert[]> {
+ this.ensureInitialized();
+
+ const query = includeTriggered
+ ? 'SELECT * FROM portfolio_alerts WHERE portfolio_id = $1 ORDER BY created_at DESC'
+ : 'SELECT * FROM portfolio_alerts WHERE portfolio_id = $1 AND is_triggered = 0 ORDER BY created_at DESC';
+
+ const results = await this.db!.select<any[]>(query, [portfolioId]);
+ return results.map(r => this.mapAlert(r));
+ }
+
+ /**
+ * Get alerts for a specific symbol
+ */
+ async getSymbolAlerts(portfolioId: string, symbol: string): Promise<PriceAlert[]> {
+ this.ensureInitialized();
+
+ const results = await this.db!.select<any[]>(
+ 'SELECT * FROM portfolio_alerts WHERE portfolio_id = $1 AND symbol = $2 AND is_triggered = 0 ORDER BY created_at DESC',
+ [portfolioId, symbol]
+ );
+
+ return results.map(r => this.mapAlert(r));
+ }
+
+ /**
+ * Delete an alert
+ */
+ async deleteAlert(alertId: string): Promise<void> {
+ this.ensureInitialized();
+
+ await this.db!.execute('DELETE FROM portfolio_alerts WHERE id = $1', [alertId]);
+ console.log(`[AlertsService] Deleted alert: ${alertId}`);
+ }
+
+ /**
+ * Trigger an alert
+ */
+ async triggerAlert(alertId: string): Promise<void> {
+ this.ensureInitialized();
+
+ await this.db!.execute(
+ `UPDATE portfolio_alerts SET is_triggered = 1, triggered_at = datetime('now') WHERE id = $1`,
+ [alertId]
+ );
+
+ console.log(`[AlertsService] Triggered alert: ${alertId}`);
+ }
+
+ /**
+ * Check if price conditions are met and trigger alerts
+ */
+ async checkAlerts(symbol: string, currentPrice: number, portfolioId?: string): Promise<PriceAlert[]> {
+ this.ensureInitialized();
+
+ const query = portfolioId
+ ? 'SELECT * FROM portfolio_alerts WHERE symbol = $1 AND portfolio_id = $2 AND is_triggered = 0'
+ : 'SELECT * FROM portfolio_alerts WHERE symbol = $1 AND is_triggered = 0';
+
+ const params = portfolioId ? [symbol, portfolioId] : [symbol];
+ const alerts = await this.db!.select<any[]>(query, params);
+
+ const triggeredAlerts: PriceAlert[] = [];
+
+ for (const alert of alerts) {
+ let shouldTrigger = false;
+
+ switch (alert.condition) {
+ case 'ABOVE':
+ shouldTrigger = currentPrice >= alert.target_value;
+ break;
+ case 'BELOW':
+ shouldTrigger = currentPrice <= alert.target_value;
+ break;
+ // PERCENT_UP and PERCENT_DOWN would need base price tracking
+ }
+
+ if (shouldTrigger) {
+ await this.triggerAlert(alert.id);
+ triggeredAlerts.push(this.mapAlert(alert));
+ }
+ }
+
+ return triggeredAlerts;
+ }
+
+ /**
+ * Get alert statistics
+ */
+ async getAlertStats(portfolioId: string): Promise<{
+ total: number;
+ active: number;
+ triggered: number;
+ byType: Record<string, number>;
+ }> {
+ this.ensureInitialized();
+
+ const alerts = await this.db!.select<any[]>(
+ 'SELECT * FROM portfolio_alerts WHERE portfolio_id = $1',
+ [portfolioId]
+ );
+
+ const stats = {
+ total: alerts.length,
+ active: alerts.filter(a => a.is_triggered === 0).length,
+ triggered: alerts.filter(a => a.is_triggered === 1).length,
+ byType: {} as Record<string, number>
+ };
+
+ alerts.forEach(alert => {
+ stats.byType[alert.type] = (stats.byType[alert.type] || 0) + 1;
+ });
+
+ return stats;
+ }
+
+ /**
+ * Map database row to PriceAlert
+ */
+ private mapAlert(row: any): PriceAlert {
+ return {
+ ...row,
+ is_triggered: row.is_triggered === 1
+ };
+ }
+
+ /**
+ * Check if service is ready
+ */
+ isReady(): boolean {
+ return this.isInitialized && this.db !== null;
+ }
+}
+
+// Export singleton instance
+export const alertsService = new AlertsService();
+export default alertsService;
diff --git a/fincept-terminal-desktop/src/services/portfolioService.ts b/fincept-terminal-desktop/src/services/portfolioService.ts
new file mode 100644
index 000000000..617cf1587
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/portfolioService.ts
@@ -0,0 +1,786 @@
+// Portfolio Service - Comprehensive Portfolio Management for Fincept Terminal
+// Handles portfolio creation, asset management, transactions, performance tracking, and analytics
+
+import Database from '@tauri-apps/plugin-sql';
+import { marketDataService, QuoteData } from './marketDataService';
+
+// ==================== TYPES ====================
+
+export interface Portfolio {
+ id: string;
+ name: string;
+ owner: string;
+ currency: string;
+ description?: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface PortfolioAsset {
+ id: string;
+ portfolio_id: string;
+ symbol: string;
+ quantity: number;
+ avg_buy_price: number;
+ first_purchase_date?: string;
+ last_updated: string;
+ notes?: string;
+}
+
+export interface Transaction {
+ id: string;
+ portfolio_id: string;
+ symbol: string;
+ transaction_type: 'BUY' | 'SELL';
+ quantity: number;
+ price: number;
+ total_value: number;
+ transaction_date: string;
+ notes?: string;
+ created_at: string;
+}
+
+export interface PortfolioSnapshot {
+ id: string;
+ portfolio_id: string;
+ total_value: number;
+ total_cost_basis: number;
+ total_pnl: number;
+ total_pnl_percent: number;
+ snapshot_date: string;
+ snapshot_data: string; // JSON of full portfolio state
+}
+
+export interface PortfolioHolding extends PortfolioAsset {
+ current_price: number;
+ market_value: number;
+ cost_basis: number;
+ unrealized_pnl: number;
+ unrealized_pnl_percent: number;
+ day_change: number;
+ day_change_percent: number;
+ weight: number;
+}
+
+export interface PortfolioSummary {
+ portfolio: Portfolio;
+ total_positions: number;
+ total_market_value: number;
+ total_cost_basis: number;
+ total_unrealized_pnl: number;
+ total_unrealized_pnl_percent: number;
+ total_day_change: number;
+ total_day_change_percent: number;
+ holdings: PortfolioHolding[];
+ last_updated: string;
+}
+
+export interface PortfolioPerformance {
+ portfolio_id: string;
+ ytd_return: number;
+ one_month_return: number;
+ three_month_return: number;
+ one_year_return: number;
+ sharpe_ratio: number;
+ beta: number;
+ max_drawdown: number;
+ volatility: number;
+ total_return: number;
+}
+
+// ==================== PORTFOLIO SERVICE CLASS ====================
+
+class PortfolioService {
+ private db: Database | null = null;
+ private dbPath = 'sqlite:fincept_terminal.db';
+ private isInitialized = false;
+
+ /**
+ * Initialize database connection
+ */
+ async initialize(): Promise<void> {
+ if (this.isInitialized && this.db) {
+ return;
+ }
+
+ try {
+ this.db = await Database.load(this.dbPath);
+ this.isInitialized = true;
+ console.log('[PortfolioService] Initialized successfully');
+ } catch (error) {
+ console.error('[PortfolioService] Initialization failed:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Ensure database is initialized
+ */
+ private ensureInitialized(): void {
+ if (!this.db || !this.isInitialized) {
+ throw new Error('PortfolioService not initialized. Call initialize() first.');
+ }
+ }
+
+ // ==================== PORTFOLIO CRUD ====================
+
+ /**
+ * Create a new portfolio
+ */
+ async createPortfolio(name: string, owner: string, currency: string = 'USD', description?: string): Promise<Portfolio> {
+ this.ensureInitialized();
+
+ const id = crypto.randomUUID();
+ await this.db!.execute(
+ `INSERT INTO portfolios (id, name, owner, currency, description)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [id, name, owner, currency, description || null]
+ );
+
+ const result = await this.db!.select<Portfolio[]>(
+ 'SELECT * FROM portfolios WHERE id = $1',
+ [id]
+ );
+
+ console.log(`[PortfolioService] Created portfolio: ${name} (ID: ${id})`);
+ return result[0];
+ }
+
+ /**
+ * Get all portfolios
+ */
+ async getPortfolios(): Promise<Portfolio[]> {
+ this.ensureInitialized();
+
+ const portfolios = await this.db!.select<Portfolio[]>(
+ 'SELECT * FROM portfolios ORDER BY created_at DESC'
+ );
+
+ return portfolios;
+ }
+
+ /**
+ * Get portfolio by ID
+ */
+ async getPortfolio(portfolioId: string): Promise<Portfolio | null> {
+ this.ensureInitialized();
+
+ const result = await this.db!.select<Portfolio[]>(
+ 'SELECT * FROM portfolios WHERE id = $1',
+ [portfolioId]
+ );
+
+ return result.length > 0 ? result[0] : null;
+ }
+
+ /**
+ * Update portfolio
+ */
+ async updatePortfolio(portfolioId: string, updates: Partial<Omit<Portfolio, 'id' | 'created_at' | 'updated_at'>>): Promise<void> {
+ this.ensureInitialized();
+
+ const sets: string[] = [];
+ const values: any[] = [];
+
+ if (updates.name !== undefined) {
+ sets.push('name = $' + (values.length + 1));
+ values.push(updates.name);
+ }
+ if (updates.owner !== undefined) {
+ sets.push('owner = $' + (values.length + 1));
+ values.push(updates.owner);
+ }
+ if (updates.currency !== undefined) {
+ sets.push('currency = $' + (values.length + 1));
+ values.push(updates.currency);
+ }
+ if (updates.description !== undefined) {
+ sets.push('description = $' + (values.length + 1));
+ values.push(updates.description);
+ }
+
+ if (sets.length > 0) {
+ sets.push("updated_at = datetime('now')");
+ values.push(portfolioId);
+
+ await this.db!.execute(
+ `UPDATE portfolios SET ${sets.join(', ')} WHERE id = $${values.length}`,
+ values
+ );
+ }
+ }
+
+ /**
+ * Delete portfolio (cascades to assets, transactions, and snapshots)
+ */
+ async deletePortfolio(portfolioId: string): Promise<void> {
+ this.ensureInitialized();
+
+ await this.db!.execute('DELETE FROM portfolios WHERE id = $1', [portfolioId]);
+ console.log(`[PortfolioService] Deleted portfolio: ${portfolioId}`);
+ }
+
+ // ==================== ASSET MANAGEMENT ====================
+
+ /**
+ * Add asset to portfolio
+ */
+ async addAsset(portfolioId: string, symbol: string, quantity: number, buyPrice: number, purchaseDate?: string): Promise<PortfolioAsset> {
+ this.ensureInitialized();
+
+ // Check if asset already exists
+ const existing = await this.db!.select<PortfolioAsset[]>(
+ 'SELECT * FROM portfolio_assets WHERE portfolio_id = $1 AND symbol = $2',
+ [portfolioId, symbol]
+ );
+
+ if (existing.length > 0) {
+ // Update existing position (average down/up)
+ const existingAsset = existing[0];
+ const newQuantity = existingAsset.quantity + quantity;
+ const newAvgPrice = ((existingAsset.avg_buy_price * existingAsset.quantity) + (buyPrice * quantity)) / newQuantity;
+
+ await this.db!.execute(
+ `UPDATE portfolio_assets
+ SET quantity = $1, avg_buy_price = $2, last_updated = datetime('now')
+ WHERE id = $3`,
+ [newQuantity, newAvgPrice, existingAsset.id]
+ );
+
+ // Record transaction
+ await this.addTransaction(portfolioId, symbol, 'BUY', quantity, buyPrice, purchaseDate);
+
+ const result = await this.db!.select<PortfolioAsset[]>(
+ 'SELECT * FROM portfolio_assets WHERE id = $1',
+ [existingAsset.id]
+ );
+
+ return result[0];
+ } else {
+ // Create new position
+ const id = crypto.randomUUID();
+ await this.db!.execute(
+ `INSERT INTO portfolio_assets (id, portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date)
+ VALUES ($1, $2, $3, $4, $5, $6)`,
+ [id, portfolioId, symbol, quantity, buyPrice, purchaseDate || new Date().toISOString()]
+ );
+
+ // Record transaction
+ await this.addTransaction(portfolioId, symbol, 'BUY', quantity, buyPrice, purchaseDate);
+
+ const result = await this.db!.select<PortfolioAsset[]>(
+ 'SELECT * FROM portfolio_assets WHERE id = $1',
+ [id]
+ );
+
+ console.log(`[PortfolioService] Added asset: ${symbol} to portfolio ${portfolioId}`);
+ return result[0];
+ }
+ }
+
+ /**
+ * Remove asset from portfolio
+ */
+ async removeAsset(portfolioId: string, symbol: string): Promise<void> {
+ this.ensureInitialized();
+
+ await this.db!.execute(
+ 'DELETE FROM portfolio_assets WHERE portfolio_id = $1 AND symbol = $2',
+ [portfolioId, symbol]
+ );
+
+ console.log(`[PortfolioService] Removed asset: ${symbol} from portfolio ${portfolioId}`);
+ }
+
+ /**
+ * Update asset (modify quantity and average price)
+ */
+ async updateAsset(portfolioId: string, symbol: string, quantity: number, avgBuyPrice: number): Promise<void> {
+ this.ensureInitialized();
+
+ await this.db!.execute(
+ `UPDATE portfolio_assets
+ SET quantity = $1, avg_buy_price = $2, last_updated = datetime('now')
+ WHERE portfolio_id = $3 AND symbol = $4`,
+ [quantity, avgBuyPrice, portfolioId, symbol]
+ );
+
+ console.log(`[PortfolioService] Updated asset: ${symbol} in portfolio ${portfolioId}`);
+ }
+
+ /**
+ * Sell asset (reduce quantity)
+ */
+ async sellAsset(portfolioId: string, symbol: string, quantity: number, sellPrice: number, transactionDate?: string): Promise<void> {
+ this.ensureInitialized();
+
+ const asset = await this.db!.select<PortfolioAsset[]>(
+ 'SELECT * FROM portfolio_assets WHERE portfolio_id = $1 AND symbol = $2',
+ [portfolioId, symbol]
+ );
+
+ if (asset.length === 0) {
+ throw new Error(`Asset ${symbol} not found in portfolio`);
+ }
+
+ const currentAsset = asset[0];
+
+ if (quantity > currentAsset.quantity) {
+ throw new Error(`Cannot sell ${quantity} shares of ${symbol}. Only ${currentAsset.quantity} available.`);
+ }
+
+ const newQuantity = currentAsset.quantity - quantity;
+
+ if (newQuantity === 0) {
+ // Remove asset completely
+ await this.removeAsset(portfolioId, symbol);
+ } else {
+ // Update quantity
+ await this.db!.execute(
+ `UPDATE portfolio_assets
+ SET quantity = $1, last_updated = datetime('now')
+ WHERE portfolio_id = $2 AND symbol = $3`,
+ [newQuantity, portfolioId, symbol]
+ );
+ }
+
+ // Record sell transaction
+ await this.addTransaction(portfolioId, symbol, 'SELL', quantity, sellPrice, transactionDate);
+
+ console.log(`[PortfolioService] Sold ${quantity} shares of ${symbol} from portfolio ${portfolioId}`);
+ }
+
+ /**
+ * Get all assets in a portfolio
+ */
+ async getPortfolioAssets(portfolioId: string): Promise<PortfolioAsset[]> {
+ this.ensureInitialized();
+
+ return await this.db!.select<PortfolioAsset[]>(
+ 'SELECT * FROM portfolio_assets WHERE portfolio_id = $1 ORDER BY symbol',
+ [portfolioId]
+ );
+ }
+
+ // ==================== TRANSACTION MANAGEMENT ====================
+
+ /**
+ * Add transaction
+ */
+ async addTransaction(
+ portfolioId: string,
+ symbol: string,
+ type: 'BUY' | 'SELL',
+ quantity: number,
+ price: number,
+ transactionDate?: string,
+ notes?: string
+ ): Promise<Transaction> {
+ this.ensureInitialized();
+
+ const id = crypto.randomUUID();
+ const totalValue = quantity * price;
+ const date = transactionDate || new Date().toISOString();
+
+ await this.db!.execute(
+ `INSERT INTO portfolio_transactions
+ (id, portfolio_id, symbol, transaction_type, quantity, price, total_value, transaction_date, notes)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
+ [id, portfolioId, symbol, type, quantity, price, totalValue, date, notes || null]
+ );
+
+ const result = await this.db!.select<Transaction[]>(
+ 'SELECT * FROM portfolio_transactions WHERE id = $1',
+ [id]
+ );
+
+ return result[0];
+ }
+
+ /**
+ * Get all transactions for a portfolio
+ */
+ async getPortfolioTransactions(portfolioId: string, limit: number = 100): Promise<Transaction[]> {
+ this.ensureInitialized();
+
+ return await this.db!.select<Transaction[]>(
+ 'SELECT * FROM portfolio_transactions WHERE portfolio_id = $1 ORDER BY transaction_date DESC LIMIT $2',
+ [portfolioId, limit]
+ );
+ }
+
+ /**
+ * Get transactions for a specific symbol
+ */
+ async getSymbolTransactions(portfolioId: string, symbol: string): Promise<Transaction[]> {
+ this.ensureInitialized();
+
+ return await this.db!.select<Transaction[]>(
+ 'SELECT * FROM portfolio_transactions WHERE portfolio_id = $1 AND symbol = $2 ORDER BY transaction_date DESC',
+ [portfolioId, symbol]
+ );
+ }
+
+ // ==================== PORTFOLIO VALUATION & HOLDINGS ====================
+
+ /**
+ * Fetch market prices for symbols
+ */
+ async fetchMarketPrices(symbols: string[]): Promise<Map<string, QuoteData>> {
+ const quotes = await marketDataService.getQuotes(symbols);
+ const priceMap = new Map<string, QuoteData>();
+
+ quotes.forEach(quote => {
+ priceMap.set(quote.symbol, quote);
+ });
+
+ return priceMap;
+ }
+
+ /**
+ * Calculate portfolio value with current market prices
+ */
+ async calculatePortfolioValue(portfolioId: string): Promise<number> {
+ this.ensureInitialized();
+
+ const assets = await this.getPortfolioAssets(portfolioId);
+
+ if (assets.length === 0) {
+ return 0;
+ }
+
+ const symbols = assets.map(a => a.symbol);
+ const prices = await this.fetchMarketPrices(symbols);
+
+ let totalValue = 0;
+
+ assets.forEach(asset => {
+ const quote = prices.get(asset.symbol);
+ if (quote) {
+ totalValue += quote.price * asset.quantity;
+ }
+ });
+
+ return totalValue;
+ }
+
+ /**
+ * Get portfolio holdings with current market data
+ */
+ async getPortfolioHoldings(portfolioId: string): Promise<PortfolioHolding[]> {
+ this.ensureInitialized();
+
+ const assets = await this.getPortfolioAssets(portfolioId);
+
+ if (assets.length === 0) {
+ return [];
+ }
+
+ const symbols = assets.map(a => a.symbol);
+ const prices = await this.fetchMarketPrices(symbols);
+
+ const holdings: PortfolioHolding[] = [];
+ let totalMarketValue = 0;
+
+ // First pass: calculate total market value
+ assets.forEach(asset => {
+ const quote = prices.get(asset.symbol);
+ if (quote) {
+ totalMarketValue += quote.price * asset.quantity;
+ }
+ });
+
+ // Second pass: create holdings with weights
+ assets.forEach(asset => {
+ const quote = prices.get(asset.symbol);
+
+ if (quote) {
+ const marketValue = quote.price * asset.quantity;
+ const costBasis = asset.avg_buy_price * asset.quantity;
+ const unrealizedPnL = marketValue - costBasis;
+ const unrealizedPnLPercent = (unrealizedPnL / costBasis) * 100;
+ const dayChange = quote.change * asset.quantity;
+ const dayChangePercent = quote.change_percent;
+ const weight = (marketValue / totalMarketValue) * 100;
+
+ holdings.push({
+ ...asset,
+ current_price: quote.price,
+ market_value: marketValue,
+ cost_basis: costBasis,
+ unrealized_pnl: unrealizedPnL,
+ unrealized_pnl_percent: unrealizedPnLPercent,
+ day_change: dayChange,
+ day_change_percent: dayChangePercent,
+ weight: weight
+ });
+ }
+ });
+
+ return holdings;
+ }
+
+ /**
+ * Get complete portfolio summary
+ */
+ async getPortfolioSummary(portfolioId: string): Promise<PortfolioSummary> {
+ this.ensureInitialized();
+
+ const portfolio = await this.getPortfolio(portfolioId);
+ if (!portfolio) {
+ throw new Error(`Portfolio ${portfolioId} not found`);
+ }
+
+ const holdings = await this.getPortfolioHoldings(portfolioId);
+
+ let totalMarketValue = 0;
+ let totalCostBasis = 0;
+ let totalUnrealizedPnL = 0;
+ let totalDayChange = 0;
+
+ holdings.forEach(holding => {
+ totalMarketValue += holding.market_value;
+ totalCostBasis += holding.cost_basis;
+ totalUnrealizedPnL += holding.unrealized_pnl;
+ totalDayChange += holding.day_change;
+ });
+
+ const totalUnrealizedPnLPercent = totalCostBasis > 0 ? (totalUnrealizedPnL / totalCostBasis) * 100 : 0;
+ const totalDayChangePercent = (totalMarketValue - totalDayChange) > 0
+ ? (totalDayChange / (totalMarketValue - totalDayChange)) * 100
+ : 0;
+
+ return {
+ portfolio,
+ total_positions: holdings.length,
+ total_market_value: totalMarketValue,
+ total_cost_basis: totalCostBasis,
+ total_unrealized_pnl: totalUnrealizedPnL,
+ total_unrealized_pnl_percent: totalUnrealizedPnLPercent,
+ total_day_change: totalDayChange,
+ total_day_change_percent: totalDayChangePercent,
+ holdings,
+ last_updated: new Date().toISOString()
+ };
+ }
+
+ // ==================== RETURNS & PERFORMANCE ANALYTICS ====================
+
+ /**
+ * Calculate realized and unrealized P&L
+ */
+ async calculateReturns(portfolioId: string): Promise<{ realized_pnl: number; unrealized_pnl: number; total_pnl: number }> {
+ this.ensureInitialized();
+
+ const summary = await this.getPortfolioSummary(portfolioId);
+ const unrealizedPnL = summary.total_unrealized_pnl;
+
+ // Calculate realized P&L from transactions
+ const transactions = await this.getPortfolioTransactions(portfolioId);
+ let realizedPnL = 0;
+
+ // Group transactions by symbol
+ const symbolGroups = new Map<string, Transaction[]>();
+ transactions.forEach(txn => {
+ if (!symbolGroups.has(txn.symbol)) {
+ symbolGroups.set(txn.symbol, []);
+ }
+ symbolGroups.get(txn.symbol)!.push(txn);
+ });
+
+ // Calculate realized gains/losses using FIFO
+ symbolGroups.forEach((txns, symbol) => {
+ const buys = txns.filter(t => t.transaction_type === 'BUY').reverse();
+ const sells = txns.filter(t => t.transaction_type === 'SELL').reverse();
+
+ sells.forEach(sell => {
+ let remainingQuantity = sell.quantity;
+
+ for (const buy of buys) {
+ if (remainingQuantity <= 0) break;
+
+ const quantityToMatch = Math.min(remainingQuantity, buy.quantity);
+ const costBasis = buy.price * quantityToMatch;
+ const proceeds = sell.price * quantityToMatch;
+ realizedPnL += (proceeds - costBasis);
+
+ remainingQuantity -= quantityToMatch;
+ }
+ });
+ });
+
+ return {
+ realized_pnl: realizedPnL,
+ unrealized_pnl: unrealizedPnL,
+ total_pnl: realizedPnL + unrealizedPnL
+ };
+ }
+
+ // ==================== SNAPSHOTS & HISTORY ====================
+
+ /**
+ * Save portfolio snapshot
+ */
+ async saveSnapshot(portfolioId: string): Promise<PortfolioSnapshot> {
+ this.ensureInitialized();
+
+ const summary = await this.getPortfolioSummary(portfolioId);
+
+ const id = crypto.randomUUID();
+ const snapshotData = JSON.stringify({
+ holdings: summary.holdings,
+ total_positions: summary.total_positions
+ });
+
+ await this.db!.execute(
+ `INSERT INTO portfolio_snapshots
+ (id, portfolio_id, total_value, total_cost_basis, total_pnl, total_pnl_percent, snapshot_data)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,
+ [
+ id,
+ portfolioId,
+ summary.total_market_value,
+ summary.total_cost_basis,
+ summary.total_unrealized_pnl,
+ summary.total_unrealized_pnl_percent,
+ snapshotData
+ ]
+ );
+
+ const result = await this.db!.select<PortfolioSnapshot[]>(
+ 'SELECT * FROM portfolio_snapshots WHERE id = $1',
+ [id]
+ );
+
+ console.log(`[PortfolioService] Saved snapshot for portfolio ${portfolioId}`);
+ return result[0];
+ }
+
+ /**
+ * Get portfolio performance history
+ */
+ async getPortfolioPerformanceHistory(portfolioId: string, limit: number = 30): Promise<PortfolioSnapshot[]> {
+ this.ensureInitialized();
+
+ return await this.db!.select<PortfolioSnapshot[]>(
+ 'SELECT * FROM portfolio_snapshots WHERE portfolio_id = $1 ORDER BY snapshot_date DESC LIMIT $2',
+ [portfolioId, limit]
+ );
+ }
+
+ // ==================== REBALANCING ====================
+
+ /**
+ * Rebalance portfolio to target weights
+ * Strategy: 'equal' - equal weight all positions, or custom weight map
+ */
+ async rebalancePortfolio(portfolioId: string, strategy: 'equal' | Map<string, number>): Promise<Map<string, { action: 'BUY' | 'SELL'; quantity: number; reason: string }>> {
+ this.ensureInitialized();
+
+ const holdings = await this.getPortfolioHoldings(portfolioId);
+ const totalValue = holdings.reduce((sum, h) => sum + h.market_value, 0);
+
+ const rebalanceActions = new Map<string, { action: 'BUY' | 'SELL'; quantity: number; reason: string }>();
+
+ if (strategy === 'equal') {
+ const targetWeight = 100 / holdings.length;
+
+ holdings.forEach(holding => {
+ const currentWeight = holding.weight;
+ const diff = targetWeight - currentWeight;
+
+ if (Math.abs(diff) > 0.5) { // 0.5% threshold
+ const targetValue = (targetWeight / 100) * totalValue;
+ const currentValue = holding.market_value;
+ const valueDiff = targetValue - currentValue;
+ const quantityDiff = valueDiff / holding.current_price;
+
+ rebalanceActions.set(holding.symbol, {
+ action: quantityDiff > 0 ? 'BUY' : 'SELL',
+ quantity: Math.abs(quantityDiff),
+ reason: `Rebalance from ${currentWeight.toFixed(2)}% to ${targetWeight.toFixed(2)}%`
+ });
+ }
+ });
+ } else {
+ // Custom weight map
+ holdings.forEach(holding => {
+ const targetWeight = strategy.get(holding.symbol) || 0;
+ const currentWeight = holding.weight;
+ const diff = targetWeight - currentWeight;
+
+ if (Math.abs(diff) > 0.5) {
+ const targetValue = (targetWeight / 100) * totalValue;
+ const currentValue = holding.market_value;
+ const valueDiff = targetValue - currentValue;
+ const quantityDiff = valueDiff / holding.current_price;
+
+ rebalanceActions.set(holding.symbol, {
+ action: quantityDiff > 0 ? 'BUY' : 'SELL',
+ quantity: Math.abs(quantityDiff),
+ reason: `Rebalance from ${currentWeight.toFixed(2)}% to ${targetWeight.toFixed(2)}%`
+ });
+ }
+ });
+ }
+
+ return rebalanceActions;
+ }
+
+ // ==================== EXPORT ====================
+
+ /**
+ * Export portfolio data as CSV
+ */
+ async exportPortfolioCSV(portfolioId: string): Promise<string> {
+ const summary = await this.getPortfolioSummary(portfolioId);
+
+ let csv = 'Symbol,Quantity,Avg Buy Price,Current Price,Market Value,Cost Basis,Unrealized P&L,Unrealized P&L %,Day Change,Day Change %,Weight %\n';
+
+ summary.holdings.forEach(holding => {
+ csv += `${holding.symbol},${holding.quantity},${holding.avg_buy_price.toFixed(2)},${holding.current_price.toFixed(2)},${holding.market_value.toFixed(2)},${holding.cost_basis.toFixed(2)},${holding.unrealized_pnl.toFixed(2)},${holding.unrealized_pnl_percent.toFixed(2)},${holding.day_change.toFixed(2)},${holding.day_change_percent.toFixed(2)},${holding.weight.toFixed(2)}\n`;
+ });
+
+ csv += `\nTOTAL,,,,${summary.total_market_value.toFixed(2)},${summary.total_cost_basis.toFixed(2)},${summary.total_unrealized_pnl.toFixed(2)},${summary.total_unrealized_pnl_percent.toFixed(2)},${summary.total_day_change.toFixed(2)},${summary.total_day_change_percent.toFixed(2)},100.00\n`;
+
+ return csv;
+ }
+
+ /**
+ * Export portfolio transactions as CSV
+ */
+ async exportTransactionsCSV(portfolioId: string): Promise<string> {
+ const transactions = await this.getPortfolioTransactions(portfolioId, 1000);
+
+ let csv = 'Date,Symbol,Type,Quantity,Price,Total Value,Notes\n';
+
+ transactions.forEach(txn => {
+ csv += `${txn.transaction_date},${txn.symbol},${txn.transaction_type},${txn.quantity},${txn.price.toFixed(2)},${txn.total_value.toFixed(2)},"${txn.notes || ''}"\n`;
+ });
+
+ return csv;
+ }
+
+ // ==================== UTILITY ====================
+
+ /**
+ * Check if service is ready
+ */
+ isReady(): boolean {
+ return this.isInitialized && this.db !== null;
+ }
+
+ /**
+ * Get service status
+ */
+ getStatus(): { initialized: boolean; ready: boolean } {
+ return {
+ initialized: this.isInitialized,
+ ready: this.isReady()
+ };
+ }
+}
+
+// Export singleton instance
+export const portfolioService = new PortfolioService();
+export default portfolioService;
diff --git a/fincept-terminal-desktop/src/services/sectorService.ts b/fincept-terminal-desktop/src/services/sectorService.ts
new file mode 100644
index 000000000..6d682bde9
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/sectorService.ts
@@ -0,0 +1,210 @@
+// Sector Classification Service
+// Maps stock symbols to their sectors and industries
+
+export interface SectorInfo {
+ sector: string;
+ industry?: string;
+ description?: string;
+}
+
+// Common sector classifications (GICS sectors)
+export const SECTORS = {
+ TECHNOLOGY: 'Technology',
+ HEALTHCARE: 'Healthcare',
+ FINANCIAL: 'Financial Services',
+ CONSUMER_CYCLICAL: 'Consumer Cyclical',
+ CONSUMER_DEFENSIVE: 'Consumer Defensive',
+ INDUSTRIALS: 'Industrials',
+ ENERGY: 'Energy',
+ UTILITIES: 'Utilities',
+ REAL_ESTATE: 'Real Estate',
+ MATERIALS: 'Basic Materials',
+ COMMUNICATION: 'Communication Services',
+ CRYPTO: 'Cryptocurrency',
+ OTHER: 'Other'
+};
+
+// Known symbol to sector mappings
+const SYMBOL_SECTOR_MAP: Record<string, SectorInfo> = {
+ // Technology
+ 'AAPL': { sector: SECTORS.TECHNOLOGY, industry: 'Consumer Electronics' },
+ 'MSFT': { sector: SECTORS.TECHNOLOGY, industry: 'Software' },
+ 'GOOGL': { sector: SECTORS.COMMUNICATION, industry: 'Internet Content' },
+ 'GOOG': { sector: SECTORS.COMMUNICATION, industry: 'Internet Content' },
+ 'AMZN': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Internet Retail' },
+ 'META': { sector: SECTORS.COMMUNICATION, industry: 'Social Media' },
+ 'NVDA': { sector: SECTORS.TECHNOLOGY, industry: 'Semiconductors' },
+ 'TSLA': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Auto Manufacturers' },
+ 'AMD': { sector: SECTORS.TECHNOLOGY, industry: 'Semiconductors' },
+ 'INTC': { sector: SECTORS.TECHNOLOGY, industry: 'Semiconductors' },
+ 'CRM': { sector: SECTORS.TECHNOLOGY, industry: 'Software' },
+ 'ORCL': { sector: SECTORS.TECHNOLOGY, industry: 'Software' },
+ 'ADBE': { sector: SECTORS.TECHNOLOGY, industry: 'Software' },
+ 'CSCO': { sector: SECTORS.TECHNOLOGY, industry: 'Communication Equipment' },
+ 'IBM': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },
+
+ // Healthcare
+ 'JNJ': { sector: SECTORS.HEALTHCARE, industry: 'Drug Manufacturers' },
+ 'UNH': { sector: SECTORS.HEALTHCARE, industry: 'Healthcare Plans' },
+ 'PFE': { sector: SECTORS.HEALTHCARE, industry: 'Drug Manufacturers' },
+ 'ABBV': { sector: SECTORS.HEALTHCARE, industry: 'Drug Manufacturers' },
+ 'TMO': { sector: SECTORS.HEALTHCARE, industry: 'Diagnostics & Research' },
+ 'ABT': { sector: SECTORS.HEALTHCARE, industry: 'Medical Devices' },
+ 'MRK': { sector: SECTORS.HEALTHCARE, industry: 'Drug Manufacturers' },
+
+ // Financial
+ 'JPM': { sector: SECTORS.FINANCIAL, industry: 'Banks' },
+ 'BAC': { sector: SECTORS.FINANCIAL, industry: 'Banks' },
+ 'WFC': { sector: SECTORS.FINANCIAL, industry: 'Banks' },
+ 'GS': { sector: SECTORS.FINANCIAL, industry: 'Capital Markets' },
+ 'MS': { sector: SECTORS.FINANCIAL, industry: 'Capital Markets' },
+ 'V': { sector: SECTORS.FINANCIAL, industry: 'Credit Services' },
+ 'MA': { sector: SECTORS.FINANCIAL, industry: 'Credit Services' },
+ 'BRK.B': { sector: SECTORS.FINANCIAL, industry: 'Insurance' },
+
+ // Consumer
+ 'WMT': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Discount Stores' },
+ 'PG': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Household Products' },
+ 'KO': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Beverages' },
+ 'PEP': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Beverages' },
+ 'COST': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Discount Stores' },
+ 'NKE': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Footwear & Accessories' },
+ 'MCD': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Restaurants' },
+ 'SBUX': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Restaurants' },
+ 'DIS': { sector: SECTORS.COMMUNICATION, industry: 'Entertainment' },
+ 'NFLX': { sector: SECTORS.COMMUNICATION, industry: 'Entertainment' },
+
+ // Energy
+ 'XOM': { sector: SECTORS.ENERGY, industry: 'Oil & Gas' },
+ 'CVX': { sector: SECTORS.ENERGY, industry: 'Oil & Gas' },
+ 'COP': { sector: SECTORS.ENERGY, industry: 'Oil & Gas' },
+
+ // Industrials
+ 'BA': { sector: SECTORS.INDUSTRIALS, industry: 'Aerospace & Defense' },
+ 'HON': { sector: SECTORS.INDUSTRIALS, industry: 'Conglomerates' },
+ 'UPS': { sector: SECTORS.INDUSTRIALS, industry: 'Integrated Freight & Logistics' },
+ 'CAT': { sector: SECTORS.INDUSTRIALS, industry: 'Farm & Heavy Machinery' },
+
+ // Indian Stocks
+ 'RELIANCE.NS': { sector: SECTORS.ENERGY, industry: 'Oil & Gas Refining' },
+ 'RELIANCE.BO': { sector: SECTORS.ENERGY, industry: 'Oil & Gas Refining' },
+ 'TCS.NS': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },
+ 'TCS.BO': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },
+ 'INFY.NS': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },
+ 'INFY.BO': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },
+ 'HDFCBANK.NS': { sector: SECTORS.FINANCIAL, industry: 'Banks' },
+ 'HDFCBANK.BO': { sector: SECTORS.FINANCIAL, industry: 'Banks' },
+ 'ITC.NS': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Tobacco' },
+ 'ITC.BO': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Tobacco' },
+
+ // Cryptocurrency
+ 'BTC-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },
+ 'ETH-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },
+ 'USDT-USD': { sector: SECTORS.CRYPTO, industry: 'Stablecoin' },
+ 'BNB-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },
+ 'XRP-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },
+ 'SOL-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },
+ 'ADA-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },
+ 'DOGE-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },
+
+ // ETFs
+ 'SPY': { sector: SECTORS.OTHER, industry: 'Index ETF' },
+ 'QQQ': { sector: SECTORS.OTHER, industry: 'Index ETF' },
+ 'VOO': { sector: SECTORS.OTHER, industry: 'Index ETF' },
+ 'VTI': { sector: SECTORS.OTHER, industry: 'Index ETF' },
+ 'IWM': { sector: SECTORS.OTHER, industry: 'Index ETF' },
+};
+
+class SectorService {
+ /**
+ * Get sector information for a symbol
+ */
+ getSectorInfo(symbol: string): SectorInfo {
+ // Normalize symbol (uppercase, remove exchange suffix variations)
+ const normalizedSymbol = symbol.toUpperCase().trim();
+
+ // Check direct mapping
+ if (SYMBOL_SECTOR_MAP[normalizedSymbol]) {
+ return SYMBOL_SECTOR_MAP[normalizedSymbol];
+ }
+
+ // Check without exchange suffix (.NS, .BO, etc.)
+ const baseSymbol = normalizedSymbol.split('.')[0];
+ if (SYMBOL_SECTOR_MAP[baseSymbol]) {
+ return SYMBOL_SECTOR_MAP[baseSymbol];
+ }
+
+ // Heuristic classification based on symbol patterns
+ return this.classifyByPattern(normalizedSymbol);
+ }
+
+ /**
+ * Classify symbol by patterns (fallback)
+ */
+ private classifyByPattern(symbol: string): SectorInfo {
+ // Crypto patterns
+ if (symbol.endsWith('-USD') || symbol.endsWith('USD') || symbol.endsWith('USDT')) {
+ return { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' };
+ }
+
+ // ETF patterns
+ if (symbol.length === 3 && (symbol.startsWith('V') || symbol.startsWith('I') || symbol.startsWith('S'))) {
+ return { sector: SECTORS.OTHER, industry: 'Index ETF' };
+ }
+
+ // Indian stocks
+ if (symbol.endsWith('.NS') || symbol.endsWith('.BO')) {
+ return { sector: SECTORS.OTHER, industry: 'Indian Stock' };
+ }
+
+ // Default fallback
+ return { sector: SECTORS.OTHER, industry: 'Unknown' };
+ }
+
+ /**
+ * Get all unique sectors from a list of symbols
+ */
+ getUniqueSectors(symbols: string[]): string[] {
+ const sectors = new Set<string>();
+ symbols.forEach(symbol => {
+ const info = this.getSectorInfo(symbol);
+ sectors.add(info.sector);
+ });
+ return Array.from(sectors).sort();
+ }
+
+ /**
+ * Group symbols by sector
+ */
+ groupBySector(symbols: string[]): Record<string, string[]> {
+ const grouped: Record<string, string[]> = {};
+
+ symbols.forEach(symbol => {
+ const info = this.getSectorInfo(symbol);
+ if (!grouped[info.sector]) {
+ grouped[info.sector] = [];
+ }
+ grouped[info.sector].push(symbol);
+ });
+
+ return grouped;
+ }
+
+ /**
+ * Add custom sector mapping
+ */
+ addSectorMapping(symbol: string, sectorInfo: SectorInfo): void {
+ SYMBOL_SECTOR_MAP[symbol.toUpperCase()] = sectorInfo;
+ }
+
+ /**
+ * Get all supported sectors
+ */
+ getAllSectors(): string[] {
+ return Object.values(SECTORS);
+ }
+}
+
+// Export singleton
+export const sectorService = new SectorService();
+export default sectorService;
diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.ts
index 13edc88e3..7c36730fd 100644
--- a/fincept-terminal-desktop/src/services/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/sqliteService.ts
@@ -263,6 +263,64 @@ class SQLiteService {
)
`);
+ // Portfolio tables
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS portfolios (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ owner TEXT NOT NULL,
+ currency TEXT DEFAULT 'USD',
+ description TEXT,
+ created_at TEXT DEFAULT (datetime('now')),
+ updated_at TEXT DEFAULT (datetime('now'))
+ )
+ `);
+
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS portfolio_assets (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ quantity REAL NOT NULL,
+ avg_buy_price REAL NOT NULL,
+ first_purchase_date TEXT,
+ last_updated TEXT DEFAULT (datetime('now')),
+ notes TEXT,
+ FOREIGN KEY (portfolio_id) REFERENCES portfolios(id) ON DELETE CASCADE,
+ UNIQUE(portfolio_id, symbol)
+ )
+ `);
+
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS portfolio_transactions (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ transaction_type TEXT NOT NULL,
+ quantity REAL NOT NULL,
+ price REAL NOT NULL,
+ total_value REAL NOT NULL,
+ transaction_date TEXT NOT NULL,
+ notes TEXT,
+ created_at TEXT DEFAULT (datetime('now')),
+ FOREIGN KEY (portfolio_id) REFERENCES portfolios(id) ON DELETE CASCADE
+ )
+ `);
+
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS portfolio_snapshots (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ total_value REAL NOT NULL,
+ total_cost_basis REAL NOT NULL,
+ total_pnl REAL NOT NULL,
+ total_pnl_percent REAL NOT NULL,
+ snapshot_date TEXT DEFAULT (datetime('now')),
+ snapshot_data TEXT NOT NULL,
+ FOREIGN KEY (portfolio_id) REFERENCES portfolios(id) ON DELETE CASCADE
+ )
+ `);
+
// Create indexes
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_credentials_service ON credentials(service_name)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_settings_category ON settings(category)`);
@@ -273,6 +331,11 @@ class SQLiteService {
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_mcp_usage_timestamp ON mcp_tool_usage(timestamp DESC)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_market_cache_category ON market_data_cache(category)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_market_cache_time ON market_data_cache(cached_at)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_portfolio_assets_portfolio ON portfolio_assets(portfolio_id)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_portfolio_transactions_portfolio ON portfolio_transactions(portfolio_id)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_portfolio_transactions_date ON portfolio_transactions(transaction_date DESC)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_portfolio_snapshots_portfolio ON portfolio_snapshots(portfolio_id)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_portfolio_snapshots_date ON portfolio_snapshots(snapshot_date DESC)`);
}
private async seedDefaultSettings(): Promise<void> {