File size: 35,745 Bytes
1297711
 
476a678
1297711
 
 
 
f09546b
1297711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c59784
1297711
 
 
 
 
f09546b
 
 
 
 
 
 
 
 
 
 
 
 
903b80e
f09546b
 
 
 
 
1297711
 
f09546b
1297711
f09546b
1297711
f09546b
903b80e
 
 
1297711
903b80e
 
 
 
 
 
 
 
 
 
1297711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08c5993
1297711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f09546b
1297711
 
 
 
 
 
 
 
903b80e
 
 
476a678
1297711
 
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
import os
import sys
import streamlit as st
import pandas as pd
import numpy as np
from io import BytesIO
import uuid
from tvDatafeed import TvDatafeed, Interval

from huggingface_hub import snapshot_download

# Download files from the private space
private_repo = "kishan-1721/my_private_app"  # Replace with your private space's repo ID
cache_dir = "/data/private_space_cache"  # Updated to use writable /data directory
snapshot_download(
    repo_id=private_repo,
    repo_type="space",
    local_dir=cache_dir,
    token=os.getenv("HF_TOKEN")  # Assumes HF_TOKEN is set as a secret
)

# Add the downloaded files to the Python path
sys.path.append(cache_dir)

# --- Streamlit Page Configuration ---
st.set_page_config(page_title="Stock Market Analyzer", layout="wide")

# --- Main Application ---
def main():
    st.title("Stock Market Analyzer")

    with st.container():
        col1, col2, col3, col4, col5, col6 = st.columns(6)
        with col1:
            global sideways_threshold
            sideways_threshold = st.slider("Sideways Threshold", min_value=0.0, max_value=2.0, value=0.0, step=0.01, format="%.2f") / 100
        with col2:
            global buffer
            buffer = st.slider("Buffer", min_value=0.0, max_value=2.0, value=0.0, step=0.01, format="%.2f") / 100
        with col3:
            global intra_sl_value
            intra_sl_value = st.slider("Intra SL Value", min_value=0.0, max_value=10.0, value=1.5, step=0.1, format="%.1f") / 100
        with col4:
            global target_sl
            target_sl = st.slider("Target SL Value", min_value=0.0, max_value=15.0, value=0.0, step=0.1, format="%.1f") / 100
        with col5:
            global trail_offset
            trail_offset = st.slider("Trailing SL %", min_value=0.0, max_value=10.0, value=3.0, step=0.1, format="%.1f") / 100
        with col6:
            global max_loss_sl
            max_loss_sl = st.slider("MaxLoss SL Value", min_value=0.0, max_value=10.0, value=3.0, step=0.1, format="%.1f") / 100
            
    with st.container():
        col1, col2, col4, col3  = st.columns([1,1,1,2])

        with col1:
            Trailing_Value = st.radio(
                "Set your Trailing Value ?",
                ["Close", "High - Low"],
                index=1
            )

            Exchange = st.radio(
                "Select your Exchange ?",
                ["Indian", "Crypto"],
                index=0
            )

        with col2:
            global brokerages
            brokerages = st.number_input(label="Brokerages",step=0.01,value=0.2644 ,format="%.4f")

            global interest_rate
            interest_rate = st.number_input(label="Funding Cost Per Day",step=0.01,value=0.04 ,format="%.4f")

            if intra_sl_value <= 0.0:
                st.text("IntraBar is Set to Previous Top - Bottom")
            if target_sl <= 0.0:
                st.text("No Target is Set")
            if trail_offset <= 0.0:
                st.text("No Trailing Stop-loss")

        with col4:
            global MTF_Exposure
            MTF_Exposure = st.slider("MTF Exposure", min_value=2.00, max_value=8.00, value=3.00, step=0.1, format="%.2f")

            selected_script  = st.radio(
                "Select Your Script",
                ["Old", "New Maxloss"],
                index=0
            )

        with col3:
            # File uploader

            if Exchange == 'Indian':
                symbol = ['NIFTY', 'BANKNIFTY', 'FINNIFTY', 'NIFTYIT', 'NIFTYFMCG', 'NIFTYMETAL', 'NIFTYPSU', 'NIFTYAUTO', 'NIFTYMEDIA', 'NIFTYPVTBANK', 'NIFTYREALTY', 'NIFTYCONSUMER', 'NIFTYENERGY', 
                          'NIFTYHEALTHCARE', 'NIFTYINFRA', 'NIFTYPHARMA', 'RELIANCE', 'TATAMOTORS', 'HDFCBANK', 'ICICIBANK', 'INFY', 'HINDUNILVR', 'LT', 'TCS', 'HDFC', 'KOTAKBANK', 'AXISBANK', 'ITC', 'SBIN', 'MARUTI', 'BAJFINANCE']
                exchange_list = ['NSE', 'BSE', 'MCX', 'NFO', 'CDS']
            else:
                symbol = ['ETHUSDT', 'BTCUSDT', 'BNBUSDT', 'XRPUSDT', 'SOLUSDT', 'DOGEUSDT', 'ADAUSDT', 'MATICUSDT', 'DOTUSDT', 'TRXUSDT']
                exchange_list = ['BINANCE', 'BITFINEX', 'COINBASE', 'BITSTAMP', 'OKEX', 'BYBIT', 'GEMINI']

            ## Add search functionality in selectbox
            # symbol = st.selectbox("Select Symbol", symbol, index=0, key="symbol_select")
            symbol = st.selectbox("Select Symbol", symbol, index=0, key="symbol_select", help="Search for a symbol by typing in the box")
            symbol_exchange = st.selectbox("Select Exchange", exchange_list, index=0, key="exchange_select", help="Search for an exchange by typing in the box")


            # symbol = st.selectbox("Select Symbol", symbol, index=0)
            # symbol_exchange = st.selectbox("Select Exchange", exchange_list, index=0)
            
            # uploaded_file = st.file_uploader("Upload your CSV file", type=["csv"])

    if selected_script == "Old":
        from main4 import get_buy_signal, parse_date, get_sell_signal, year_wise_analysis, calculate_yearly_returns, calculate_mtf_returns, crypto_year_wise_analysis, crypto_calculate_mtf_returns, crypto_calculate_yearly_returns, find_sequences, generate_trade_signals, data_collection
    else:
        from main6 import get_buy_signal, parse_date, get_sell_signal, year_wise_analysis, calculate_yearly_returns, calculate_mtf_returns, crypto_year_wise_analysis, crypto_calculate_mtf_returns, crypto_calculate_yearly_returns, find_sequences, generate_trade_signals, data_collection
    

    if st.button("Start Analysis"):
        HISTORICAL_DATA = data_collection(symbol = symbol, exchange = symbol_exchange)



        # st.divider()
        if HISTORICAL_DATA is not None:
            df = HISTORICAL_DATA.copy()
            try:
                df = df[['Date','Open','High', 'Low', 'Close']]
            except:
                df = df[['Date','Open','High', 'Low', 'Price']]

        # if st.button("Start Analysis"):
            # Data preprocessing
            df.columns = df.columns.str.strip()
            df['Date'] = parse_date(df['Date'])
            df.sort_values('Date', inplace=True)

            if 'Price' in df.columns:
                df = df.rename(columns={'Price': 'Close'})
            df['%Change'] = df['Close'].pct_change().fillna(0) * 100
            df["Direction"] = df["%Change"].apply(lambda x: "πŸ“ˆ" if x > 0 else "πŸ“‰")
            df['Side Ways'] = df['%Change'].apply(lambda x: abs(x / 100) < sideways_threshold)

            # Generate signals and trades
            # result = generate_trade_signals(df, trail_offset, target_sl, Trailing_Value)
            
            if selected_script == "Old":
                result = generate_trade_signals(df, trail_offset, target_sl, Trailing_Value, buffer, intra_sl_value)
            else:    
                result = generate_trade_signals(df, trail_offset, target_sl, Trailing_Value, buffer, intra_sl_value, max_loss_sl)
                
            final_df = result[1]
            final_df['Gap Loss 2%'] = final_df.apply(lambda x: True if x['Gap_UP_Down Trade'] == True and x['Profit %'] < -2 else False, axis=1)
            final_df['Gap Exit'] = np.where(final_df['Gap_UP_Down Trade'].shift(-1).eq(True), True, False)
            final_df['Gap Exit Loss % 2'] = np.where(final_df['Gap_UP_Down Trade'].shift(-1).eq(True) & (final_df['Profit %'] < -2), True, False)

            col1, col2 = st.columns(2)

            # with col1:
            #     st.subheader("πŸ“Ά Processed Signal Data", divider=True)
            #     st.dataframe(final_df)

            df = df.assign(Year=df['Date'].dt.year)
            final_df = final_df.assign(Year=final_df['Entry Date'].dt.year)

            if Exchange == 'Indian':

    ################################################### Performing Analysis ###################################################

                system_returns_no_compound, system_yearly_no_compound = calculate_yearly_returns(df,final_df, False, brokerages)

                system_returns_with_compound, system_yearly_with_compound = calculate_yearly_returns(df,final_df, True, brokerages)

                system_mtf_no_compound, system_mtf_yearly_no_compound = calculate_mtf_returns(df,final_df, MTF_Exposure, False, brokerages)
                            
                system_mtf_with_compound, system_mtf_yearly_with_compound = calculate_mtf_returns(df,final_df, MTF_Exposure, True, brokerages)
                
    ################################################### BUY Trade Performing Analysis ###################################################

                buy_trades_df = final_df[final_df['Trade Type'] == 'BUY']

                buy_trades_no_compound, buy_trades_yearly_no_compound = calculate_yearly_returns(df,buy_trades_df, False, brokerages)

                buy_trades_compound, buy_trades_yearly_compound = calculate_yearly_returns(df,buy_trades_df, True, brokerages)

                buy_trades_mtf_no_compound, buy_trades_mtf_yearly_no_compound = calculate_mtf_returns(df,buy_trades_df, MTF_Exposure, False, brokerages)

                buy_trades_mtf_returns_compound, buy_trades_mtf_yearly_compound = calculate_mtf_returns(df,buy_trades_df, MTF_Exposure, True, brokerages)

            else:
    ################################################### Crypto Performing Analysis ###################################################

    ################################################### Performing Analysis ###################################################

                system_returns_no_compound, system_yearly_no_compound = crypto_calculate_yearly_returns(df,final_df, False, brokerages)

                system_returns_with_compound, system_yearly_with_compound = crypto_calculate_yearly_returns(df,final_df, True, brokerages)

                system_mtf_no_compound, system_mtf_yearly_no_compound = crypto_calculate_mtf_returns(df,final_df, MTF_Exposure, False, brokerages, interest_rate)
                            
                system_mtf_with_compound, system_mtf_yearly_with_compound = crypto_calculate_mtf_returns(df,final_df, MTF_Exposure, True, brokerages, interest_rate)
                
    ################################################### BUY Trade Performing Analysis ###################################################

                buy_trades_df = final_df[final_df['Trade Type'] == 'BUY']

                buy_trades_no_compound, buy_trades_yearly_no_compound = crypto_calculate_yearly_returns(df,buy_trades_df, False, brokerages)

                buy_trades_compound, buy_trades_yearly_compound = crypto_calculate_yearly_returns(df,buy_trades_df, True, brokerages)

                buy_trades_mtf_no_compound, buy_trades_mtf_yearly_no_compound = crypto_calculate_mtf_returns(df,buy_trades_df, MTF_Exposure, False, brokerages, interest_rate)

                buy_trades_mtf_returns_compound, buy_trades_mtf_yearly_compound = crypto_calculate_mtf_returns(df,buy_trades_df, MTF_Exposure, True, brokerages, interest_rate)

            # system_yearly_analysis = year_wise_analysis(df, system_returns_no_compound)
            # System_Gain_Com = year_wise_analysis(df, system_returns_with_compound)
            # year_analysis_ = year_wise_analysis(df, system_mtf_with_compound)

            System_Gain_Com = system_mtf_yearly_no_compound
            # year_analysis_ = system_mtf_yearly_with_compound

            initial_investment_amount = 100000

            with col1:
                st.subheader("πŸ“† Year-Wise Performance", divider=True)
                st.dataframe(system_yearly_no_compound)

            with col2:
                st.subheader("πŸ“Ά Compounding Year-Wise Performance", divider=True)
                st.dataframe(System_Gain_Com)


            pcol1, pcol2, pcol3 = st.columns(3)
            
            with pcol1:
                st.subheader("πŸ“Š Performance Overview", divider=True)
                
                container = st.container(border=True)
                container.text(f"Average Trades : {round(system_yearly_no_compound['Total_Trades'].mean(), 0)}")
                container.text(f"Average BUY Trades : {round(system_yearly_no_compound['Total BUY Trades'].mean(), 0)}")
                container.text(f"Average SELL Trades : {round(system_yearly_no_compound['Total SELL Trades'].mean(), 0)}")

                container = st.container(border=True)
                container.text(f"Start Price {system_yearly_no_compound['Start_Price'].iloc[0]}, End Price : {system_yearly_no_compound['End_Price'].iloc[-1]}")
                container.text(f"Average Index Gain %: {round(system_yearly_no_compound['Index Gain'].sum() / len(system_yearly_no_compound), 2)}")
                container.text(f"Index CAGR = {round(((system_yearly_no_compound['End_Price'].iloc[-1] / system_yearly_no_compound['Start_Price'].iloc[0]) ** (1 / len(system_yearly_no_compound)) - 1) * 100, 2) } ")

                # container.text(f"Average System Gain %: {round(system_yearly_no_compound['System Gain'].sum() / len(system_yearly_no_compound), 2)}")
                # container.text(f"Difference: {round(system_yearly_no_compound['Difference'].sum() / len(system_yearly_no_compound) , 2) }")

            with pcol2:
                st.subheader("πŸ“Š Trade Overview", divider=True)

                container = st.container(border=True)               
                container.text(f"Total Years : {len(system_yearly_no_compound)}")
                container.text(f"Total Trades: {len(final_df)}")
                container.text(f"Profitable Trades {round(len(final_df[final_df['Profit'] > 0]))}")
                container.text(f"Total Target Hit: {len(final_df[final_df['Exit Condition'] == 'Target Hit'])}")
                container.text(f"Total Trailing Hit: {len(final_df[final_df['Exit Condition'] == 'Trailing Hit'])}")
                container.text(f"Total IntraBar Hit: {len(final_df[final_df['Exit Condition'] == 'IntraBar Hit'])}")
                container.text(f"Total MaxLoss Hit: {len(final_df[final_df['Exit Condition'] == f'MaxLoss {max_loss_sl*100}% Hit'])}")
                container.text(f"High - Low Average: {round(final_df['change %'].mean(), 2)}")
                # container.text(f"High - Low Average Number new: {round(np.percentile(final_df['change %'], 60), 2)}")
                container.text(f"% Winning Ratio {round((len(final_df[final_df['Profit'] > 0]) / len(final_df)) * 100, 2)} %")

            with pcol3:
                st.subheader("πŸ“Š Gap Up & Down Overview", divider=True)

                container = st.container(border=True)               
                container.text(f"Total Gap_UP_Down Trades: {final_df['Gap_UP_Down Trade'].sum()}")
                container.text(f"Total Gap_UP_Down Exit Trades: {final_df['Gap Exit'].sum()}")
                container.text(f"Loss More than 2 % in Gap_UP_Down Trades: {final_df['Gap Loss 2%'].sum()}")
                container.text(f"Loss More than 2 % in Gap_UP_Down Exit Trades: {final_df['Gap Exit Loss % 2'].sum()}")


                ################################## Risk Reward Ratio ##################################
                container = st.container(border=True)               
                
                p_trades = len(final_df[final_df['Profit'] > 0])
                N_trades = len(final_df[final_df['Profit'] < 0])

                p_profit_ = final_df[final_df['Profit'] > 0]['Profit'].sum()
                N_profit_ = final_df[final_df['Profit'] < 0]['Profit'].sum()

                p_profit_avg = final_df[final_df['Profit'] > 0]['Profit %'].mean()
                N_profit_avg = final_df[final_df['Profit'] < 0]['Profit %'].mean()
                
                # container.text(f" (p_profit = {p_profit_} / p_trades = {p_trades}) / (N_profit_ = {N_profit_} / N_trades = {N_trades})")

                ratio = abs((p_profit_ / p_trades) / ( N_profit_ / N_trades))

                container.text(f"% Risk Reward Ratio: {round(ratio, 3 )} %")
                container.text(f"% Profit Avg: {round(p_profit_avg, 4 )} %")
                container.text(f"% Loss Avg: {round(N_profit_avg, 4 )} ")

                if Exchange != 'Indian':
                    container.text(f"Max Holding Days: {System_Gain_Com['HOLDING DAYS'].max()}")
                

            st.divider()
################################################### Performance Analysis ###################################################

            pcol1, pcol2, pcol3 = st.columns(3)

            with pcol1:
                st.subheader("πŸ“ˆ System Performance", divider=True)

                total_profit_ = round(system_yearly_no_compound['Final Profit After All'].sum(), 2)
                total_profit_AVG = round(system_yearly_no_compound['System Gain'].sum() / len(system_yearly_no_compound), 2)

                buy_profit = round(buy_trades_yearly_no_compound['Final Profit After All'].sum(), 2)
                buy_profit_AVG = round(buy_trades_yearly_no_compound['System Gain'].sum() / len(buy_trades_yearly_no_compound), 2)

                sell_profit = round(total_profit_ - buy_profit, 2)
                sell_profit_avg = round(total_profit_AVG - buy_profit_AVG, 2)

                container = st.container(border=True)
                container.write(f"**Total Profit : {total_profit_} (AVG : {total_profit_AVG} %)**")
                container.write(f"**Buy Profit : {buy_profit} (AVG : {buy_profit_AVG} %)**")
                container.write(f"**SELL Profit : {sell_profit} (AVG : {sell_profit_avg} %)**")
                container.text(f"Total Years : {len(system_yearly_no_compound)}")

                # container.write(f"**Total BUY Profit : {round(system_yearly_no_compound['BUY_Profit'].sum(), 2)} ({round((system_yearly_no_compound['BUY_Profit'].sum() * 100)/system_yearly_no_compound['Profit'].sum(), 2)} %) (AVG : {round(system_yearly_no_compound['BUY_Gain'].mean(), 2)} %)**")
                # container.write(f"**Total SELL Profit : {round(system_yearly_no_compound['SELL_Profit'].sum(), 2)} ({round((system_yearly_no_compound['SELL_Profit'].sum() * 100)/system_yearly_no_compound['Profit'].sum(), 2)} %)**")
                
                container.markdown("---") 
                ten_years = system_yearly_no_compound.tail(10)
                container.write(f"**Last 10 Years AVG %: {round(ten_years['System Gain'].sum() / len(ten_years), 2)}**")
                # container.text(f"Last 10 Years Only BUY AVG % : {round(ten_years['BUY_Gain'].mean(), 2)}")

                ten_years = buy_trades_yearly_no_compound.tail(10)
                container.write(f"**Buy System Last 10 Years AVG %: {round(ten_years['System Gain'].sum() / len(ten_years), 2)}**")
                
                container.markdown("---") 
                five_years = system_yearly_no_compound.tail(5)
                container.write(f"**Last 5 Years AVG %: {round(five_years['System Gain'].sum() / len(five_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")

                five_years = buy_trades_yearly_no_compound.tail(5)
                container.write(f"**Buy System Last 5 Years AVG %: {round(five_years['System Gain'].sum() / len(five_years), 2)}**")
                
                container.markdown("---") 
                three_years = system_yearly_no_compound.tail(3)
                container.write(f"**Last 3 Years AVG %: {round(three_years['System Gain'].sum() / len(three_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")

                three_years = buy_trades_yearly_no_compound.tail(3)
                container.write(f"**Buy System Last 3 Years AVG %: {round(three_years['System Gain'].sum() / len(three_years), 2)}**")

                container.markdown("---") 
                two_years = system_yearly_no_compound.tail(2)
                container.write(f"**Last 2 Years AVG %: {round(two_years['System Gain'].sum() / len(two_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")

                two_years = buy_trades_yearly_no_compound.tail(2)
                container.write(f"**Buy System Last 2 Years AVG %: {round(two_years['System Gain'].sum() / len(two_years), 2)}**")

                container.markdown("---") 
                one_years = system_yearly_no_compound.tail(1)
                container.write(f"**Last 1 Years AVG %: {round(one_years['System Gain'].sum() / len(one_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")

                one_years = buy_trades_yearly_no_compound.tail(1)
                container.write(f"**Buy System Last 1 Years AVG %: {round(one_years['System Gain'].sum() / len(one_years), 2)}**")

            with pcol2:
                st.subheader("πŸ“ˆ Compounding Performance", divider=True)

                compund_system_cagr = round((((((system_yearly_with_compound['Final Profit After All'].sum()) + 100000) / 100000 ) ** (1 / len(system_yearly_with_compound))) -1 ) * 100 , 2)
                buy_compund_system_cagr = round((((((buy_trades_yearly_compound['Final Profit After All'].sum()) + 100000) / 100000) ** (1 / len(buy_trades_yearly_compound))) -1 ) * 100 , 2)

                container = st.container(border=True)
                container.write(f"**Total Profit : {round(system_yearly_with_compound['Final Profit After All'].sum(), 2)} (AVG : {round(system_yearly_with_compound['System Gain'].sum() / len(system_yearly_with_compound), 2)} %) (C:{compund_system_cagr} %)**")
                container.write(f"**Buy Profit : {round(buy_trades_yearly_compound['Final Profit After All'].sum(), 2)} (AVG : {round(buy_trades_yearly_compound['System Gain'].sum() / len(buy_trades_yearly_compound), 2)} %) (C:{buy_compund_system_cagr} %)**")
                container.write(f"Initial Investment : {initial_investment_amount}")

                # container.write(f"**Total BUY Profit : {round(system_yearly_with_compound['BUY_Profit'].sum(), 2)} ({round((system_yearly_with_compound['BUY_Profit'].sum() * 100)/system_yearly_with_compound['Profit'].sum(), 2)} %) (AVG : {round(system_yearly_with_compound['BUY_Gain'].mean(), 2)} %)**")
                # container.write(f"**Total SELL Profit : {round(system_yearly_with_compound['SELL_Profit'].sum(), 2)} ({round((system_yearly_with_compound['SELL_Profit'].sum() * 100)/system_yearly_with_compound['Profit'].sum(), 2)} %)**")
                
                container.markdown("---") 
                ten_years = system_yearly_with_compound.tail(10)
                container.write(f"**Last 10 Years AVG %: {round(ten_years['System Gain'].sum() / len(ten_years), 2)}**")
                # container.text(f"Last 10 Years Only BUY AVG % : {round(ten_years['BUY_Gain'].mean(), 2)}")

                ten_years = buy_trades_yearly_compound.tail(10)
                container.write(f"**Buy System Last 10 Years AVG %: {round(ten_years['System Gain'].sum() / len(ten_years), 2)}**")
                
                container.markdown("---") 
                five_years = system_yearly_with_compound.tail(5)
                container.write(f"**Last 5 Years AVG %: {round(five_years['System Gain'].sum() / len(five_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")
                
                five_years = buy_trades_yearly_compound.tail(5)
                container.write(f"**Buy System Last 5 Years AVG %: {round(five_years['System Gain'].sum() / len(five_years), 2)}**")

                container.markdown("---") 
                three_years = system_yearly_with_compound.tail(3)
                container.write(f"**Last 3 Years AVG %: {round(three_years['System Gain'].sum() / len(three_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")
                
                three_years = buy_trades_yearly_compound.tail(3)
                container.write(f"**Buy System Last 3 Years AVG %: {round(three_years['System Gain'].sum() / len(three_years), 2)}**")

                container.markdown("---") 
                two_years = system_yearly_with_compound.tail(2)
                container.write(f"**Last 2 Years AVG %: {round(two_years['System Gain'].sum() / len(two_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")
                
                two_years = buy_trades_yearly_compound.tail(2)
                container.write(f"**Buy System Last 2 Years AVG %: {round(two_years['System Gain'].sum() / len(two_years), 2)}**")

                container.markdown("---") 
                one_years = system_yearly_with_compound.tail(1)
                container.write(f"**Last 1 Years AVG %: {round(one_years['System Gain'].sum() / len(one_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")
                
                one_years = buy_trades_yearly_compound.tail(1)
                container.write(f"**Buy System Last 1 Years AVG %: {round(one_years['System Gain'].sum() / len(one_years), 2)}**")

            with pcol3:
                st.subheader("πŸ“ˆ MTF Compounding Gain", divider=True)

                mtf_investment = initial_investment_amount / MTF_Exposure 

                compund_system_cagr = round((((((system_mtf_yearly_with_compound['Final Profit After All'].sum()) + mtf_investment) / mtf_investment) ** (1 / len(system_mtf_yearly_with_compound))) -1 ) * 100 , 2)
                buy_compund_system_cagr = round((((((buy_trades_mtf_yearly_compound['Final Profit After All'].sum()) + mtf_investment) / mtf_investment) ** (1 / len(buy_trades_mtf_yearly_compound))) -1 ) * 100 , 2)

                container = st.container(border=True)
                container.write(f"**Total Profit : {round(system_mtf_yearly_with_compound['Final Profit After All'].sum(), 2)} (AVG : {round(system_mtf_yearly_with_compound['System Gain'].sum() / len(system_mtf_yearly_with_compound), 2)} %) (C:{compund_system_cagr} %)**")
                container.write(f"**Buy Profit : {round(buy_trades_mtf_yearly_compound['Final Profit After All'].sum(), 2)} (AVG : {round(buy_trades_mtf_yearly_compound['System Gain'].sum() / len(buy_trades_mtf_yearly_compound), 2)} %) (C:{buy_compund_system_cagr} %)**")
                container.write(f"Initial Investment : {mtf_investment}")

                # container.write(f"**Total BUY Profit : {round(system_mtf_yearly_with_compound['BUY_Profit'].sum(), 2)} ({round((system_mtf_yearly_with_compound['BUY_Profit'].sum() * 100)/system_mtf_yearly_with_compound['Profit'].sum(), 2)} %) (AVG : {round(system_mtf_yearly_with_compound['BUY_Gain'].mean(), 2)} %)**")
                # container.write(f"**Total SELL Profit : {round(system_mtf_yearly_with_compound['SELL_Profit'].sum(), 2)} ({round((system_mtf_yearly_with_compound['SELL_Profit'].sum() * 100)/system_mtf_yearly_with_compound['Profit'].sum(), 2)} %)**")
                
                container.markdown("---") 
                ten_years = system_mtf_yearly_with_compound.tail(10)
                container.write(f"**Last 10 Years AVG %: {round(ten_years['System Gain'].sum() / len(ten_years), 2)}**")
                # container.text(f"Last 10 Years Only BUY AVG % : {round(ten_years['BUY_Gain'].mean(), 2)}")

                ten_years = buy_trades_mtf_yearly_compound.tail(10)
                container.write(f"**Buy System Last 10 Years AVG %: {round(ten_years['System Gain'].sum() / len(ten_years), 2)}**")
                
                container.markdown("---") 
                five_years = system_mtf_yearly_with_compound.tail(5)
                container.write(f"**Last 5 Years AVG %: {round(five_years['System Gain'].sum() / len(five_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")

                five_years = buy_trades_mtf_yearly_compound.tail(5)
                container.write(f"**Buy System Last 5 Years AVG %: {round(five_years['System Gain'].sum() / len(five_years), 2)}**")

                container.markdown("---") 
                three_years = system_mtf_yearly_with_compound.tail(3)
                container.write(f"**Last 3 Years AVG %: {round(three_years['System Gain'].sum() / len(three_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")

                three_years = buy_trades_mtf_yearly_compound.tail(3)
                container.write(f"**Buy System Last 3 Years AVG %: {round(three_years['System Gain'].sum() / len(three_years), 2)}**")

                container.markdown("---") 
                two_years = system_mtf_yearly_with_compound.tail(2)
                container.write(f"**Last 2 Years AVG %: {round(two_years['System Gain'].sum() / len(two_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")

                two_years = buy_trades_mtf_yearly_compound.tail(2)
                container.write(f"**Buy System Last 2 Years AVG %: {round(two_years['System Gain'].sum() / len(two_years), 2)}**")
           
                container.markdown("---") 
                one_years = system_mtf_yearly_with_compound.tail(1)
                container.write(f"**Last 1 Years AVG %: {round(one_years['System Gain'].sum() / len(one_years), 2)}**")
                # container.text(f"Last 5 Years Only BUY AVG % : {round(five_years['BUY_Gain'].mean(), 2)}")

                one_years = buy_trades_mtf_yearly_compound.tail(1)
                container.write(f"**Buy System Last 1 Years AVG %: {round(one_years['System Gain'].sum() / len(one_years), 2)}**")
           
            temp = final_df[['Entry Date', 'Trade Type', 'Gap_UP_Down Trade', 'GAP_P', 'Entry Price', 'Exit Date', 'Exit Condition', 'Exit Price', 'Profit', 'Profit %', 'Gap Loss 2%','Year']]
            temp.rename(columns={'Trade Type' : 'Trade', 'Gap_UP_Down Trade' : 'GAP', 'Entry Price' : 'Entry', 'Exit Price' : 'Exit', 'Gap Loss 2%' : 'Gap Loss %'}, inplace = True)
            
            # Filter out rows where '% Profit' is NaN and sort by 'Entry Date'
            def max_Profit_loss(final_df):
                filtered_df = final_df[final_df['Profit %'].notna()].sort_values('Entry Date')

                # Define conditions for profit and loss sequences
                profit_condition = lambda row: row['Profit %'] >= 0
                loss_condition = lambda row: row['Profit %'] <= 0

                # Find profit and loss sequences
                profit_sequences = find_sequences(filtered_df, profit_condition)
                loss_sequences = find_sequences(filtered_df, loss_condition)

                # Convert sequences to DataFrames
                profit_df = pd.DataFrame(profit_sequences)
                loss_df = pd.DataFrame(loss_sequences)

                # Get top 20 sequences
                # Top 20 profit sequences (highest total % profit)
                top_profit_df = profit_df.sort_values('Total %', ascending=False).head(20)
                # Top 20 loss sequences (most negative total % loss)
                top_loss_df = loss_df.sort_values('Total %', ascending=True).head(20)

                # Add 'Type' column to distinguish between profit and loss
                top_profit_df['Type'] = 'Profit'
                top_loss_df['Type'] = 'Loss'

                top_profit_df.reset_index(drop=True, inplace=True)
                top_loss_df.reset_index(drop=True, inplace=True)

                data = {
                    'Year_L': top_loss_df['Start Date'].apply(lambda x: x.year),
                    # 'End Date_Loss': top_loss_df['End Date'],
                    '%_Loss': top_loss_df['Total %'],
                    
                    'Year_P': top_profit_df['Start Date'].apply(lambda x: x.year),
                    # 'End Date_Profit': top_profit_df['End Date'],
                    '%_Profit': top_profit_df['Total %']
                }
                return pd.DataFrame(data)
                
            st.divider()
            
            st.subheader("Detail Analysis of Maximum Profit πŸ“ˆ and Loss πŸ“‰", divider=True)
            pcol1, pcol2, pcol3 = st.columns([1,1,2])

            with pcol1:
                st.text("General Analysis")
                profit_loss_all = max_Profit_loss(final_df)
                st.dataframe(profit_loss_all)

            with pcol2:
                st.text("Only in BUY Trades")
                profit_loss_all_BUY = max_Profit_loss(buy_trades_df)
                st.dataframe(profit_loss_all_BUY)
            
            with pcol3:
                st.text("Gap Up & Down Loss πŸ“‰")
                st.dataframe(final_df[final_df['Gap Exit Loss % 2'] == True].reset_index())

            # Save to Excel
            excel_buffer = BytesIO()
            with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
                final_df.to_excel(writer, sheet_name='Trades Analysis', index=False)
                # temp.to_excel(writer, sheet_name='Full Analysis', index=False)
                system_returns_no_compound.to_excel(writer, sheet_name='System Analysis', index=False)
                system_yearly_no_compound.to_excel(writer, sheet_name='System Yearly', index=False)

                profit_loss_all.to_excel(writer, sheet_name='Profit-Loss Analysis', index=False)

                system_returns_with_compound.to_excel(writer, sheet_name='System Compounding', index=False)
                system_yearly_with_compound.to_excel(writer, sheet_name='System Compounding Yearly', index=False)

                system_mtf_no_compound.to_excel(writer, sheet_name='MTF System Analysis', index=False)
                system_mtf_yearly_no_compound.to_excel(writer, sheet_name='MTF System Yearly', index=False)

                system_mtf_with_compound.to_excel(writer, sheet_name='CMP MTF System', index=False)
                system_mtf_yearly_with_compound.to_excel(writer, sheet_name='CMP MTF Yearly', index=False)

                buy_trades_no_compound.to_excel(writer, sheet_name='BUY Analysis', index=False)
                buy_trades_yearly_no_compound.to_excel(writer, sheet_name='BUY Yearly', index=False)

                buy_trades_compound.to_excel(writer, sheet_name='BUY Compound', index=False)
                buy_trades_yearly_compound.to_excel(writer, sheet_name='BUY Compound Yearly', index=False)

                buy_trades_mtf_no_compound.to_excel(writer, sheet_name='BUY MTF', index=False)
                buy_trades_mtf_yearly_no_compound.to_excel(writer, sheet_name='BUY MTF Yearly', index=False)
                
                buy_trades_mtf_returns_compound.to_excel(writer, sheet_name='BUY MTF CMP', index=False)
                buy_trades_mtf_yearly_compound.to_excel(writer, sheet_name='BUY MTF CMP Yearly', index=False)


            file_name_ = f"{symbol} Trailing {trail_offset} Target {target_sl}"

            excel_buffer.seek(0)
            st.download_button(
                label="Download Excel File",
                data=excel_buffer,
                file_name=f"Analysis of {file_name_}.xlsx",
                mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            )
            
        else:
            st.error("No historical data found for the selected symbol and exchange. Please check the inputs and try again.")

if __name__ == "__main__":
    main()