Stock_Analyzer_API / src /streamlit_app.py
kishan-1721's picture
Update src/streamlit_app.py
903b80e verified
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()