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(""" """, 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(""" """, unsafe_allow_html=True) st.markdown('
', 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'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.