File size: 35,589 Bytes
be36f95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Indian Stock Analyzer</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #4f46e5 0%, #10b981 100%);
        }
        .stock-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        .chart-container {
            height: 300px;
            position: relative;
        }
        .pulse {
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% {
                transform: scale(0.95);
                box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.7);
            }
            70% {
                transform: scale(1);
                box-shadow: 0 0 0 10px rgba(79, 70, 229, 0);
            }
            100% {
                transform: scale(0.95);
                box-shadow: 0 0 0 0 rgba(79, 70, 229, 0);
            }
        }
        #stockInput {
            min-height: 100px;
        }
        .blink {
            animation: blink 1s step-start infinite;
        }
        @keyframes blink {
            50% { opacity: 0; }
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Header -->
    <header class="gradient-bg text-white">
        <div class="container mx-auto px-4 py-8">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-3xl font-bold">Indian Stock Analyzer</h1>
                    <p class="mt-2 opacity-90">Real-time analysis of Indian stocks</p>
                </div>
                <div class="flex items-center space-x-4">
                    <div id="lastUpdated" class="text-sm bg-white/20 px-3 py-1 rounded-full hidden">
                        <i class="fas fa-clock mr-1"></i> <span>Updated: <span id="updateTime">Just now</span></span>
                    </div>
                    <button class="bg-white text-indigo-600 px-4 py-2 rounded-lg font-medium hover:bg-gray-100 transition">
                        <i class="fas fa-user mr-2"></i>Login
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="container mx-auto px-4 py-8">
        <!-- Input Section -->
        <section class="mb-12">
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h2 class="text-2xl font-semibold text-gray-800 mb-4">Analyze Your Stocks</h2>
                <div class="flex flex-col md:flex-row gap-4">
                    <div class="flex-1">
                        <label for="stockInput" class="block text-sm font-medium text-gray-700 mb-2">Enter Stock Symbols (one per line or comma separated)</label>
                        <div class="flex flex-col">
                            <textarea id="stockInput" placeholder="Enter stock symbols, one per line or comma separated
e.g. 
RELIANCE.NS
TCS.NS
HDFCBANK.NS

or 

RELIANCE.NS, TCS.NS, HDFCBANK.NS" 
                                   class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"></textarea>
                            <div class="flex items-center mt-2">
                                <button id="analyzeBtn" class="bg-indigo-600 text-white px-6 py-3 rounded-lg hover:bg-indigo-700 transition flex items-center justify-center">
                                    <i class="fas fa-chart-line mr-2"></i> Analyze
                                </button>
                                <div id="apiStatus" class="ml-4 flex items-center text-sm hidden">
                                    <span class="w-2 h-2 rounded-full mr-2 bg-green-500"></span>
                                    <span>API Connected</span>
                                </div>
                            </div>
                        </div>
                        <p class="mt-2 text-sm text-gray-500">Use NSE symbols with .NS suffix (e.g., RELIANCE.NS)</p>
                    </div>
                    <div class="md:w-64">
                        <label for="timeFrame" class="block text-sm font-medium text-gray-700 mb-2">Time Frame</label>
                        <select id="timeFrame" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                            <option value="TIME_SERIES_INTRADAY">Today</option>
                            <option value="TIME_SERIES_DAILY" selected>Daily</option>
                            <option value="TIME_SERIES_WEEKLY">Weekly</option>
                            <option value="TIME_SERIES_MONTHLY">Monthly</option>
                        </select>
                        <div class="mt-4">
                            <label class="inline-flex items-center">
                                <input type="checkbox" id="autoRefresh" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-offset-0 focus:ring-indigo-200 focus:ring-opacity-50">
                                <span class="ml-2 text-sm text-gray-700">Auto-refresh (30s)</span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Results Section (Initially hidden) -->
        <section id="resultsSection" class="hidden">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-semibold text-gray-800">Analysis Results</h2>
                <div class="flex space-x-2">
                    <button id="exportBtn" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition flex items-center">
                        <i class="fas fa-file-export mr-2"></i> Export
                    </button>
                    <button id="refreshBtn" class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition flex items-center">
                        <i class="fas fa-sync-alt mr-2"></i> Refresh
                    </button>
                </div>
            </div>

            <!-- Summary Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div class="bg-white rounded-xl shadow-md p-6 flex items-center stock-card transition">
                    <div class="bg-indigo-100 p-3 rounded-full mr-4">
                        <i class="fas fa-rupee-sign text-indigo-600 text-xl"></i>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Total Value</p>
                        <h3 class="text-2xl font-bold text-gray-800" id="totalValue">Loading...</h3>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6 flex items-center stock-card transition">
                    <div class="bg-green-100 p-3 rounded-full mr-4">
                        <i class="fas fa-arrow-up text-green-600 text-xl"></i>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Best Performer</p>
                        <h3 class="text-2xl font-bold text-gray-800" id="bestPerformer">Loading...</h3>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6 flex items-center stock-card transition">
                    <div class="bg-red-100 p-3 rounded-full mr-4">
                        <i class="fas fa-arrow-down text-red-600 text-xl"></i>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Worst Performer</p>
                        <h3 class="text-2xl font-bold text-gray-800" id="worstPerformer">Loading...</h3>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6 flex items-center stock-card transition">
                    <div class="bg-blue-100 p-3 rounded-full mr-4">
                        <i class="fas fa-percentage text-blue-600 text-xl"></i>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Avg Return</p>
                        <h3 class="text-2xl font-bold text-gray-800" id="avgReturn">Loading...</h3>
                    </div>
                </div>
            </div>

            <!-- Stock Performance Chart -->
            <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">Performance Comparison</h3>
                    <div class="flex space-x-2">
                        <button class="px-3 py-1 text-sm bg-indigo-100 text-indigo-700 rounded-lg">1D</button>
                        <button class="px-3 py-1 text-sm bg-indigo-600 text-white rounded-lg">1W</button>
                        <button class="px-3 py-1 text-sm bg-indigo-100 text-indigo-700 rounded-lg">1M</button>
                    </div>
                </div>
                <div class="chart-container">
                    <canvas id="performanceChart"></canvas>
                </div>
            </div>

            <!-- Individual Stock Cards -->
            <div id="stockCardsContainer" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- Stock cards will be dynamically inserted here -->
            </div>
        </section>

        <!-- Loading State (Initially hidden) -->
        <section id="loadingSection" class="hidden">
            <div class="bg-white rounded-xl shadow-lg p-12 text-center">
                <div class="inline-block p-6 bg-indigo-100 rounded-full mb-6 pulse">
                    <i class="fas fa-chart-pie text-indigo-600 text-4xl"></i>
                </div>
                <h3 class="text-xl font-semibold text-gray-800 mb-2">Fetching Stock Data</h3>
                <p class="text-gray-500 mb-6">Connecting to market data sources...</p>
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div id="progressBar" class="bg-indigo-600 h-2.5 rounded-full" style="width: 0%"></div>
                </div>
                <p id="fetchingSymbol" class="text-sm text-gray-500 mt-4"></p>
            </div>
        </section>

        <!-- Error State (Initially hidden) -->
        <section id="errorSection" class="hidden">
            <div class="bg-red-50 border-l-4 border-red-400 p-4 rounded-lg">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-circle h-5 w-5 text-red-400"></i>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-red-800" id="errorTitle">Error</h3>
                        <div class="mt-2 text-sm text-red-700" id="errorMessage">
                            <p>There was an error fetching stock data. Please try again.</p>
                        </div>
                        <div class="mt-4">
                            <button id="retryBtn" class="bg-red-100 text-red-800 px-3 py-1 rounded-md text-sm font-medium hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                                Retry
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- Footer -->
    <footer class="bg-gray-800 text-white py-8">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
                <div>
                    <h3 class="text-lg font-semibold mb-4">Indian Stock Analyzer</h3>
                    <p class="text-gray-400">Real-time analysis of Indian stocks using market data.</p>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">Popular Stocks</h3>
                    <ul class="space-y-2">
                        <li><a href="#" class="text-gray-400 hover:text-white transition">RELIANCE.NS</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition">TCS.NS</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition">HDFCBANK.NS</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition">INFY.NS</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">Resources</h3>
                    <ul class="space-y-2">
                        <li><a href="#" class="text-gray-400 hover:text-white transition">NSE India</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition">BSE India</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition">Market News</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition">API Docs</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">Connect With Us</h3>
                    <div class="flex space-x-4 mb-4">
                        <a href="#" class="bg-gray-700 p-2 rounded-full hover:bg-indigo-600 transition"><i class="fab fa-twitter"></i></a>
                        <a href="#" class="bg-gray-700 p-2 rounded-full hover:bg-indigo-600 transition"><i class="fab fa-linkedin-in"></i></a>
                        <a href="#" class="bg-gray-700 p-2 rounded-full hover:bg-indigo-600 transition"><i class="fab fa-facebook-f"></i></a>
                    </div>
                    <p class="text-gray-400">Data provided by Alpha Vantage</p>
                </div>
            </div>
            <div class="border-t border-gray-700 mt-8 pt-6 text-center text-gray-400">
                <p>© 2023 Indian Stock Analyzer. All rights reserved.</p>
            </div>
        </div>
    </footer>

    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <script>
        // API Configuration
        const API_KEY = 'YOUR_ALPHA_VANTAGE_API_KEY'; // Replace with your Alpha Vantage API key
        const BASE_URL = 'https://www.alphavantage.co/query';
        
        // DOM Elements
        const analyzeBtn = document.getElementById('analyzeBtn');
        const stockInput = document.getElementById('stockInput');
        const resultsSection = document.getElementById('resultsSection');
        const loadingSection = document.getElementById('loadingSection');
        const errorSection = document.getElementById('errorSection');
        const stockCardsContainer = document.getElementById('stockCardsContainer');
        const progressBar = document.getElementById('progressBar');
        const totalValue = document.getElementById('totalValue');
        const bestPerformer = document.getElementById('bestPerformer');
        const worstPerformer = document.getElementById('worstPerformer');
        const avgReturn = document.getElementById('avgReturn');
        const exportBtn = document.getElementById('exportBtn');
        const refreshBtn = document.getElementById('refreshBtn');
        const retryBtn = document.getElementById('retryBtn');
        const timeFrame = document.getElementById('timeFrame');
        const autoRefresh = document.getElementById('autoRefresh');
        const lastUpdated = document.getElementById('lastUpdated');
        const updateTime = document.getElementById('updateTime');
        const apiStatus = document.getElementById('apiStatus');
        const fetchingSymbol = document.getElementById('fetchingSymbol');
        const errorTitle = document.getElementById('errorTitle');
        const errorMessage = document.getElementById('errorMessage');

        // Initialize chart
        let performanceChart;
        let autoRefreshInterval;
        let currentStocks = [];

        // Event Listeners
        analyzeBtn.addEventListener('click', analyzeStocks);
        exportBtn.addEventListener('click', exportData);
        refreshBtn.addEventListener('click', analyzeStocks);
        retryBtn.addEventListener('click', analyzeStocks);
        autoRefresh.addEventListener('change', toggleAutoRefresh);

        // Toggle auto-refresh
        function toggleAutoRefresh() {
            if (autoRefresh.checked) {
                autoRefreshInterval = setInterval(analyzeStocks, 30000); // 30 seconds
            } else {
                clearInterval(autoRefreshInterval);
            }
        }

        // Format date
        function formatDate(date) {
            const options = { 
                year: 'numeric', 
                month: 'short', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            };
            return new Date(date).toLocaleString('en-IN', options);
        }

        // Show last updated time
        function showLastUpdated() {
            lastUpdated.classList.remove('hidden');
            updateTime.textContent = formatDate(new Date());
        }

        // Show API status
        function showApiStatus(connected) {
            apiStatus.classList.remove('hidden');
            const dot = apiStatus.querySelector('.w-2');
            const text = apiStatus.querySelector('span:last-child');
            
            if (connected) {
                dot.classList.remove('bg-red-500');
                dot.classList.add('bg-green-500');
                text.textContent = 'API Connected';
            } else {
                dot.classList.remove('bg-green-500');
                dot.classList.add('bg-red-500');
                text.textContent = 'API Disconnected';
            }
        }

        // Analyze Stocks Function
        async function analyzeStocks() {
            const inputValue = stockInput.value.trim();
            if (!inputValue) {
                showError('Input Error', 'Please enter at least one stock symbol');
                return;
            }

            // Show loading state
            loadingSection.classList.remove('hidden');
            resultsSection.classList.add('hidden');
            errorSection.classList.add('hidden');
            
            // Process input - accept both comma separated and one per line
            let symbols = [];
            if (inputValue.includes(',')) {
                symbols = inputValue.split(',').map(s => s.trim().toUpperCase());
            } else {
                symbols = inputValue.split('\n').map(s => s.trim().toUpperCase()).filter(s => s.length > 0);
            }

            // Remove duplicates
            symbols = [...new Set(symbols)];

            // Check if symbols have .NS suffix (NSE)
            symbols = symbols.map(symbol => {
                if (!symbol.endsWith('.NS') && !symbol.endsWith('.BO')) {
                    return symbol + '.NS'; // Default to NSE if no exchange specified
                }
                return symbol;
            });

            try {
                // Show API status
                showApiStatus(true);
                
                // Fetch data for each symbol
                const stocks = [];
                let progress = 0;
                
                for (const symbol of symbols) {
                    fetchingSymbol.textContent = `Fetching data for ${symbol}...`;
                    progress += 100 / symbols.length;
                    progressBar.style.width = `${progress}%`;
                    
                    const stockData = await fetchStockData(symbol);
                    if (stockData) {
                        stocks.push(stockData);
                    }
                }
                
                if (stocks.length === 0) {
                    throw new Error('No valid stock data received');
                }
                
                currentStocks = stocks;
                
                // Hide loading and show results
                loadingSection.classList.add('hidden');
                resultsSection.classList.remove('hidden');
                
                // Update summary
                updateSummary(stocks);

                // Render stock cards
                renderStockCards(stocks);

                // Render performance chart
                renderPerformanceChart(stocks);
                
                // Show last updated time
                showLastUpdated();
                
            } catch (error) {
                console.error('Error fetching stock data:', error);
                showError('API Error', error.message || 'Failed to fetch stock data. Please try again.');
                showApiStatus(false);
            }
        }

        // Fetch Stock Data from Alpha Vantage
        async function fetchStockData(symbol) {
            try {
                const functionType = timeFrame.value;
                let url = `${BASE_URL}?function=${functionType}&symbol=${symbol}&apikey=${API_KEY}`;
                
                if (functionType === 'TIME_SERIES_INTRADAY') {
                    url += '&interval=5min';
                }
                
                const response = await fetch(url);
                const data = await response.json();
                
                if (data['Error Message']) {
                    throw new Error(data['Error Message']);
                }
                
                if (data['Note']) {
                    throw new Error('API rate limit exceeded. Please wait a minute and try again.');
                }
                
                // Parse the data based on the function type
                let timeSeries, metaData;
                
                if (functionType === 'TIME_SERIES_INTRADAY') {
                    timeSeries = data['Time Series (5min)'];
                    metaData = data['Meta Data'];
                } else if (functionType === 'TIME_SERIES_DAILY') {
                    timeSeries = data['Time Series (Daily)'];
                    metaData = data['Meta Data'];
                } else if (functionType === 'TIME_SERIES_WEEKLY') {
                    timeSeries = data['Weekly Time Series'];
                    metaData = data['Meta Data'];
                } else if (functionType === 'TIME_SERIES_MONTHLY') {
                    timeSeries = data['Monthly Time Series'];
                    metaData = data['Meta Data'];
                }
                
                if (!timeSeries || !metaData) {
                    throw new Error('Invalid data format received from API');
                }
                
                // Get the latest data point
                const dates = Object.keys(timeSeries).sort((a, b) => new Date(b) - new Date(a));
                const latestDate = dates[0];
                const latestData = timeSeries[latestDate];
                
                // Get previous close date
                const prevDate = dates[1];
                const prevData = timeSeries[prevDate];
                
                // Calculate percentage change
                const latestClose = parseFloat(latestData['4. close']);
                const prevClose = parseFloat(prevData['4. close']);
                const changePercent = ((latestClose - prevClose) / prevClose) * 100;
                
                // Get last 7 data points for chart
                const chartData = [];
                const chartLabels = [];
                
                for (let i = 0; i < Math.min(7, dates.length); i++) {
                    const date = dates[i];
                    const dataPoint = timeSeries[date];
                    chartData.push(parseFloat(dataPoint['4. close']));
                    chartLabels.push(new Date(date).toLocaleDateString('en-IN', { month: 'short', day: 'numeric' }));
                }
                
                // Reverse to show chronological order
                chartData.reverse();
                chartLabels.reverse();
                
                return {
                    symbol: symbol,
                    name: metaData['2. Symbol'].replace('.NS', ''),
                    price: latestClose,
                    change: changePercent.toFixed(2),
                    open: parseFloat(latestData['1. open']),
                    high: parseFloat(latestData['2. high']),
                    low: parseFloat(latestData['3. low']),
                    volume: formatVolume(parseInt(latestData['5. volume'])),
                    chartData: chartData,
                    chartLabels: chartLabels,
                    lastUpdated: metaData['3. Last Refreshed']
                };
                
            } catch (error) {
                console.error(`Error fetching data for ${symbol}:`, error);
                return null;
            }
        }

        // Format volume for display
        function formatVolume(volume) {
            if (volume >= 10000000) {
                return (volume / 10000000).toFixed(1) + 'Cr';
            } else if (volume >= 100000) {
                return (volume / 100000).toFixed(1) + 'L';
            } else if (volume >= 1000) {
                return (volume / 1000).toFixed(1) + 'K';
            }
            return volume.toString();
        }

        // Show Error Function
        function showError(title, message) {
            errorTitle.textContent = title;
            errorMessage.innerHTML = `<p>${message}</p>`;
            
            loadingSection.classList.add('hidden');
            resultsSection.classList.add('hidden');
            errorSection.classList.remove('hidden');
        }

        // Update Summary Function
        function updateSummary(stocks) {
            // Calculate total value (sample calculation)
            const total = stocks.reduce((sum, stock) => sum + stock.price * 1000, 0);
            totalValue.textContent = `₹${(total / 1000).toFixed(2)}K`;

            // Find best and worst performers
            const sortedByPerformance = [...stocks].sort((a, b) => b.change - a.change);
            bestPerformer.textContent = `${sortedByPerformance[0].symbol} (+${sortedByPerformance[0].change}%)`;
            worstPerformer.textContent = `${sortedByPerformance[sortedByPerformance.length - 1].symbol} (${sortedByPerformance[sortedByPerformance.length - 1].change}%)`;

            // Calculate average return
            const avg = stocks.reduce((sum, stock) => sum + parseFloat(stock.change), 0) / stocks.length;
            avgReturn.textContent = `${avg >= 0 ? '+' : ''}${avg.toFixed(2)}%`;
        }

        // Render Stock Cards Function
        function renderStockCards(stocks) {
            stockCardsContainer.innerHTML = '';
            
            stocks.forEach(stock => {
                const card = document.createElement('div');
                card.className = 'bg-white rounded-xl shadow-md p-6 stock-card transition';
                card.innerHTML = `
                    <div class="flex justify-between items-start mb-4">
                        <div>
                            <h3 class="text-xl font-bold text-gray-800">${stock.name}</h3>
                            <p class="text-gray-500">${stock.symbol}</p>
                        </div>
                        <span class="px-3 py-1 rounded-full text-sm font-medium ${stock.change >= 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
                            ${stock.change >= 0 ? '+' : ''}${stock.change}%
                        </span>
                    </div>
                    <div class="mb-4">
                        <p class="text-2xl font-bold text-gray-800 mb-1">₹${stock.price.toFixed(2)}</p>
                        <div class="flex justify-between text-sm text-gray-500">
                            <span>Open: ₹${stock.open.toFixed(2)}</span>
                            <span>High: ₹${stock.high.toFixed(2)}</span>
                        </div>
                        <div class="flex justify-between text-sm text-gray-500 mt-1">
                            <span>Low: ₹${stock.low.toFixed(2)}</span>
                            <span>Vol: ${stock.volume}</span>
                        </div>
                    </div>
                    <div class="h-24 mb-4">
                        <canvas class="stock-mini-chart" data-symbol="${stock.symbol}"></canvas>
                    </div>
                    <div class="text-xs text-gray-500 text-right">
                        Updated: ${stock.lastUpdated}
                    </div>
                    <div class="mt-4 pt-4 border-t border-gray-100">
                        <button class="w-full bg-indigo-600 text-white py-2 rounded-lg hover:bg-indigo-700 transition">
                            View Detailed Analysis
                        </button>
                    </div>
                `;
                stockCardsContainer.appendChild(card);
            });

            // Render mini charts for each stock
            setTimeout(() => {
                stocks.forEach(stock => {
                    const canvas = document.querySelector(`.stock-mini-chart[data-symbol="${stock.symbol}"]`);
                    if (canvas) {
                        renderMiniChart(canvas, stock.chartData, stock.chartLabels, stock.change >= 0 ? '#10B981' : '#EF4444');
                    }
                });
            }, 100);
        }

        // Render Mini Chart Function
        function renderMiniChart(canvas, data, labels, color) {
            new Chart(canvas, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        borderColor: color,
                        borderWidth: 2,
                        tension: 0.3,
                        fill: false,
                        pointRadius: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        x: {
                            display: false
                        },
                        y: {
                            display: false
                        }
                    }
                }
            });
        }

        // Render Performance Chart Function
        function renderPerformanceChart(stocks) {
            const ctx = document.getElementById('performanceChart').getContext('2d');
            
            if (performanceChart) {
                performanceChart.destroy();
            }

            // Prepare data for chart
            const colors = ['#4F46E5', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899'];
            
            const datasets = stocks.map((stock, index) => ({
                label: stock.symbol,
                data: stock.chartData,
                borderColor: colors[index % colors.length],
                backgroundColor: colors[index % colors.length] + '20',
                borderWidth: 2,
                tension: 0.3,
                fill: true
            }));

            performanceChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: stocks[0].chartLabels, // Use first stock's labels
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            callbacks: {
                                label: function(context) {
                                    return context.dataset.label + ': ₹' + context.parsed.y.toFixed(2);
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: false,
                            grid: {
                                drawBorder: false
                            },
                            ticks: {
                                callback: function(value) {
                                    return '₹' + value.toFixed(2);
                                }
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    }
                }
            });
        }

        // Export Data Function
        function exportData() {
            if (currentStocks.length === 0) {
                alert('No data to export');
                return;
            }
            
            // Create CSV content
            let csvContent = "Symbol,Name,Price,Change(%),Open,High,Low,Volume\n";
            
            currentStocks.forEach(stock => {
                csvContent += `${stock.symbol},${stock.name},${stock.price},${stock.change},${stock.open},${stock.high},${stock.low},${stock.volume}\n`;
            });
            
            // Create download link
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.setAttribute('href', url);
            link.setAttribute('download', `stock_data_${new Date().toISOString().slice(0,10)}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // Initialize with sample data on first load
        document.addEventListener('DOMContentLoaded', () => {
            stockInput.value = 'RELIANCE.NS\nTCS.NS\nHDFCBANK.NS';
            showApiStatus(false);
        });
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=Rickesh/stock-analysis" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>