|
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 |
|
|
|
|
|
st.set_page_config(page_title="Theaimart Stock Analysis", page_icon="π", layout="wide") |
|
|
|
|
|
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] |
|
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) |
|
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() |
|
|
|
|
|
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." |
|
|
|
|
|
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. |
|
""" |
|
|
|
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] |
|
|
|
|
|
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() |
|
|
|
|
|
volatility = returns.std() * np.sqrt(252) |
|
annual_return = (returns.mean() * 252) |
|
sharpe_ratio = annual_return / volatility if volatility != 0 else 0 |
|
|
|
|
|
var_95 = np.percentile(returns, 5) |
|
cvar_95 = returns[returns <= var_95].mean() |
|
|
|
|
|
downside_returns = returns[returns < 0] |
|
downside_deviation = np.sqrt(np.mean(downside_returns ** 2)) |
|
|
|
|
|
cumulative_returns = (1 + returns).cumprod() |
|
max_return = cumulative_returns.cummax() |
|
drawdown = (cumulative_returns - max_return) / max_return |
|
max_drawdown = drawdown.min() |
|
|
|
|
|
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%}" |
|
} |
|
|
|
|
|
corr_matrix = stock_data[['Open', 'High', 'Low', 'Close', 'Volume']].corr() |
|
|
|
|
|
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): |
|
|
|
random_returns = np.random.normal(mu, sigma, time_horizon) |
|
|
|
cumulative_returns = np.cumprod(1 + random_returns) |
|
|
|
simulations[i] = initial_investment * cumulative_returns |
|
|
|
return simulations |
|
|
|
|
|
st.title("π Theaimart Stock Investment Analysis") |
|
|
|
|
|
st.write(f"π
Analysis Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") |
|
|
|
|
|
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 |
|
|
|
|
|
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) |
|
|
|
|
|
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: |
|
|
|
st.subheader("π Stock Price Trends") |
|
st.plotly_chart(create_candlestick_chart(stock_data), use_container_width=True) |
|
|
|
|
|
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) |
|
|
|
|
|
st.subheader("πΌ Personalized Trading Strategy") |
|
strategy = develop_trading_strategies(stock_selection, risk_tolerance, trading_strategy_preference, |
|
stock_data) |
|
st.success(strategy) |
|
|
|
|
|
st.subheader("π Smart Execution Plan") |
|
plan = plan_trade_execution(stock_selection, initial_capital, risk_tolerance, stock_data) |
|
st.info(plan) |
|
|
|
|
|
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']})") |
|
|
|
|
|
st.subheader("π² Advanced Portfolio Simulation") |
|
|
|
num_simulations = 1000 |
|
time_horizon = 252 |
|
|
|
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}") |
|
|
|
|
|
fig = go.Figure() |
|
for i in range(min(100, num_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 |
|
|
|
|
|
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) |
|
|
|
|
|
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.") |
|
|