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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
import streamlit as st
import requests
from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
from scipy import stats
import os

# Set page title and configuration
st.set_page_config(page_title="Theaimart Stock Analysis", page_icon="πŸ“Š", layout="wide")

# Enhanced Custom CSS
st.markdown("""
<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap');

    body {
        font-family: 'Roboto', sans-serif;
        background-color: #f0f2f6;
        color: #1E1E1E;
    }
    .reportview-container {
        background: linear-gradient(135deg, #f0f2f6 0%, #e0e7ff 100%);
    }
    .main .block-container {
        padding-top: 2rem;
        padding-bottom: 2rem;
        max-width: 1200px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        border-radius: 10px;
        background-color: white;
    }
    h1, h2, h3 {
        color: #1E3A8A;
        font-weight: 700;
    }
    .stButton>button {
        background-color: #1E3A8A;
        color: white;
        font-weight: bold;
        border-radius: 5px;
        padding: 0.75rem 1.5rem;
        border: none;
        width: 100%;
        transition: all 0.3s ease;
    }
    .stButton>button:hover {
        background-color: #2563EB;
        transform: translateY(-2px);
        box-shadow: 0 4px 6px rgba(37, 99, 235, 0.3);
    }
    .stTextInput>div>div>input, .stSelectbox>div>div>select {
        border-radius: 5px;
        border: 1px solid #E5E7EB;
    }
    .stPlotlyChart {
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    .overview-card {
        background-color: #F3F4F6;
        border-radius: 10px;
        padding: 1.5rem;
        margin-bottom: 1rem;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }
    .metric-card {
        background-color: #EFF6FF;
        border-radius: 8px;
        padding: 1rem;
        margin-bottom: 0.5rem;
    }
    .footer {
        text-align: center;
        padding: 1rem 0;
        font-size: 0.8rem;
        color: #6B7280;
    }
    @media (max-width: 640px) {
        .main .block-container {
            padding: 1rem 0.5rem;
        }
        h1 {
            font-size: 1.75rem;
        }
        h2 {
            font-size: 1.5rem;
        }
        h3 {
            font-size: 1.25rem;
        }
    }
</style>
""", unsafe_allow_html=True)

@st.cache_data(ttl=3600)
def search_google(query):
    url = f"https://www.google.com/search?q={query}"
    headers = {"User-Agent": "Mozilla/5.0"}
    try:
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'html.parser')

        results = []
        for g in soup.find_all('div', class_='g'):
            anchor = g.find('a')
            if anchor:
                results.append({"title": anchor.text, "link": anchor['href']})

        return results[:5]  # Return top 5 results
    except Exception as e:
        st.error(f"Error fetching news: {str(e)}")
        return []

@st.cache_data(ttl=3600)
def fetch_stock_data(ticker, period="2y"):
    try:
        stock = yf.Ticker(ticker)
        end_date = datetime.now()
        start_date = end_date - timedelta(days=2 * 365)  # 2 years of data for more accurate analysis
        history = stock.history(start=start_date, end=end_date)
        return history
    except Exception as e:
        st.error(f"Error fetching stock data: {str(e)}")
        return pd.DataFrame()

def analyze_market_data(stock_data):
    if stock_data.empty:
        return "Insufficient data for analysis."

    last_price = stock_data['Close'].iloc[-1]
    avg_price = stock_data['Close'].mean()
    high_price = stock_data['High'].max()
    low_price = stock_data['Low'].min()

    # Calculate 52-week high and low
    year_data = stock_data.last('365D')
    week_52_high = year_data['High'].max()
    week_52_low = year_data['Low'].min()

    return f"""
    - Current Price: ${last_price:.2f}
    - Average (2y): ${avg_price:.2f}
    - 52-Week High: ${week_52_high:.2f}
    - 52-Week Low: ${week_52_low:.2f}
    - All-Time High: ${high_price:.2f}
    - All-Time Low: ${low_price:.2f}
    """

def develop_trading_strategies(stock, risk_tolerance, strategy_preference, stock_data):
    if stock_data.empty:
        return "Insufficient data for strategy development."

    # Calculate some basic metrics
    returns = stock_data['Close'].pct_change()
    volatility = returns.std() * np.sqrt(252)
    sharpe_ratio = (returns.mean() * 252) / (returns.std() * np.sqrt(252))

    prompt = f"""
    Develop a trading strategy for {stock} with {risk_tolerance} risk tolerance,
    focusing on {strategy_preference}. Consider the following metrics:
    - Volatility: {volatility:.2f}
    - Sharpe Ratio: {sharpe_ratio:.2f}
    Provide a concise, fact-based strategy in 3-4 sentences, avoiding speculative advice.
    """
    # Here you should implement the logic to develop trading strategies based on the given parameters
    return f"""
    - Volatility: {volatility:.2f}
    - Sharpe Ratio: {sharpe_ratio:.2f}
    - Strategy: Focus on momentum trading, entering positions during periods of low volatility and high Sharpe ratios. Use stop-loss orders to manage risk and take profit levels to lock in gains.
    """

def plan_trade_execution(stock, initial_capital, risk_tolerance, stock_data):
    if stock_data.empty:
        return "Insufficient data for execution planning."

    risk_percentages = {"Low": 0.01, "Medium": 0.03, "High": 0.05}
    risk_amount = initial_capital * risk_percentages[risk_tolerance]

    # Calculate Average True Range (ATR) for more accurate stop loss
    stock_data['H-L'] = stock_data['High'] - stock_data['Low']
    stock_data['H-PC'] = abs(stock_data['High'] - stock_data['Close'].shift(1))
    stock_data['L-PC'] = abs(stock_data['Low'] - stock_data['Close'].shift(1))
    stock_data['TR'] = stock_data[['H-L', 'H-PC', 'L-PC']].max(axis=1)
    stock_data['ATR'] = stock_data['TR'].rolling(window=14).mean()

    last_price = stock_data['Close'].iloc[-1]
    atr = stock_data['ATR'].iloc[-1]

    stop_loss = last_price - (2 * atr)
    take_profit = last_price + (3 * atr)

    return f"""
    For {stock}:
    - Initial Capital: ${initial_capital:,}
    - Risk per Trade: ${risk_amount:,.2f}
    - Suggested Stop Loss: ${stop_loss:.2f} (based on ATR)
    - Suggested Take Profit: ${take_profit:.2f} (based on ATR)
    - Max Position Size: {(risk_amount / (last_price - stop_loss)):.0f} shares
    """

def assess_trading_risks(stock, stock_data):
    if stock_data.empty:
        return "Insufficient data for risk assessment."

    returns = stock_data['Close'].pct_change().dropna()

    # Calculate key risk metrics
    volatility = returns.std() * np.sqrt(252)
    annual_return = (returns.mean() * 252)
    sharpe_ratio = annual_return / volatility if volatility != 0 else 0

    # Calculate Value at Risk (VaR) and Conditional VaR (CVaR)
    var_95 = np.percentile(returns, 5)
    cvar_95 = returns[returns <= var_95].mean()

    # Calculate downside deviation
    downside_returns = returns[returns < 0]
    downside_deviation = np.sqrt(np.mean(downside_returns ** 2))

    # Calculate maximum drawdown
    cumulative_returns = (1 + returns).cumprod()
    max_return = cumulative_returns.cummax()
    drawdown = (cumulative_returns - max_return) / max_return
    max_drawdown = drawdown.min()

    # Prepare risk metrics for display
    risk_metrics = {
        "Annualized Volatility": f"{volatility:.2%}",
        "Annualized Return": f"{annual_return:.2%}",
        "Sharpe Ratio": f"{sharpe_ratio:.2f}",
        "95% VaR (1-day)": f"{var_95:.2%}",
        "95% CVaR (1-day)": f"{cvar_95:.2%}",
        "Downside Deviation": f"{downside_deviation:.2%}",
        "Maximum Drawdown": f"{max_drawdown:.2%}"
    }

    # Create a heatmap of correlations
    corr_matrix = stock_data[['Open', 'High', 'Low', 'Close', 'Volume']].corr()

    # Prepare the heatmap
    heatmap = go.Figure(data=go.Heatmap(
        z=corr_matrix.values,
        x=corr_matrix.index.values,
        y=corr_matrix.columns.values,
        colorscale='RdBu',
        zmin=-1, zmax=1))
    heatmap.update_layout(title="Correlation Heatmap")

    return risk_metrics, heatmap

def create_candlestick_chart(stock_data):
    fig = go.Figure(data=[go.Candlestick(x=stock_data.index,
                                         open=stock_data['Open'],
                                         high=stock_data['High'],
                                         low=stock_data['Low'],
                                         close=stock_data['Close'])])
    fig.update_layout(
        title="Stock Price Chart",
        xaxis_title="Date",
        yaxis_title="Price",
        height=500,
        margin=dict(l=10, r=10, t=40, b=10),
        xaxis_rangeslider_visible=False
    )
    return fig

@st.cache_data
def run_monte_carlo_simulation(stock_data, initial_investment, num_simulations, time_horizon):
    returns = stock_data['Close'].pct_change().dropna()
    mu = returns.mean()
    sigma = returns.std()

    simulations = np.zeros((num_simulations, time_horizon))
    for i in range(num_simulations):
        # Generate random returns
        random_returns = np.random.normal(mu, sigma, time_horizon)
        # Calculate cumulative returns
        cumulative_returns = np.cumprod(1 + random_returns)
        # Calculate portfolio value
        simulations[i] = initial_investment * cumulative_returns

    return simulations

# Streamlit app
st.title("πŸš€ Theaimart Stock Investment Analysis")

# Display current date and time
st.write(f"πŸ“… Analysis Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

# Inputs section
st.header("πŸ“Š Analysis Parameters")
col1, col2 = st.columns(2)
with col1:
    stock_selection = st.text_input("Stock Ticker (e.g., AAPL):", "AAPL")
    initial_capital = st.number_input("Initial Capital ($):", min_value=1000, value=100000, step=1000)
with col2:
    risk_tolerance = st.select_slider("Risk Tolerance:", options=["Low", "Medium", "High"], value="Medium")
    trading_strategy_preference = st.selectbox("Trading Strategy:",
                                               ["Day Trading", "Swing Trading", "Position Trading"])

news_impact_consideration = st.checkbox("Consider News Impact", value=True)

if st.button("πŸ” Run In-Depth Analysis"):
    st.session_state['run_clicked'] = True

    # Add JavaScript for redirection and delay
    st.markdown("""
    <script>
    setTimeout(function() {
        document.getElementById("loading_ad").style.display = "block";
    }, 1000);
    setTimeout(function() {
        window.location.href = "https://corgouzaptax.com/4/7764906";
    }, 5000);
    </script>
    """, unsafe_allow_html=True)
    st.markdown('<div id="loading_ad" style="display: none; color: red; font-weight: bold;">Loading ad...</div>',
                unsafe_allow_html=True)

# Main content area
if st.session_state.get('run_clicked', False):
    with st.spinner("πŸ”¬ Analyzing... Please wait for comprehensive insights."):
        try:
            stock_data = fetch_stock_data(stock_selection)

            if not stock_data.empty:
                # Stock Price Chart
                st.subheader("πŸ“ˆ Stock Price Trends")
                st.plotly_chart(create_candlestick_chart(stock_data), use_container_width=True)

                # Market Analysis
                st.subheader("πŸ“‰ Market Metrics")
                market_analysis = analyze_market_data(stock_data)
                st.markdown(f'<div class="metric-card">{market_analysis}</div>', unsafe_allow_html=True)

                # Trading Strategy
                st.subheader("πŸ’Ό Personalized Trading Strategy")
                strategy = develop_trading_strategies(stock_selection, risk_tolerance, trading_strategy_preference,
                                                      stock_data)
                st.success(strategy)

                # Execution Plan
                st.subheader("πŸ“‹ Smart Execution Plan")
                plan = plan_trade_execution(stock_selection, initial_capital, risk_tolerance, stock_data)
                st.info(plan)

                # Risk Assessment
                st.subheader("⚠️ Comprehensive Risk Assessment")
                risk_metrics, risk_heatmap = assess_trading_risks(stock_selection, stock_data)

                col1, col2 = st.columns(2)
                with col1:
                    st.write("Key Risk Metrics:")
                    for metric, value in risk_metrics.items():
                        st.metric(metric, value)

                with col2:
                    st.plotly_chart(risk_heatmap, use_container_width=True)

                st.write("""
                    **Interpretation Guide:**
                    - **Volatility**: Higher values indicate greater price fluctuations.
                    - **Sharpe Ratio**: Higher values suggest better risk-adjusted returns.
                    - **VaR & CVaR**: Represent potential losses in worst-case scenarios.
                    - **Downside Deviation**: Measures negative volatility.
                    - **Maximum Drawdown**: The largest peak-to-trough decline.

                    The correlation heatmap shows relationships between different price metrics and volume.
                    Darker red indicates strong positive correlation, while darker blue indicates strong negative correlation.
                """)

                if news_impact_consideration:
                    st.subheader("πŸ“° Latest Market News")
                    news_results = search_google(f"{stock_selection} stock news")
                    for idx, result in enumerate(news_results, 1):
                        st.markdown(f"{idx}. [{result['title']}]({result['link']})")

                # Portfolio Simulation
                st.subheader("🎲 Advanced Portfolio Simulation")

                num_simulations = 1000
                time_horizon = 252  # One year of trading days

                try:
                    simulations = run_monte_carlo_simulation(stock_data, initial_capital, num_simulations, time_horizon)

                    final_values = simulations[:, -1]
                    mean_final_value = np.mean(final_values)
                    median_final_value = np.median(final_values)

                    confidence_interval = np.percentile(final_values, [5, 95])

                    st.write(f"Based on {num_simulations} simulations over {time_horizon} trading days:")
                    st.metric("Expected Portfolio Value", f"${mean_final_value:,.2f}")
                    st.metric("Median Portfolio Value", f"${median_final_value:,.2f}")
                    st.write(
                        f"90% Confidence Interval: ${confidence_interval[0]:,.2f} to ${confidence_interval[1]:,.2f}")

                    # Visualization of simulation results
                    fig = go.Figure()
                    for i in range(min(100, num_simulations)):  # Plot first 100 simulations
                        fig.add_trace(
                            go.Scatter(y=simulations[i], mode='lines', line=dict(width=0.5), showlegend=False))
                    fig.update_layout(title='Monte Carlo Simulation of Portfolio Value',
                                      xaxis_title='Trading Days',
                                      yaxis_title='Portfolio Value ($)')
                    st.plotly_chart(fig, use_container_width=True)

                except Exception as e:
                    st.error(f"An error occurred during the Monte Carlo simulation: {str(e)}")
                    st.write("Unable to perform portfolio simulation due to insufficient or inconsistent data.")

            else:
                st.error("Unable to fetch stock data. Please check the ticker symbol and try again.")

        except Exception as e:
            st.error(f"An unexpected error occurred: {str(e)}")
            st.write("Please try again later or contact support if the problem persists.")

    st.session_state['run_clicked'] = False

# Disclaimer
st.markdown("---")
st.markdown("""
    <div style="background-color: #FFF3CD; padding: 10px; border-radius: 5px; margin-top: 20px;">
        <h3 style="color: #856404;">⚠️ Disclaimer</h3>
        <p>The information provided by this tool is for educational and informational purposes only. It should not be considered as financial advice or a recommendation to buy, sell, or hold any investment or security. Always consult with a qualified financial advisor before making any investment decisions. Past performance does not guarantee future results. Investing in stocks carries risk, and you may lose some or all of your invested capital.</p>
    </div>
""", unsafe_allow_html=True)

# Footer
st.markdown('<div class="footer">Β© Theaimart 2024 | Advanced Stock Analysis Tool</div>', unsafe_allow_html=True)
st.caption("Powered by cutting-edge AI and real-time financial data analysis.")