forked from CurrentDao-org/CurrentDao-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathportfolio-analytics.patch
More file actions
3220 lines (3210 loc) · 127 KB
/
Copy pathportfolio-analytics.patch
File metadata and controls
3220 lines (3210 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
From 3b49b8c228c0c3971a47a99d951c47695eac0a1a Mon Sep 17 00:00:00 2001
From: Gift Austin <giftaustin@Gifts-MacBook-Pro.local>
Date: Sat, 28 Mar 2026 07:37:11 -0400
Subject: [PATCH 1/3] feat: Add comprehensive portfolio analytics interface
- Create complete trading history and portfolio analytics system
- Implement PerformanceMetrics component with ROI, Sharpe ratio, volatility
- Add ProfitLoss component with P&L analysis and trend tracking
- Create AssetAllocation component with rebalancing recommendations
- Implement TradingStatistics component with cost analysis and tax reporting
- Add TradingHistory component with filtering, sorting, and export
- Create portfolio calculation utilities and analytics hook
- Build main portfolio history page with tabbed navigation
- Support CSV, PDF, JSON, and Excel export functionality
- Include mobile-responsive design with Tailwind CSS
---
app/portfolio/history/page.tsx | 272 +++++++++++++
components/portfolio/AssetAllocation.tsx | 413 +++++++++++++++++++
components/portfolio/PerformanceMetrics.tsx | 244 ++++++++++++
components/portfolio/ProfitLoss.tsx | 355 +++++++++++++++++
components/portfolio/TradingHistory.tsx | 417 +++++++++++++++++++
components/portfolio/TradingStatistics.tsx | 404 +++++++++++++++++++
hooks/usePortfolioAnalytics.ts | 381 ++++++++++++++++++
types/portfolio.ts | 137 +++++++
utils/portfolioCalculations.ts | 420 ++++++++++++++++++++
9 files changed, 3043 insertions(+)
create mode 100644 app/portfolio/history/page.tsx
create mode 100644 components/portfolio/AssetAllocation.tsx
create mode 100644 components/portfolio/PerformanceMetrics.tsx
create mode 100644 components/portfolio/ProfitLoss.tsx
create mode 100644 components/portfolio/TradingHistory.tsx
create mode 100644 components/portfolio/TradingStatistics.tsx
create mode 100644 hooks/usePortfolioAnalytics.ts
create mode 100644 types/portfolio.ts
create mode 100644 utils/portfolioCalculations.ts
diff --git a/app/portfolio/history/page.tsx b/app/portfolio/history/page.tsx
new file mode 100644
index 0000000..34b9eb6
--- /dev/null
+++ b/app/portfolio/history/page.tsx
@@ -0,0 +1,272 @@
+import React, { useState } from 'react';
+import { usePortfolioAnalytics } from '../../../hooks/usePortfolioAnalytics';
+import { TradingHistory } from '../../../components/portfolio/TradingHistory';
+import { PerformanceMetrics } from '../../../components/portfolio/PerformanceMetrics';
+import { ProfitLoss } from '../../../components/portfolio/ProfitLoss';
+import { AssetAllocation } from '../../../components/portfolio/AssetAllocation';
+import { TradingStatistics } from '../../../components/portfolio/TradingStatistics';
+import { ExportOptions } from '../../../types/portfolio';
+
+export default function PortfolioHistoryPage() {
+ const [activeTab, setActiveTab] = useState<'overview' | 'history' | 'metrics' | 'pnl' | 'allocation' | 'statistics'>('overview');
+ const [dateRange, setDateRange] = useState<'1m' | '3m' | '6m' | '1y' | 'all'>('all');
+ const [isExporting, setIsExporting] = useState(false);
+
+ const { analytics, loading, error, trades, portfolio, exportData, refreshData, addTrade, updateTrade, deleteTrade } = usePortfolioAnalytics();
+
+ const handleExport = async (format: 'csv' | 'pdf' | 'json' | 'excel') => {
+ if (!analytics) return;
+
+ setIsExporting(true);
+ try {
+ const exportOptions: ExportOptions = {
+ format,
+ dateRange: {
+ start: dateRange === 'all' ? new Date('2020-01-01') : new Date(Date.now() - (dateRange === '1m' ? 30 : dateRange === '3m' ? 90 : dateRange === '6m' ? 180 : 365) * 24 * 60 * 60 * 1000),
+ end: new Date()
+ },
+ includeMetrics: ['performance', 'allocation', 'pnl', 'statistics'],
+ includeCharts: true
+ };
+
+ const data = await exportData(exportOptions);
+
+ const blob = new Blob([data], {
+ type: format === 'json' ? 'application/json' :
+ format === 'csv' ? 'text/csv' :
+ format === 'pdf' ? 'application/pdf' :
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
+ });
+
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `portfolio-analytics-${new Date().toISOString().split('T')[0]}.${format}`;
+ a.click();
+ URL.revokeObjectURL(url);
+ } catch (err) {
+ console.error('Export failed:', err);
+ } finally {
+ setIsExporting(false);
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="min-h-screen bg-gray-50 flex items-center justify-center">
+ <div className="text-center">
+ <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
+ <p className="text-gray-600">Loading portfolio analytics...</p>
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="min-h-screen bg-gray-50 flex items-center justify-center">
+ <div className="text-center">
+ <div className="bg-red-100 rounded-full p-4 w-16 h-16 mx-auto mb-4">
+ <span className="text-red-600 text-2xl">⚠️</span>
+ </div>
+ <h2 className="text-xl font-semibold text-gray-900 mb-2">Error Loading Data</h2>
+ <p className="text-gray-600 mb-4">{error}</p>
+ <button
+ onClick={refreshData}
+ className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
+ >
+ Retry
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ if (!analytics) {
+ return (
+ <div className="min-h-screen bg-gray-50 flex items-center justify-center">
+ <div className="text-center">
+ <p className="text-gray-600">No portfolio data available</p>
+ </div>
+ </div>
+ );
+ }
+
+ const tabs = [
+ { id: 'overview', label: 'Overview', icon: '📊' },
+ { id: 'history', label: 'Trading History', icon: '📜' },
+ { id: 'metrics', label: 'Performance', icon: '📈' },
+ { id: 'pnl', label: 'P&L Analysis', icon: '💰' },
+ { id: 'allocation', label: 'Allocation', icon: '🎯' },
+ { id: 'statistics', label: 'Statistics', icon: '📊' }
+ ];
+
+ const dateRanges = [
+ { id: '1m', label: '1 Month' },
+ { id: '3m', label: '3 Months' },
+ { id: '6m', label: '6 Months' },
+ { id: '1y', label: '1 Year' },
+ { id: 'all', label: 'All Time' }
+ ];
+
+ return (
+ <div className="min-h-screen bg-gray-50">
+ <div className="bg-white shadow-sm border-b border-gray-200">
+ <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
+ <div className="flex justify-between items-center py-6">
+ <div>
+ <h1 className="text-3xl font-bold text-gray-900">Portfolio Analytics</h1>
+ <p className="text-gray-600 mt-1">
+ {portfolio?.name || 'Energy Trading Portfolio'} •
+ Total Value: {new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 0
+ }).format(analytics.portfolio.totalValue)}
+ </p>
+ </div>
+ <div className="flex items-center space-x-4">
+ <select
+ value={dateRange}
+ onChange={(e) => setDateRange(e.target.value as any)}
+ className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
+ >
+ {dateRanges.map(range => (
+ <option key={range.id} value={range.id}>{range.label}</option>
+ ))}
+ </select>
+ <button
+ onClick={refreshData}
+ className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
+ >
+ Refresh
+ </button>
+ <div className="relative">
+ <button
+ onClick={() => {}}
+ className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
+ >
+ <span>Export</span>
+ <span>⬇️</span>
+ </button>
+ <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 z-10 hidden">
+ <div className="py-1">
+ {['csv', 'pdf', 'json', 'excel'].map(format => (
+ <button
+ key={format}
+ onClick={() => handleExport(format as any)}
+ disabled={isExporting}
+ className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 disabled:opacity-50"
+ >
+ Export as {format.toUpperCase()}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex space-x-8 overflow-x-auto">
+ {tabs.map(tab => (
+ <button
+ key={tab.id}
+ onClick={() => setActiveTab(tab.id as any)}
+ className={`flex items-center space-x-2 py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
+ activeTab === tab.id
+ ? 'border-blue-600 text-blue-600'
+ : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
+ }`}
+ >
+ <span>{tab.icon}</span>
+ <span>{tab.label}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
+ {activeTab === 'overview' && (
+ <div className="space-y-6">
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ <PerformanceMetrics metrics={analytics.metrics} />
+ <ProfitLoss profitLoss={analytics.profitLoss} />
+ </div>
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ <AssetAllocation allocation={analytics.allocation} />
+ <TradingStatistics
+ statistics={analytics.statistics}
+ taxReports={analytics.taxReports}
+ />
+ </div>
+ </div>
+ )}
+
+ {activeTab === 'history' && (
+ <TradingHistory
+ trades={trades}
+ onTradeUpdate={updateTrade}
+ onTradeDelete={deleteTrade}
+ />
+ )}
+
+ {activeTab === 'metrics' && (
+ <PerformanceMetrics metrics={analytics.metrics} />
+ )}
+
+ {activeTab === 'pnl' && (
+ <ProfitLoss profitLoss={analytics.profitLoss} />
+ )}
+
+ {activeTab === 'allocation' && (
+ <AssetAllocation allocation={analytics.allocation} />
+ )}
+
+ {activeTab === 'statistics' && (
+ <TradingStatistics
+ statistics={analytics.statistics}
+ taxReports={analytics.taxReports}
+ />
+ )}
+ </div>
+
+ <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 border-t border-gray-200">
+ <div className="bg-blue-50 rounded-lg p-6">
+ <h3 className="text-lg font-semibold text-blue-900 mb-4">Quick Actions</h3>
+ <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
+ <button
+ onClick={() => setActiveTab('history')}
+ className="flex items-center justify-center space-x-2 px-4 py-3 bg-white rounded-lg hover:bg-gray-50 transition-colors border border-blue-200"
+ >
+ <span>📜</span>
+ <span className="text-sm font-medium text-gray-900">View All Trades</span>
+ </button>
+ <button
+ onClick={() => setActiveTab('metrics')}
+ className="flex items-center justify-center space-x-2 px-4 py-3 bg-white rounded-lg hover:bg-gray-50 transition-colors border border-blue-200"
+ >
+ <span>📈</span>
+ <span className="text-sm font-medium text-gray-900">Performance Report</span>
+ </button>
+ <button
+ onClick={() => setActiveTab('allocation')}
+ className="flex items-center justify-center space-x-2 px-4 py-3 bg-white rounded-lg hover:bg-gray-50 transition-colors border border-blue-200"
+ >
+ <span>🎯</span>
+ <span className="text-sm font-medium text-gray-900">Rebalance Portfolio</span>
+ </button>
+ <button
+ onClick={() => handleExport('pdf')}
+ disabled={isExporting}
+ className="flex items-center justify-center space-x-2 px-4 py-3 bg-white rounded-lg hover:bg-gray-50 transition-colors border border-blue-200 disabled:opacity-50"
+ >
+ <span>📄</span>
+ <span className="text-sm font-medium text-gray-900">Tax Report</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/components/portfolio/AssetAllocation.tsx b/components/portfolio/AssetAllocation.tsx
new file mode 100644
index 0000000..5e2461e
--- /dev/null
+++ b/components/portfolio/AssetAllocation.tsx
@@ -0,0 +1,413 @@
+import React, { useState } from 'react';
+import { AssetAllocation, PortfolioAsset } from '../../types/portfolio';
+
+interface AssetAllocationProps {
+ allocation: AssetAllocation[];
+ className?: string;
+}
+
+export const AssetAllocation: React.FC<AssetAllocationProps> = ({
+ allocation,
+ className = ''
+}) => {
+ const [selectedAssetType, setSelectedAssetType] = useState<string | null>(null);
+ const [viewMode, setViewMode] = useState<'chart' | 'table'>('chart');
+
+ const formatCurrency = (amount: number) => {
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 2
+ }).format(amount);
+ };
+
+ const formatPercentage = (value: number) => {
+ return `${value.toFixed(2)}%`;
+ };
+
+ const getAssetTypeColor = (assetType: string) => {
+ const colors: Record<string, string> = {
+ solar: '#FCD34D',
+ wind: '#60A5FA',
+ hydro: '#67E8F9',
+ nuclear: '#A78BFA',
+ fossil: '#9CA3AF',
+ battery: '#34D399',
+ grid: '#FB923C'
+ };
+ return colors[assetType] || '#9CA3AF';
+ };
+
+ const getAssetTypeIcon = (assetType: string) => {
+ const icons: Record<string, string> = {
+ solar: '☀️',
+ wind: '💨',
+ hydro: '💧',
+ nuclear: '⚛️',
+ fossil: '🏭',
+ battery: '🔋',
+ grid: '⚡'
+ };
+ return icons[assetType] || '📊';
+ };
+
+ const totalValue = allocation.reduce((sum, item) => sum + item.value, 0);
+
+ const getAllocationStatus = (current: number, target: number) => {
+ const deviation = Math.abs(current - target);
+ if (deviation <= 2) return { status: 'Balanced', color: 'text-green-600' };
+ if (deviation <= 5) return { status: 'Minor Deviation', color: 'text-yellow-600' };
+ return { status: 'Rebalancing Needed', color: 'text-red-600' };
+ };
+
+ const exportToCSV = () => {
+ const headers = ['Asset Type', 'Value', 'Current %', 'Target %', 'Deviation', 'Status'];
+ const rows = allocation.map(item => {
+ const status = getAllocationStatus(item.percentage, item.targetPercentage);
+ return [
+ item.assetType,
+ formatCurrency(item.value),
+ formatPercentage(item.percentage),
+ formatPercentage(item.targetPercentage),
+ formatPercentage(item.deviation),
+ status.status
+ ];
+ });
+
+ const csv = [headers, ...rows].map(row => row.join(',')).join('\n');
+ const blob = new Blob([csv], { type: 'text/csv' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `asset-allocation-${new Date().toISOString().split('T')[0]}.csv`;
+ a.click();
+ URL.revokeObjectURL(url);
+ };
+
+ return (
+ <div className={`bg-white rounded-lg shadow-lg p-6 ${className}`}>
+ <div className="flex justify-between items-center mb-6">
+ <h2 className="text-2xl font-bold text-gray-900">Asset Allocation</h2>
+ <div className="flex space-x-4">
+ <button
+ onClick={exportToCSV}
+ className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
+ >
+ Export CSV
+ </button>
+ </div>
+ </div>
+
+ <div className="flex items-center justify-between mb-6">
+ <div className="flex space-x-2">
+ <button
+ onClick={() => setViewMode('chart')}
+ className={`px-3 py-1 rounded-lg text-sm font-medium transition-colors ${
+ viewMode === 'chart'
+ ? 'bg-blue-600 text-white'
+ : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
+ }`}
+ >
+ Chart View
+ </button>
+ <button
+ onClick={() => setViewMode('table')}
+ className={`px-3 py-1 rounded-lg text-sm font-medium transition-colors ${
+ viewMode === 'table'
+ ? 'bg-blue-600 text-white'
+ : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
+ }`}
+ >
+ Table View
+ </button>
+ </div>
+ <div className="text-sm text-gray-600">
+ Total Portfolio Value: <span className="font-bold text-gray-900">{formatCurrency(totalValue)}</span>
+ </div>
+ </div>
+
+ {viewMode === 'chart' ? (
+ <div className="space-y-6">
+ <div className="bg-gray-50 rounded-lg p-6">
+ <h3 className="text-lg font-semibold text-gray-900 mb-4">Allocation Distribution</h3>
+ <div className="space-y-4">
+ {allocation.map((item) => (
+ <div key={item.assetType} className="space-y-2">
+ <div className="flex justify-between items-center">
+ <div className="flex items-center space-x-2">
+ <span className="text-lg">{getAssetTypeIcon(item.assetType)}</span>
+ <span className="font-medium text-gray-900 capitalize">{item.assetType}</span>
+ </div>
+ <div className="text-right">
+ <span className="font-bold text-gray-900">{formatPercentage(item.percentage)}</span>
+ <span className="text-sm text-gray-500 ml-2">
+ Target: {formatPercentage(item.targetPercentage)}
+ </span>
+ </div>
+ </div>
+ <div className="relative">
+ <div className="w-full bg-gray-200 rounded-full h-8">
+ <div
+ className="h-8 rounded-full flex items-center justify-center text-white text-xs font-medium transition-all duration-300"
+ style={{
+ width: `${Math.min(item.percentage, 100)}%`,
+ backgroundColor: getAssetTypeColor(item.assetType)
+ }}
+ >
+ {item.percentage >= 5 && formatPercentage(item.percentage)}
+ </div>
+ </div>
+ {item.targetPercentage > 0 && (
+ <div
+ className="absolute top-0 h-8 border-l-2 border-dashed border-red-400"
+ style={{ left: `${item.targetPercentage}%` }}
+ />
+ )}
+ </div>
+ <div className="flex justify-between items-center text-sm">
+ <span className="text-gray-600">{formatCurrency(item.value)}</span>
+ <div className="flex items-center space-x-2">
+ {(() => {
+ const status = getAllocationStatus(item.percentage, item.targetPercentage);
+ return (
+ <>
+ <span className={status.color}>{status.status}</span>
+ <button
+ onClick={() => setSelectedAssetType(
+ selectedAssetType === item.assetType ? null : item.assetType
+ )}
+ className="text-blue-600 hover:text-blue-800"
+ >
+ {selectedAssetType === item.assetType ? 'Hide' : 'Show'} Details
+ </button>
+ </>
+ );
+ })()}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="bg-gray-50 rounded-lg p-6">
+ <h3 className="text-lg font-semibold text-gray-900 mb-4">Rebalancing Recommendations</h3>
+ <div className="space-y-3">
+ {allocation
+ .filter(item => Math.abs(item.deviation) > 2)
+ .sort((a, b) => Math.abs(b.deviation) - Math.abs(a.deviation))
+ .map((item) => (
+ <div key={item.assetType} className="flex items-center justify-between p-3 bg-white rounded-lg">
+ <div className="flex items-center space-x-3">
+ <span className="text-lg">{getAssetTypeIcon(item.assetType)}</span>
+ <div>
+ <p className="font-medium text-gray-900 capitalize">{item.assetType}</p>
+ <p className="text-sm text-gray-600">
+ Current: {formatPercentage(item.percentage)} vs Target: {formatPercentage(item.targetPercentage)}
+ </p>
+ </div>
+ </div>
+ <div className="text-right">
+ <p className={`font-medium ${item.percentage > item.targetPercentage ? 'text-red-600' : 'text-green-600'}`}>
+ {item.percentage > item.targetPercentage ? 'Reduce' : 'Increase'} by {formatPercentage(Math.abs(item.deviation))}
+ </p>
+ <p className="text-sm text-gray-600">
+ {formatCurrency((Math.abs(item.deviation) / 100) * totalValue)}
+ </p>
+ </div>
+ </div>
+ ))}
+ {allocation.filter(item => Math.abs(item.deviation) > 2).length === 0 && (
+ <p className="text-green-600 font-medium">Portfolio is well balanced!</p>
+ )}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="overflow-x-auto">
+ <table className="min-w-full divide-y divide-gray-200">
+ <thead className="bg-gray-50">
+ <tr>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Asset Type
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Value
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Current %
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Target %
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Deviation
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Status
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Actions
+ </th>
+ </tr>
+ </thead>
+ <tbody className="bg-white divide-y divide-gray-200">
+ {allocation.map((item) => {
+ const status = getAllocationStatus(item.percentage, item.targetPercentage);
+ return (
+ <tr key={item.assetType} className="hover:bg-gray-50">
+ <td className="px-6 py-4 whitespace-nowrap">
+ <div className="flex items-center space-x-2">
+ <span className="text-lg">{getAssetTypeIcon(item.assetType)}</span>
+ <span className="font-medium text-gray-900 capitalize">{item.assetType}</span>
+ </div>
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
+ {formatCurrency(item.value)}
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap">
+ <span className="text-sm font-medium text-gray-900">
+ {formatPercentage(item.percentage)}
+ </span>
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap">
+ <span className="text-sm text-gray-600">
+ {formatPercentage(item.targetPercentage)}
+ </span>
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap">
+ <span className={`text-sm font-medium ${
+ item.deviation > 0 ? 'text-red-600' : item.deviation < 0 ? 'text-green-600' : 'text-gray-600'
+ }`}>
+ {formatPercentage(item.deviation)}
+ </span>
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap">
+ <span className={`px-2 py-1 text-xs font-medium rounded-full ${
+ status.color === 'text-green-600' ? 'bg-green-100 text-green-800' :
+ status.color === 'text-yellow-600' ? 'bg-yellow-100 text-yellow-800' :
+ 'bg-red-100 text-red-800'
+ }`}>
+ {status.status}
+ </span>
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
+ <button
+ onClick={() => setSelectedAssetType(
+ selectedAssetType === item.assetType ? null : item.assetType
+ )}
+ className="text-blue-600 hover:text-blue-900"
+ >
+ {selectedAssetType === item.assetType ? 'Hide' : 'Show'} Assets
+ </button>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ )}
+
+ {selectedAssetType && (
+ <div className="mt-6 p-4 bg-gray-50 rounded-lg">
+ <h3 className="text-lg font-semibold text-gray-900 mb-4">
+ {getAssetTypeIcon(selectedAssetType)} {selectedAssetType.charAt(0).toUpperCase() + selectedAssetType.slice(1)} Assets
+ </h3>
+ <div className="overflow-x-auto">
+ <table className="min-w-full divide-y divide-gray-200">
+ <thead className="bg-gray-50">
+ <tr>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Asset
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Quantity
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Avg Buy Price
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Current Price
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Total Value
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Return
+ </th>
+ </tr>
+ </thead>
+ <tbody className="bg-white divide-y divide-gray-200">
+ {allocation
+ .find(item => item.assetType === selectedAssetType)
+ ?.assets.map((asset: PortfolioAsset) => (
+ <tr key={asset.id} className="hover:bg-gray-50">
+ <td className="px-6 py-4 whitespace-nowrap font-medium text-gray-900">
+ {asset.symbol}
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
+ {asset.quantity.toLocaleString()}
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
+ {formatCurrency(asset.averageBuyPrice)}
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
+ {formatCurrency(asset.currentPrice)}
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
+ {formatCurrency(asset.totalValue)}
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap">
+ <span className={`text-sm font-medium ${
+ asset.returnPercentage >= 0 ? 'text-green-600' : 'text-red-600'
+ }`}>
+ {formatPercentage(asset.returnPercentage)}
+ </span>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ )}
+
+ <div className="mt-6 p-4 bg-blue-50 rounded-lg">
+ <h3 className="text-sm font-medium text-blue-900 mb-3">Allocation Insights</h3>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-blue-800">
+ <div>
+ <p className="font-medium">Diversification Score:</p>
+ <p>
+ {allocation.length >= 5 ? 'Excellent' : allocation.length >= 3 ? 'Good' : 'Limited'}
+ {' '}diversification across {allocation.length} energy types
+ </p>
+ </div>
+ <div>
+ <p className="font-medium">Rebalancing Priority:</p>
+ <p>
+ {allocation.filter(item => Math.abs(item.deviation) > 5).length}
+ {' '}asset types require immediate attention
+ </p>
+ </div>
+ <div>
+ <p className="font-medium">Largest Allocation:</p>
+ <p>
+ {allocation.length > 0
+ ? `${allocation.sort((a, b) => b.value - a.value)[0].assetType} (${formatPercentage(allocation.sort((a, b) => b.value - a.value)[0].percentage)})`
+ : 'N/A'}
+ </p>
+ </div>
+ <div>
+ <p className="font-medium">Allocation Efficiency:</p>
+ <p>
+ {allocation.filter(item => Math.abs(item.deviation) <= 2).length / allocation.length >= 0.7
+ ? 'Well balanced'
+ : 'Needs optimization'}
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/components/portfolio/PerformanceMetrics.tsx b/components/portfolio/PerformanceMetrics.tsx
new file mode 100644
index 0000000..ec85340
--- /dev/null
+++ b/components/portfolio/PerformanceMetrics.tsx
@@ -0,0 +1,244 @@
+import React from 'react';
+import { PerformanceMetrics } from '../../types/portfolio';
+
+interface PerformanceMetricsProps {
+ metrics: PerformanceMetrics;
+ className?: string;
+}
+
+export const PerformanceMetrics: React.FC<PerformanceMetricsProps> = ({
+ metrics,
+ className = ''
+}) => {
+ const formatCurrency = (amount: number) => {
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 2
+ }).format(amount);
+ };
+
+ const formatPercentage = (value: number) => {
+ return `${value.toFixed(2)}%`;
+ };
+
+ const formatNumber = (value: number) => {
+ return new Intl.NumberFormat('en-US', {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ }).format(value);
+ };
+
+ const getMetricColor = (value: number, type: 'higher' | 'lower' = 'higher') => {
+ if (type === 'higher') {
+ return value > 0 ? 'text-green-600' : value < 0 ? 'text-red-600' : 'text-gray-600';
+ } else {
+ return value < 0 ? 'text-green-600' : value > 0 ? 'text-red-600' : 'text-gray-600';
+ }
+ };
+
+ const getQualityRating = (sharpeRatio: number) => {
+ if (sharpeRatio > 2) return { rating: 'Excellent', color: 'text-green-600', bg: 'bg-green-100' };
+ if (sharpeRatio > 1) return { rating: 'Good', color: 'text-blue-600', bg: 'bg-blue-100' };
+ if (sharpeRatio > 0.5) return { rating: 'Fair', color: 'text-yellow-600', bg: 'bg-yellow-100' };
+ return { rating: 'Poor', color: 'text-red-600', bg: 'bg-red-100' };
+ };
+
+ const qualityRating = getQualityRating(metrics.sharpeRatio);
+
+ return (
+ <div className={`bg-white rounded-lg shadow-lg p-6 ${className}`}>
+ <div className="flex justify-between items-center mb-6">
+ <h2 className="text-2xl font-bold text-gray-900">Performance Metrics</h2>
+ <div className={`px-3 py-1 rounded-full ${qualityRating.bg}`}>
+ <span className={`text-sm font-medium ${qualityRating.color}`}>
+ {qualityRating.rating}
+ </span>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
+ <div className="bg-gray-50 rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-600 mb-2">Returns</h3>
+ <div className="space-y-3">
+ <div>
+ <p className="text-xs text-gray-500">Total Return</p>
+ <p className={`text-lg font-bold ${getMetricColor(metrics.totalReturn)}`}>
+ {formatCurrency(metrics.totalReturn)}
+ </p>
+ <p className={`text-sm ${getMetricColor(metrics.totalReturnPercentage)}`}>
+ {formatPercentage(metrics.totalReturnPercentage)}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Annualized Return</p>
+ <p className={`text-lg font-bold ${getMetricColor(metrics.annualizedReturn)}`}>
+ {formatPercentage(metrics.annualizedReturn * 100)}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="bg-gray-50 rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-600 mb-2">Risk Metrics</h3>
+ <div className="space-y-3">
+ <div>
+ <p className="text-xs text-gray-500">Sharpe Ratio</p>
+ <p className="text-lg font-bold text-gray-900">
+ {formatNumber(metrics.sharpeRatio)}
+ </p>
+ <p className="text-xs text-gray-500">Risk-adjusted return</p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Volatility</p>
+ <p className={`text-lg font-bold ${getMetricColor(metrics.volatility, 'lower')}`}>
+ {formatPercentage(metrics.volatility)}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Max Drawdown</p>
+ <p className={`text-lg font-bold ${getMetricColor(metrics.maxDrawdown, 'lower')}`}>
+ {formatPercentage(metrics.maxDrawdown)}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="bg-gray-50 rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-600 mb-2">Market Comparison</h3>
+ <div className="space-y-3">
+ <div>
+ <p className="text-xs text-gray-500">Beta</p>
+ <p className="text-lg font-bold text-gray-900">
+ {formatNumber(metrics.beta)}
+ </p>
+ <p className="text-xs text-gray-500">Market sensitivity</p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Alpha</p>
+ <p className={`text-lg font-bold ${getMetricColor(metrics.alpha)}`}>
+ {formatPercentage(metrics.alpha)}
+ </p>
+ <p className="text-xs text-gray-500">Excess return</p>
+ </div>
+ </div>
+ </div>
+
+ <div className="bg-gray-50 rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-600 mb-2">Trading Statistics</h3>
+ <div className="space-y-3">
+ <div>
+ <p className="text-xs text-gray-500">Total Trades</p>
+ <p className="text-lg font-bold text-gray-900">
+ {metrics.totalTrades}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Win Rate</p>
+ <p className={`text-lg font-bold ${getMetricColor(metrics.winRate)}`}>
+ {formatPercentage(metrics.winRate)}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Profit Factor</p>
+ <p className={`text-lg font-bold ${getMetricColor(metrics.profitFactor - 1)}`}>
+ {formatNumber(metrics.profitFactor)}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="bg-gray-50 rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-600 mb-2">Trade Performance</h3>
+ <div className="space-y-3">
+ <div>
+ <p className="text-xs text-gray-500">Average Win</p>
+ <p className="text-lg font-bold text-green-600">
+ {formatCurrency(metrics.averageWin)}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Average Loss</p>
+ <p className="text-lg font-bold text-red-600">
+ {formatCurrency(metrics.averageLoss)}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Win/Loss Ratio</p>
+ <p className="text-lg font-bold text-gray-900">
+ {metrics.averageLoss > 0 ? formatNumber(metrics.averageWin / metrics.averageLoss) : '∞'}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="bg-gray-50 rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-600 mb-2">Extreme Trades</h3>
+ <div className="space-y-3">
+ <div>
+ <p className="text-xs text-gray-500">Largest Win</p>
+ <p className="text-lg font-bold text-green-600">
+ {formatCurrency(metrics.largestWin)}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Largest Loss</p>
+ <p className="text-lg font-bold text-red-600">
+ {formatCurrency(metrics.largestLoss)}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Winning Trades</p>
+ <p className="text-lg font-bold text-gray-900">
+ {metrics.winningTrades} / {metrics.totalTrades}
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="mt-6 p-4 bg-blue-50 rounded-lg">
+ <h3 className="text-sm font-medium text-blue-900 mb-2">Performance Insights</h3>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-blue-800">
+ <div>
+ <p className="font-medium">Risk-Adjusted Performance:</p>
+ <p>
+ {metrics.sharpeRatio > 1 ? 'Strong' : metrics.sharpeRatio > 0.5 ? 'Moderate' : 'Weak'}
+ {' '}risk-adjusted returns with Sharpe ratio of {formatNumber(metrics.sharpeRatio)}
+ </p>
+ </div>
+ <div>
+ <p className="font-medium">Trading Consistency:</p>
+ <p>
+ {metrics.winRate > 60 ? 'Excellent' : metrics.winRate > 40 ? 'Good' : 'Needs Improvement'}
+ {' '}win rate at {formatPercentage(metrics.winRate)}
+ </p>
+ </div>
+ <div>
+ <p className="font-medium">Volatility Profile:</p>
+ <p>
+ {metrics.volatility < 15 ? 'Low' : metrics.volatility < 25 ? 'Moderate' : 'High'}
+ {' '}volatility at {formatPercentage(metrics.volatility)}
+ </p>
+ </div>
+ <div>
+ <p className="font-medium">Drawdown Risk:</p>
+ <p>
+ {metrics.maxDrawdown < 10 ? 'Minimal' : metrics.maxDrawdown < 20 ? 'Moderate' : 'High'}
+ {' '}maximum drawdown of {formatPercentage(metrics.maxDrawdown)}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="mt-6 flex justify-end space-x-4">
+ <button className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
+ Export Metrics
+ </button>
+ <button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
+ View Detailed Report
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/components/portfolio/ProfitLoss.tsx b/components/portfolio/ProfitLoss.tsx
new file mode 100644
index 0000000..1338f7f
--- /dev/null
+++ b/components/portfolio/ProfitLoss.tsx
@@ -0,0 +1,355 @@
+import React, { useState } from 'react';
+import { ProfitLossData } from '../../types/portfolio';
+
+interface ProfitLossProps {
+ profitLoss: ProfitLossData;
+ className?: string;
+}
+
+export const ProfitLoss: React.FC<ProfitLossProps> = ({
+ profitLoss,
+ className = ''