-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3150 lines (2746 loc) · 133 KB
/
Copy pathscript.js
File metadata and controls
3150 lines (2746 loc) · 133 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
// Stock Exchange Mapping for correct TradingView symbols
const STOCK_EXCHANGE_MAPPING = {
"AAPL": "NASDAQ", "ABBV": "NYSE", "ABT": "NYSE", "ACN": "NYSE", "ADBE": "NASDAQ", "ADP": "NASDAQ", "AMD": "NASDAQ", "AMGN": "NYSE", "AMZN": "NASDAQ", "AON": "NYSE", "APD": "NYSE", "AVGO": "NASDAQ", "AXP": "NYSE", "BA": "NYSE", "BAC": "NYSE", "BLK": "NYSE", "BMY": "NYSE", "BRK.B": "NYSE", "C": "NYSE", "CAT": "NYSE", "CL": "NYSE", "CMCSA": "NASDAQ", "CME": "NYSE", "CMG": "NYSE", "CNC": "NYSE", "COF": "NYSE", "COP": "NYSE", "COST": "NASDAQ", "CRM": "NASDAQ", "CSCO": "NASDAQ", "CVS": "NYSE", "CVX": "NYSE", "DE": "NYSE", "DHR": "NYSE", "DIS": "NYSE", "DUK": "NYSE", "EMR": "NYSE", "EOG": "NYSE", "FDX": "NYSE", "GD": "NYSE", "GE": "NYSE", "GILD": "NASDAQ", "GOOGL": "NASDAQ", "GS": "NYSE", "HD": "NYSE", "HON": "NYSE", "IBM": "NYSE", "ICE": "NYSE", "INTC": "NASDAQ", "ISRG": "NASDAQ", "ITW": "NYSE", "JNJ": "NYSE", "JPM": "NYSE", "KO": "NYSE", "LIN": "NYSE", "LLY": "NYSE", "LOW": "NYSE", "MA": "NYSE", "MCD": "NYSE", "MCO": "NYSE", "MDLZ": "NASDAQ", "META": "NASDAQ", "MMC": "NYSE", "MMM": "NYSE", "MS": "NYSE", "MSFT": "NASDAQ", "NEE": "NYSE", "NFLX": "NASDAQ", "NKE": "NYSE", "NOW": "NASDAQ", "NSC": "NYSE", "NVDA": "NASDAQ", "ORCL": "NASDAQ", "PEP": "NYSE", "PFE": "NYSE", "PG": "NYSE", "PM": "NYSE", "PNC": "NYSE", "PYPL": "NASDAQ", "QCOM": "NASDAQ", "RTX": "NYSE", "SBUX": "NASDAQ", "SHW": "NYSE", "SLB": "NYSE", "SO": "NYSE", "SPGI": "NYSE", "T": "NYSE", "TFC": "NYSE", "TGT": "NYSE", "TJX": "NYSE", "TMO": "NYSE", "TSLA": "NASDAQ", "TXN": "NASDAQ", "UNH": "NYSE", "UNP": "NYSE", "UPS": "NYSE", "USB": "NYSE", "V": "NYSE", "VZ": "NYSE", "WFC": "NYSE", "WMT": "NYSE", "XOM": "NYSE"
};
// Helper function to create correct TradingView symbol
function createTradingViewSymbol(symbol) {
const exchange = STOCK_EXCHANGE_MAPPING[symbol] || 'NYSE';
return `${exchange}:${symbol}`;
}
class SP100CapexApp {
constructor() {
this.data = [];
this.filteredData = [];
this.insights = [];
this.displayedData = [];
this.itemsPerPage = 10;
this.currentPage = 1;
this.sortDirection = 'desc'; // 'desc' for descending (highest first), 'asc' for ascending (lowest first)
console.log('SP100CapexApp initialized with pagination:', this.itemsPerPage, 'items per page');
this.init();
}
async init() {
try {
await this.loadData();
this.setupEventListeners();
this.updateStats();
this.updateMarketStatus();
this.render();
console.log(`Pagination: Showing ${this.displayedData.length} of ${this.filteredData.length} companies`);
} catch (error) {
console.error('Error initializing app:', error);
this.showError();
}
}
async loadData() {
const capexResponse = await fetch('./data/financial_data.json');
if (!capexResponse.ok) {
throw new Error(`Failed to fetch capex data: ${capexResponse.status}`);
}
this.data = await capexResponse.json();
this.filteredData = [...this.data];
// Apply default sort by capex on initial load
this.sortData('capex');
// Ensure dropdown shows the correct default value
const sortDropdown = document.getElementById('sort-by');
if (sortDropdown) {
sortDropdown.value = 'capex';
}
this.updateDisplayedData();
// Try to get update timestamp, but don't fail if it's missing
try {
const updateResponse = await fetch('./data/last_updated.json');
if (updateResponse.ok) {
const updateInfo = await updateResponse.json();
this.updateLastUpdated(updateInfo.timestamp);
} else {
this.updateLastUpdated(new Date().toISOString());
}
} catch (updateError) {
console.warn('Could not load update timestamp:', updateError);
this.updateLastUpdated(new Date().toISOString());
}
// Generate insights from data
this.generateInsights();
}
setupEventListeners() {
const search = document.getElementById('search');
const sortBy = document.getElementById('sort-by');
const filterSector = document.getElementById('filter-sector');
const sortDirection = document.getElementById('sort-direction');
const ethAddress = document.getElementById('eth-address');
if (search) {
search.addEventListener('input', (e) => {
this.filterData();
});
}
if (sortBy) {
sortBy.addEventListener('change', (e) => {
this.sortData(e.target.value);
});
}
if (sortDirection) {
sortDirection.addEventListener('click', () => {
this.toggleSortDirection();
});
}
if (filterSector) {
filterSector.addEventListener('change', (e) => {
this.filterData();
});
}
if (ethAddress) {
ethAddress.addEventListener('click', () => {
navigator.clipboard.writeText(ethAddress.textContent);
});
}
}
filterData() {
const query = document.getElementById('search').value;
const sectorFilter = document.getElementById('filter-sector').value;
this.filteredData = this.data.filter(company => {
const matchesSearch = !query ||
company.name.toLowerCase().includes(query.toLowerCase()) ||
company.symbol.toLowerCase().includes(query.toLowerCase()) ||
company.sector.toLowerCase().includes(query.toLowerCase());
const matchesSector = !sectorFilter || company.sector === sectorFilter;
return matchesSearch && matchesSector;
});
// Reset pagination when filtering
this.currentPage = 1;
this.updateDisplayedData();
this.updateStats();
this.updateMarketStatus();
this.render();
}
toggleSortDirection() {
this.sortDirection = this.sortDirection === 'desc' ? 'asc' : 'desc';
// Update button UI
const btn = document.getElementById('sort-direction');
const icon = btn.querySelector('.sort-icon');
const label = btn.querySelector('.sort-label');
if (this.sortDirection === 'asc') {
btn.classList.add('ascending');
icon.textContent = '↑';
label.textContent = 'Lowest First';
} else {
btn.classList.remove('ascending');
icon.textContent = '↓';
label.textContent = 'Highest First';
}
// Re-sort with new direction
const sortBy = document.getElementById('sort-by')?.value || 'capex';
this.sortData(sortBy);
}
sortData(sortBy) {
const direction = this.sortDirection === 'desc' ? 1 : -1; // Multiplier for sort direction
this.filteredData.sort((a, b) => {
let comparison = 0;
switch (sortBy) {
case 'capex':
comparison = Math.abs(b.capex) - Math.abs(a.capex);
break;
case 'market_cap':
comparison = b.market_cap - a.market_cap;
break;
case 'name':
comparison = a.name.localeCompare(b.name);
// For name sorting, desc means Z-A, asc means A-Z
return comparison * -direction;
case 'sector':
comparison = a.sector.localeCompare(b.sector);
// For sector sorting, keep alphabetical regardless of direction
return comparison;
case 'revenue':
comparison = b.revenue - a.revenue;
break;
case 'earnings':
// Sort by earnings, handling missing values
const earningsA = a.earnings || 0;
const earningsB = b.earnings || 0;
comparison = earningsB - earningsA;
break;
default:
comparison = 0;
}
return comparison * direction;
});
// Reset pagination when sorting
this.currentPage = 1;
this.updateDisplayedData();
this.render();
}
updateDisplayedData() {
const startIndex = 0;
const endIndex = this.currentPage * this.itemsPerPage;
this.displayedData = this.filteredData.slice(startIndex, endIndex);
console.log(`updateDisplayedData: page=${this.currentPage}, itemsPerPage=${this.itemsPerPage}, showing ${startIndex}-${endIndex} of ${this.filteredData.length} companies`);
console.log(`Result: displayedData.length = ${this.displayedData.length}`);
}
loadMore() {
console.log('Load More clicked! Current page:', this.currentPage, '-> New page:', this.currentPage + 1);
this.currentPage++;
this.updateDisplayedData();
this.render();
}
// Debug method for manual testing
testPagination() {
console.log('=== PAGINATION TEST ===');
console.log('Total data:', this.data.length);
console.log('Filtered data:', this.filteredData.length);
console.log('Displayed data:', this.displayedData.length);
console.log('Current page:', this.currentPage);
console.log('Items per page:', this.itemsPerPage);
console.log('Should show Load More?', this.displayedData.length < this.filteredData.length);
console.log('=======================');
}
updateStats() {
const totalCompanies = this.filteredData.length;
const totalCapex = this.filteredData.reduce((sum, company) => sum + Math.abs(company.capex), 0);
const avgCapex = totalCompanies > 0 ? totalCapex / totalCompanies : 0;
document.getElementById('total-companies').textContent = totalCompanies;
document.getElementById('total-capex').textContent = this.formatCurrency(totalCapex);
document.getElementById('avg-capex').textContent = this.formatCurrency(avgCapex);
}
renderChart() {
const canvas = document.getElementById('capex-chart');
if (!canvas) {
console.error('Canvas element not found');
return;
}
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error('Canvas context not available');
return;
}
// Set canvas size
canvas.width = 900;
canvas.height = 500;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Get top 10 companies for chart
const top10 = this.filteredData.slice(0, 10);
if (top10.length === 0) {
ctx.fillStyle = '#666';
ctx.font = '16px Arial';
ctx.textAlign = 'center';
ctx.fillText('No data available', canvas.width / 2, canvas.height / 2);
return;
}
const maxCapex = Math.max(...top10.map(c => Math.abs(c.capex)));
const barHeight = 35;
const barSpacing = 5;
const chartWidth = canvas.width - 250;
const startY = 80;
// Draw title
ctx.fillStyle = '#333';
ctx.font = 'bold 24px Arial';
ctx.textAlign = 'center';
ctx.fillText('Top 10 Companies by CapEx', canvas.width / 2, 40);
// Draw bars
top10.forEach((company, index) => {
const barWidth = Math.max((Math.abs(company.capex) / maxCapex) * chartWidth, 5);
const y = startY + index * (barHeight + barSpacing);
// Draw bar background
ctx.fillStyle = '#f0f0f0';
ctx.fillRect(180, y, chartWidth, barHeight);
// Draw bar
ctx.fillStyle = '#2563eb';
ctx.fillRect(180, y, barWidth, barHeight);
// Draw company symbol
ctx.fillStyle = '#333';
ctx.font = 'bold 14px Arial';
ctx.textAlign = 'right';
ctx.fillText(company.symbol, 170, y + barHeight / 2 + 5);
// Draw value
ctx.fillStyle = '#fff';
ctx.font = 'bold 12px Arial';
ctx.textAlign = 'left';
if (barWidth > 100) {
ctx.fillText(this.formatCurrency(company.capex), 190, y + barHeight / 2 + 4);
} else {
ctx.fillStyle = '#333';
ctx.fillText(this.formatCurrency(company.capex), 190 + barWidth + 5, y + barHeight / 2 + 4);
}
});
}
formatCurrency(amount) {
const absAmount = Math.abs(amount);
if (absAmount >= 1e9) {
return `${(amount / 1e9).toFixed(1)}B`;
} else if (absAmount >= 1e6) {
return `${(amount / 1e6).toFixed(1)}M`;
} else if (absAmount >= 1e3) {
return `${(amount / 1e3).toFixed(1)}K`;
}
return `${amount.toLocaleString()}`;
}
getRatingClass(recommendation) {
const rec = recommendation.toLowerCase();
if (rec.includes('buy') || rec.includes('outperform') || rec.includes('overweight')) {
return 'rating-buy';
} else if (rec.includes('sell') || rec.includes('underperform') || rec.includes('underweight')) {
return 'rating-sell';
} else {
return 'rating-hold';
}
}
updateLastUpdated(timestamp) {
const date = new Date(timestamp);
document.getElementById('last-updated').textContent =
`Last updated: ${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
}
render() {
this.renderList();
this.renderLoadMoreButton();
}
renderList() {
const list = document.getElementById('company-list');
const loading = document.getElementById('loading');
loading.classList.add('hidden');
list.classList.remove('hidden');
// Check if sorting by sector to use grouped view
const sortBy = document.getElementById('sort-by')?.value;
if (sortBy === 'sector') {
console.log('Rendering grouped by sector - pagination disabled for this view');
this.renderGroupedBySector();
} else {
console.log(`Rendering list view: ${this.displayedData.length} companies`);
list.innerHTML = this.displayedData.map((company, index) => `
<div class="company-card">
<div class="card-header">
<div class="rank-number">#${index + 1}</div>
<div class="company-info">
<div class="company-name">${company.name}</div>
<div class="company-symbol">${company.symbol} • ${company.sector}</div>
</div>
</div>
<div class="card-body">
<div class="metrics-grid">
<div class="metric-group">
<div class="metric-label">💰 Revenue</div>
<div class="metric-value">${this.formatCurrency(company.revenue)}</div>
</div>
${company.earnings ? `
<div class="metric-group">
<div class="metric-label">💵 Earnings</div>
<div class="metric-value earnings">${this.formatCurrency(company.earnings)}</div>
</div>
` : ''}
${company.operating_income ? `
<div class="metric-group">
<div class="metric-label">⚙️ Operating Income</div>
<div class="metric-value">${this.formatCurrency(company.operating_income)}</div>
</div>
` : ''}
${company.free_cash_flow ? `
<div class="metric-group">
<div class="metric-label">💸 Free Cash Flow</div>
<div class="metric-value fcf">${this.formatCurrency(company.free_cash_flow)}</div>
</div>
` : ''}
<div class="metric-group">
<div class="metric-label">🏗️ CapEx</div>
<div class="metric-value capex">${this.formatCurrency(company.capex)}</div>
</div>
${company.total_assets ? `
<div class="metric-group">
<div class="metric-label">📊 Total Assets</div>
<div class="metric-value">${this.formatCurrency(company.total_assets)}</div>
</div>
` : ''}
${company.debt_to_equity !== undefined ? `
<div class="metric-group">
<div class="metric-label">📈 Debt/Equity</div>
<div class="metric-value ratio">${company.debt_to_equity}x</div>
</div>
` : ''}
${company.profit_margin !== undefined ? `
<div class="metric-group">
<div class="metric-label">📉 Profit Margin</div>
<div class="metric-value margin">${company.profit_margin}%</div>
</div>
` : ''}
<div class="metric-group market-cap-group">
<div class="metric-label">💎 Market Cap</div>
<div class="metric-value market-cap">${this.formatCurrency(company.market_cap)}</div>
</div>
</div>
${company.analyst_estimates ? `
<div class="analyst-forecasts">
<div class="forecast-header">📈 Analyst Forecasts</div>
<div class="forecast-grid">
${company.analyst_estimates.estimated_revenue ? `
<div class="forecast-item">
<div class="forecast-label">Revenue Est.</div>
<div class="forecast-value">${this.formatCurrency(company.analyst_estimates.estimated_revenue)}</div>
</div>
` : ''}
${company.analyst_estimates.estimated_eps ? `
<div class="forecast-item">
<div class="forecast-label">EPS Est.</div>
<div class="forecast-value">$${company.analyst_estimates.estimated_eps.toFixed(2)}</div>
</div>
` : ''}
${company.analyst_estimates.target_price ? `
<div class="forecast-item">
<div class="forecast-label">Price Target</div>
<div class="forecast-value">$${company.analyst_estimates.target_price.toFixed(2)}</div>
</div>
` : ''}
${company.analyst_estimates.recommendation ? `
<div class="forecast-item">
<div class="forecast-label">Rating</div>
<div class="forecast-value rating ${this.getRatingClass(company.analyst_estimates.recommendation)}">${company.analyst_estimates.recommendation}</div>
</div>
` : ''}
</div>
${company.analyst_estimates.number_of_analysts > 0 ? `
<div class="forecast-meta">${company.analyst_estimates.number_of_analysts} analysts</div>
` : ''}
</div>
` : ''}
<div class="card-meta">
<span class="data-year">${company.period || company.year + ' Annual'}</span>
<span class="data-source">📄 SEC EDGAR</span>
</div>
<div class="company-actions">
<button class="action-btn price-btn" onclick="openPriceModal('${company.symbol}', '${company.name.replace(/'/g, "\\'")}'); event.stopPropagation();" title="Live price chart">
📈 Price
</button>
<button class="action-btn news-btn" onclick="openDataModal('${company.symbol}', '${company.name.replace(/'/g, "\\'")}', 'news'); event.stopPropagation();" title="Latest news">
📰 News
</button>
<button class="action-btn filings-btn" onclick="openDataModal('${company.symbol}', '${company.name.replace(/'/g, "\\'")}', 'filings'); event.stopPropagation();" title="SEC filings">
📋 Filings
</button>
<button class="action-btn statements-btn" onclick="openDataModal('${company.symbol}', '${company.name.replace(/'/g, "\\'")}', 'statements'); event.stopPropagation();" title="Financial statements">
📊 Data
</button>
</div>
</div>
</div>
`).join('');
}
}
renderGroupedBySector() {
const list = document.getElementById('company-list');
// Group companies by sector
const sectors = {};
this.filteredData.forEach(company => {
if (!sectors[company.sector]) {
sectors[company.sector] = [];
}
sectors[company.sector].push(company);
});
// Sort sectors by total capex
const sortedSectors = Object.entries(sectors)
.map(([sector, companies]) => ({
sector,
companies: companies.sort((a, b) => Math.abs(b.capex) - Math.abs(a.capex)),
totalCapex: companies.reduce((sum, c) => sum + Math.abs(c.capex), 0),
count: companies.length
}))
.sort((a, b) => b.totalCapex - a.totalCapex);
list.innerHTML = sortedSectors.map(({sector, companies, totalCapex, count}) => `
<div class="sector-group">
<div class="sector-header" onclick="toggleSector('${sector.replace(/'/g, "\\'")}')">
<div class="sector-toggle">▼</div>
<div class="sector-info">
<div class="sector-name">${sector}</div>
<div class="sector-stats">${count} companies • Total: ${this.formatCurrency(totalCapex)}</div>
</div>
</div>
<div class="sector-companies" id="sector-${sector.replace(/[^a-zA-Z0-9]/g, '-')}">
${companies.map((company, index) => `
<div class="company-card sector-company">
<div class="card-header">
<div class="rank-number">#${index + 1}</div>
<div class="company-info">
<div class="company-name">${company.name}</div>
<div class="company-symbol">${company.symbol}</div>
</div>
</div>
<div class="card-body">
<div class="metrics-grid">
<div class="metric-group">
<div class="metric-label">💰 Revenue</div>
<div class="metric-value">${this.formatCurrency(company.revenue)}</div>
</div>
${company.earnings ? `
<div class="metric-group">
<div class="metric-label">💵 Earnings</div>
<div class="metric-value earnings">${this.formatCurrency(company.earnings)}</div>
</div>
` : ''}
${company.operating_income ? `
<div class="metric-group">
<div class="metric-label">⚙️ Operating Income</div>
<div class="metric-value">${this.formatCurrency(company.operating_income)}</div>
</div>
` : ''}
${company.free_cash_flow ? `
<div class="metric-group">
<div class="metric-label">💸 Free Cash Flow</div>
<div class="metric-value fcf">${this.formatCurrency(company.free_cash_flow)}</div>
</div>
` : ''}
<div class="metric-group">
<div class="metric-label">🏗️ CapEx</div>
<div class="metric-value capex">${this.formatCurrency(company.capex)}</div>
</div>
${company.total_assets ? `
<div class="metric-group">
<div class="metric-label">📊 Total Assets</div>
<div class="metric-value">${this.formatCurrency(company.total_assets)}</div>
</div>
` : ''}
${company.debt_to_equity !== undefined ? `
<div class="metric-group">
<div class="metric-label">📈 Debt/Equity</div>
<div class="metric-value ratio">${company.debt_to_equity}x</div>
</div>
` : ''}
${company.profit_margin !== undefined ? `
<div class="metric-group">
<div class="metric-label">📉 Profit Margin</div>
<div class="metric-value margin">${company.profit_margin}%</div>
</div>
` : ''}
<div class="metric-group market-cap-group">
<div class="metric-label">💎 Market Cap</div>
<div class="metric-value market-cap">${this.formatCurrency(company.market_cap)}</div>
</div>
</div>
<div class="card-meta">
<span class="data-year">${company.period || company.year + ' Annual'}</span>
<span class="data-source">📄 SEC EDGAR</span>
</div>
<div class="company-actions">
<button class="action-btn price-btn" onclick="openPriceModal('${company.symbol}', '${company.name.replace(/'/g, "\\'")}'); event.stopPropagation();" title="Live price chart">
📈 Price
</button>
<button class="action-btn news-btn" onclick="openDataModal('${company.symbol}', '${company.name.replace(/'/g, "\\'")}', 'news'); event.stopPropagation();" title="Latest news">
📰 News
</button>
<button class="action-btn filings-btn" onclick="openDataModal('${company.symbol}', '${company.name.replace(/'/g, "\\'")}', 'filings'); event.stopPropagation();" title="SEC filings">
📋 Filings
</button>
<button class="action-btn statements-btn" onclick="openDataModal('${company.symbol}', '${company.name.replace(/'/g, "\\'")}', 'statements'); event.stopPropagation();" title="Financial statements">
📊 Data
</button>
</div>
</div>
</div>
`).join('')}
</div>
</div>
`).join('');
}
renderLoadMoreButton() {
const sortBy = document.getElementById('sort-by')?.value;
const hasMoreData = this.displayedData.length < this.filteredData.length;
let existingButton = document.getElementById('load-more-btn');
console.log(`Render Load More: displayed=${this.displayedData.length}, total=${this.filteredData.length}, hasMore=${hasMoreData}, sortBy=${sortBy}`);
// Don't show load more button in sector grouped view
if (hasMoreData && sortBy !== 'sector') {
if (!existingButton) {
// Create button only if it doesn't exist
const button = document.createElement('div');
button.id = 'load-more-btn';
button.innerHTML = `
<button class="load-more-button" onclick="window.app.loadMore()">
Load More Companies (${this.displayedData.length} of ${this.filteredData.length})
</button>
`;
const companyList = document.getElementById('company-list');
companyList.parentNode.insertBefore(button, companyList.nextSibling);
console.log('Load More button added to DOM');
} else {
// Update existing button text instead of recreating
const buttonElement = existingButton.querySelector('.load-more-button');
if (buttonElement) {
buttonElement.textContent = `Load More Companies (${this.displayedData.length} of ${this.filteredData.length})`;
}
}
} else {
// Hide button instead of removing it to prevent DOM manipulation
if (existingButton) {
existingButton.style.display = 'none';
}
console.log('No Load More button needed - all data displayed');
}
// Show button if it was hidden
if (existingButton && hasMoreData && sortBy !== 'sector') {
existingButton.style.display = 'block';
}
}
// Market status functionality
updateMarketStatus() {
const marketStatusEl = document.getElementById('market-status');
if (!marketStatusEl) return;
const now = new Date();
// Get current time in Eastern timezone properly
const easternTime = new Date(now.toLocaleString("en-US", {timeZone: "America/New_York"}));
// Fix timezone conversion bug by using Intl.DateTimeFormat
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
hour: 'numeric',
minute: 'numeric',
hour12: false
});
const easternParts = formatter.formatToParts(now);
const hour = parseInt(easternParts.find(part => part.type === 'hour').value);
const minute = parseInt(easternParts.find(part => part.type === 'minute').value);
// Get day of week in Eastern timezone
const dayFormatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
weekday: 'short'
});
const dayName = dayFormatter.format(now);
const day = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(dayName);
const currentTime = hour * 60 + minute; // minutes since midnight
// Market hours: Monday-Friday 9:30 AM - 4:00 PM ET
const marketOpen = 9 * 60 + 30; // 9:30 AM
const marketClose = 16 * 60; // 4:00 PM
const isWeekday = day >= 1 && day <= 5;
const isDuringHours = currentTime >= marketOpen && currentTime < marketClose;
const isOpen = isWeekday && isDuringHours;
const statusText = isOpen ? '🟢 Markets Open' : '🔴 Markets Closed';
// Format Eastern time display properly
const timeText = now.toLocaleString('en-US', {
timeZone: 'America/New_York',
hour: 'numeric',
minute: '2-digit',
hour12: true,
timeZoneName: 'short'
});
const utcTime = now.toLocaleString('en-US', {
timeZone: 'UTC',
hour: 'numeric',
minute: '2-digit',
hour12: true,
timeZoneName: 'short'
});
marketStatusEl.innerHTML = `
<div class="market-status ${isOpen ? 'open' : 'closed'}">
<span class="status-indicator">${statusText}</span>
<span class="market-time">${timeText} (${utcTime})</span>
</div>
`;
}
generateInsights() {
// Calculate sector totals
const sectorTotals = {};
const sectorCounts = {};
this.data.forEach(company => {
const sector = company.sector;
const capex = Math.abs(company.capex);
if (!sectorTotals[sector]) {
sectorTotals[sector] = 0;
sectorCounts[sector] = 0;
}
sectorTotals[sector] += capex;
sectorCounts[sector]++;
});
// Top spenders
const topSpenders = [...this.data]
.sort((a, b) => Math.abs(b.capex) - Math.abs(a.capex))
.slice(0, 5);
// Top sectors by total capex
const topSectors = Object.entries(sectorTotals)
.sort(([,a], [,b]) => b - a)
.slice(0, 5);
// Efficiency analysis (capex/market cap ratio)
const efficiency = this.data
.filter(c => c.market_cap > 0)
.map(c => ({
...c,
efficiency: Math.abs(c.capex) / c.market_cap
}))
.sort((a, b) => b.efficiency - a.efficiency);
this.insights = {
topSpenders,
topSectors,
mostEfficient: efficiency.slice(0, 5),
leastEfficient: efficiency.slice(-5).reverse(),
totalCapex: this.data.reduce((sum, c) => sum + Math.abs(c.capex), 0),
avgCapex: this.data.reduce((sum, c) => sum + Math.abs(c.capex), 0) / this.data.length,
sectorAnalysis: Object.entries(sectorTotals).map(([sector, total]) => ({
sector,
total,
count: sectorCounts[sector],
average: total / sectorCounts[sector]
})).sort((a, b) => b.total - a.total)
};
}
renderInsights() {
const insightsContent = document.getElementById('insights-content');
insightsContent.innerHTML = `
<div class="insights-container">
<div class="insight-card">
<h3>🏭 Investment Leaders</h3>
<p>Technology companies dominate capital expenditure spending, representing the largest infrastructure investments in the S&P 100.</p>
<div class="insight-data">
${this.insights.topSpenders.map((company, index) => `
<div class="insight-item">
<span class="rank">#${index + 1}</span>
<span class="company">${company.symbol}</span>
<span class="value">${this.formatCurrency(company.capex)}</span>
</div>
`).join('')}
</div>
</div>
<div class="insight-card">
<h3>📊 Sector Analysis</h3>
<p>Combined capital expenditure by sector reveals where American corporations are placing their largest bets for future growth.</p>
<div class="insight-data">
${this.insights.topSectors.map(([sector, total]) => `
<div class="insight-item">
<span class="sector">${sector}</span>
<span class="value">${this.formatCurrency(total)}</span>
</div>
`).join('')}
</div>
</div>
<div class="insight-card">
<h3>⚡ Investment Intensity</h3>
<p>Companies with highest capex-to-market-cap ratios, indicating aggressive infrastructure investment relative to valuation.</p>
<div class="insight-data">
${this.insights.mostEfficient.map(company => `
<div class="insight-item">
<span class="company">${company.symbol}</span>
<span class="ratio">${(company.efficiency * 100).toFixed(1)}%</span>
<span class="value">${this.formatCurrency(company.capex)}</span>
</div>
`).join('')}
</div>
</div>
<div class="insight-card">
<h3>💡 Key Insights</h3>
<div class="key-insights">
<div class="insight-point">
<strong>AI Infrastructure Boom:</strong> Top tech companies (${this.insights.topSpenders.slice(0,4).map(c => c.symbol).join(', ')})
combined ${this.formatCurrency(this.insights.topSpenders.slice(0,4).reduce((sum, c) => sum + Math.abs(c.capex), 0))}
in capex, indicating massive AI/cloud infrastructure buildout.
</div>
<div class="insight-point">
<strong>Total Market Investment:</strong> S&P 100 companies invested
${this.formatCurrency(this.insights.totalCapex)} in capital expenditures,
averaging ${this.formatCurrency(this.insights.avgCapex)} per company.
</div>
<div class="insight-point">
<strong>Sector Concentration:</strong> Technology sector leads with
${this.formatCurrency(this.insights.sectorAnalysis[0].total)} total capex,
${((this.insights.sectorAnalysis[0].total / this.insights.totalCapex) * 100).toFixed(1)}% of all spending.
</div>
</div>
</div>
</div>
`;
}
async loadStockPrices() {
// Load prices for currently displayed companies only
const symbolsToLoad = this.displayedData.map(company => company.symbol);
console.log(`Loading stock prices for ${symbolsToLoad.length} companies...`);
// Process in batches to avoid overwhelming APIs
const batchSize = 5;
const batches = [];
for (let i = 0; i < symbolsToLoad.length; i += batchSize) {
batches.push(symbolsToLoad.slice(i, i + batchSize));
}
// Process batches with delay between them
for (let i = 0; i < batches.length; i++) {
const batch = batches[i];
console.log(`Processing batch ${i + 1}/${batches.length}: ${batch.join(', ')}`);
// Process batch in parallel
const promises = batch.map(symbol => this.loadSingleStockPrice(symbol));
await Promise.allSettled(promises);
// Batch delay removed for performance
}
console.log('Stock price loading completed');
}
async loadSingleStockPrice(symbol) {
const priceElement = document.getElementById(`price-${symbol}`);
if (!priceElement) return;
try {
let price = null;
// Use secure server-side API first
price = await this.fetchFromSecureAPI(symbol);
// Fallback to demo data if API fails
if (!price) {
price = await this.getRealisticDemoPrice(symbol);
if (price) {
price.source = 'Demo Data';
}
}
if (price) {
const changePercent = price.changePercent || 0;
const changeClass = changePercent >= 0 ? 'positive' : 'negative';
const changeSymbol = changePercent >= 0 ? '+' : '';
priceElement.innerHTML = `
<span class="current-price">$${price.price.toFixed(2)}</span>
<span class="price-change ${changeClass}">${changeSymbol}${changePercent.toFixed(2)}%</span>
<span class="price-source">${price.source}</span>
`;
priceElement.className = `stock-price ${changeClass}`;
// Log successful fetch for monitoring
console.log(`✓ ${symbol}: $${price.price.toFixed(2)} (${price.source})`);
} else {
priceElement.innerHTML = '<span class="price-unavailable">Price unavailable</span>';
priceElement.className = 'stock-price unavailable';
console.warn(`✗ ${symbol}: All APIs failed`);
}
} catch (error) {
console.warn(`Failed to load price for ${symbol}:`, error);
priceElement.innerHTML = '<span class="price-unavailable">Price unavailable</span>';
priceElement.className = 'stock-price unavailable';
}
}
async fetchFromGoogleFinance(symbol) {
try {
// Google Finance API endpoint
const url = `https://www.google.com/finance/quote/${symbol}:NASDAQ`;
const proxyUrl = `https://corsproxy.io/?${encodeURIComponent(url)}`;
const response = await fetch(proxyUrl);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const htmlText = await response.text();
// Parse HTML to extract price data
const priceMatch = htmlText.match(/data-last-price="([^"]+)"/);
const changeMatch = htmlText.match(/data-last-change="([^"]+)"/);
if (priceMatch && priceMatch[1]) {
const currentPrice = parseFloat(priceMatch[1]);
const priceChange = changeMatch ? parseFloat(changeMatch[1]) : 0;
const changePercent = currentPrice > 0 ? (priceChange / (currentPrice - priceChange)) * 100 : 0;
if (currentPrice > 0) {
return {
price: currentPrice,
changePercent: changePercent,
source: 'Google Finance'
};
}
}
} catch (error) {
console.warn(`Google Finance failed for ${symbol}:`, error);
}
return null;
}
async fetchFromSecureAPI(symbol) {
try {
// Use our secure server-side API
const response = await fetch(`/api/stock-price?symbol=${symbol}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
if (data && data.price) {
return {
price: data.price,
changePercent: data.changePercent || 0,
source: data.source || 'Live Data'
};
}
} catch (error) {
console.warn(`Secure API failed for ${symbol}:`, error);
}
return null;
}
async fetchFromSimpleYahoo(symbol) {
try {
// Use CORS proxy for Yahoo Finance
const url = `https://query1.finance.yahoo.com/v8/finance/chart/${symbol}?interval=1d&range=1d`;
const proxyUrl = `https://corsproxy.io/?${encodeURIComponent(url)}`;
const response = await fetch(proxyUrl);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const result = data.chart?.result?.[0];
if (result && result.meta) {
const currentPrice = result.meta.regularMarketPrice;
const previousClose = result.meta.previousClose;
if (currentPrice && previousClose) {
const changePercent = ((currentPrice - previousClose) / previousClose) * 100;