Update app.py
Browse files
app.py
CHANGED
@@ -7,15 +7,12 @@ import yfinance as yf
|
|
7 |
import plotly.graph_objects as go
|
8 |
import plotly.express as px
|
9 |
from datetime import datetime, timedelta
|
10 |
-
import groq
|
11 |
from scipy import stats
|
12 |
-
|
|
|
13 |
# Set page title and configuration
|
14 |
st.set_page_config(page_title="Theaimart Stock Analysis", page_icon="π", layout="wide")
|
15 |
|
16 |
-
# Initialize Groq client
|
17 |
-
groq_client = groq.Groq(api_key="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")
|
18 |
-
|
19 |
# Enhanced Custom CSS
|
20 |
st.markdown("""
|
21 |
<style>
|
@@ -100,32 +97,6 @@ st.markdown("""
|
|
100 |
</style>
|
101 |
""", unsafe_allow_html=True)
|
102 |
|
103 |
-
|
104 |
-
@st.cache_data(ttl=3600)
|
105 |
-
def get_stock_overview(stock):
|
106 |
-
prompt = f"""
|
107 |
-
Provide a concise, factual overview of {stock} stock, including:
|
108 |
-
1. Brief company description
|
109 |
-
2. Key recent developments (last 6 months)
|
110 |
-
3. Major strengths and potential risks
|
111 |
-
Base your response on widely accepted financial data and recent news.
|
112 |
-
Limit the response to 5 sentences and avoid speculative statements.
|
113 |
-
"""
|
114 |
-
try:
|
115 |
-
response = groq_client.chat.completions.create(
|
116 |
-
messages=[
|
117 |
-
{"role": "system", "content": "You are a financial analyst providing brief, factual stock overviews."},
|
118 |
-
{"role": "user", "content": prompt}
|
119 |
-
],
|
120 |
-
model="mixtral-8x7b-32768",
|
121 |
-
max_tokens=200
|
122 |
-
)
|
123 |
-
return response.choices[0].message.content
|
124 |
-
except Exception as e:
|
125 |
-
st.error(f"Error fetching stock overview: {str(e)}")
|
126 |
-
return "Unable to fetch stock overview at this time."
|
127 |
-
|
128 |
-
|
129 |
@st.cache_data(ttl=3600)
|
130 |
def search_google(query):
|
131 |
url = f"https://www.google.com/search?q={query}"
|
@@ -145,7 +116,6 @@ def search_google(query):
|
|
145 |
st.error(f"Error fetching news: {str(e)}")
|
146 |
return []
|
147 |
|
148 |
-
|
149 |
@st.cache_data(ttl=3600)
|
150 |
def fetch_stock_data(ticker, period="2y"):
|
151 |
try:
|
@@ -158,7 +128,6 @@ def fetch_stock_data(ticker, period="2y"):
|
|
158 |
st.error(f"Error fetching stock data: {str(e)}")
|
159 |
return pd.DataFrame()
|
160 |
|
161 |
-
|
162 |
def analyze_market_data(stock_data):
|
163 |
if stock_data.empty:
|
164 |
return "Insufficient data for analysis."
|
@@ -182,7 +151,6 @@ def analyze_market_data(stock_data):
|
|
182 |
- All-Time Low: ${low_price:.2f}
|
183 |
"""
|
184 |
|
185 |
-
|
186 |
def develop_trading_strategies(stock, risk_tolerance, strategy_preference, stock_data):
|
187 |
if stock_data.empty:
|
188 |
return "Insufficient data for strategy development."
|
@@ -199,20 +167,12 @@ def develop_trading_strategies(stock, risk_tolerance, strategy_preference, stock
|
|
199 |
- Sharpe Ratio: {sharpe_ratio:.2f}
|
200 |
Provide a concise, fact-based strategy in 3-4 sentences, avoiding speculative advice.
|
201 |
"""
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
model="mixtral-8x7b-32768",
|
209 |
-
max_tokens=150
|
210 |
-
)
|
211 |
-
return response.choices[0].message.content
|
212 |
-
except Exception as e:
|
213 |
-
st.error(f"Error developing trading strategy: {str(e)}")
|
214 |
-
return "Unable to develop trading strategy at this time."
|
215 |
-
|
216 |
|
217 |
def plan_trade_execution(stock, initial_capital, risk_tolerance, stock_data):
|
218 |
if stock_data.empty:
|
@@ -243,7 +203,6 @@ def plan_trade_execution(stock, initial_capital, risk_tolerance, stock_data):
|
|
243 |
- Max Position Size: {(risk_amount / (last_price - stop_loss)):.0f} shares
|
244 |
"""
|
245 |
|
246 |
-
|
247 |
def assess_trading_risks(stock, stock_data):
|
248 |
if stock_data.empty:
|
249 |
return "Insufficient data for risk assessment."
|
@@ -294,7 +253,6 @@ def assess_trading_risks(stock, stock_data):
|
|
294 |
|
295 |
return risk_metrics, heatmap
|
296 |
|
297 |
-
|
298 |
def create_candlestick_chart(stock_data):
|
299 |
fig = go.Figure(data=[go.Candlestick(x=stock_data.index,
|
300 |
open=stock_data['Open'],
|
@@ -311,7 +269,6 @@ def create_candlestick_chart(stock_data):
|
|
311 |
)
|
312 |
return fig
|
313 |
|
314 |
-
|
315 |
@st.cache_data
|
316 |
def run_monte_carlo_simulation(stock_data, initial_investment, num_simulations, time_horizon):
|
317 |
returns = stock_data['Close'].pct_change().dropna()
|
@@ -329,7 +286,6 @@ def run_monte_carlo_simulation(stock_data, initial_investment, num_simulations,
|
|
329 |
|
330 |
return simulations
|
331 |
|
332 |
-
|
333 |
# Streamlit app
|
334 |
st.title("π Theaimart Stock Investment Analysis")
|
335 |
|
@@ -349,8 +305,6 @@ with col2:
|
|
349 |
|
350 |
news_impact_consideration = st.checkbox("Consider News Impact", value=True)
|
351 |
|
352 |
-
# ... [previous code remains the same] ...
|
353 |
-
|
354 |
if st.button("π Run In-Depth Analysis"):
|
355 |
st.session_state['run_clicked'] = True
|
356 |
|
@@ -375,11 +329,6 @@ if st.session_state.get('run_clicked', False):
|
|
375 |
stock_data = fetch_stock_data(stock_selection)
|
376 |
|
377 |
if not stock_data.empty:
|
378 |
-
# Stock Overview
|
379 |
-
st.subheader("π Stock Overview")
|
380 |
-
overview = get_stock_overview(stock_selection)
|
381 |
-
st.markdown(f'<div class="overview-card">{overview}</div>', unsafe_allow_html=True)
|
382 |
-
|
383 |
# Stock Price Chart
|
384 |
st.subheader("π Stock Price Trends")
|
385 |
st.plotly_chart(create_candlestick_chart(stock_data), use_container_width=True)
|
@@ -486,4 +435,4 @@ st.markdown("""
|
|
486 |
|
487 |
# Footer
|
488 |
st.markdown('<div class="footer">Β© Theaimart 2024 | Advanced Stock Analysis Tool</div>', unsafe_allow_html=True)
|
489 |
-
st.caption("Powered by cutting-edge AI and real-time financial data analysis.")
|
|
|
7 |
import plotly.graph_objects as go
|
8 |
import plotly.express as px
|
9 |
from datetime import datetime, timedelta
|
|
|
10 |
from scipy import stats
|
11 |
+
import os
|
12 |
+
|
13 |
# Set page title and configuration
|
14 |
st.set_page_config(page_title="Theaimart Stock Analysis", page_icon="π", layout="wide")
|
15 |
|
|
|
|
|
|
|
16 |
# Enhanced Custom CSS
|
17 |
st.markdown("""
|
18 |
<style>
|
|
|
97 |
</style>
|
98 |
""", unsafe_allow_html=True)
|
99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
@st.cache_data(ttl=3600)
|
101 |
def search_google(query):
|
102 |
url = f"https://www.google.com/search?q={query}"
|
|
|
116 |
st.error(f"Error fetching news: {str(e)}")
|
117 |
return []
|
118 |
|
|
|
119 |
@st.cache_data(ttl=3600)
|
120 |
def fetch_stock_data(ticker, period="2y"):
|
121 |
try:
|
|
|
128 |
st.error(f"Error fetching stock data: {str(e)}")
|
129 |
return pd.DataFrame()
|
130 |
|
|
|
131 |
def analyze_market_data(stock_data):
|
132 |
if stock_data.empty:
|
133 |
return "Insufficient data for analysis."
|
|
|
151 |
- All-Time Low: ${low_price:.2f}
|
152 |
"""
|
153 |
|
|
|
154 |
def develop_trading_strategies(stock, risk_tolerance, strategy_preference, stock_data):
|
155 |
if stock_data.empty:
|
156 |
return "Insufficient data for strategy development."
|
|
|
167 |
- Sharpe Ratio: {sharpe_ratio:.2f}
|
168 |
Provide a concise, fact-based strategy in 3-4 sentences, avoiding speculative advice.
|
169 |
"""
|
170 |
+
# Here you should implement the logic to develop trading strategies based on the given parameters
|
171 |
+
return f"""
|
172 |
+
- Volatility: {volatility:.2f}
|
173 |
+
- Sharpe Ratio: {sharpe_ratio:.2f}
|
174 |
+
- 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.
|
175 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
176 |
|
177 |
def plan_trade_execution(stock, initial_capital, risk_tolerance, stock_data):
|
178 |
if stock_data.empty:
|
|
|
203 |
- Max Position Size: {(risk_amount / (last_price - stop_loss)):.0f} shares
|
204 |
"""
|
205 |
|
|
|
206 |
def assess_trading_risks(stock, stock_data):
|
207 |
if stock_data.empty:
|
208 |
return "Insufficient data for risk assessment."
|
|
|
253 |
|
254 |
return risk_metrics, heatmap
|
255 |
|
|
|
256 |
def create_candlestick_chart(stock_data):
|
257 |
fig = go.Figure(data=[go.Candlestick(x=stock_data.index,
|
258 |
open=stock_data['Open'],
|
|
|
269 |
)
|
270 |
return fig
|
271 |
|
|
|
272 |
@st.cache_data
|
273 |
def run_monte_carlo_simulation(stock_data, initial_investment, num_simulations, time_horizon):
|
274 |
returns = stock_data['Close'].pct_change().dropna()
|
|
|
286 |
|
287 |
return simulations
|
288 |
|
|
|
289 |
# Streamlit app
|
290 |
st.title("π Theaimart Stock Investment Analysis")
|
291 |
|
|
|
305 |
|
306 |
news_impact_consideration = st.checkbox("Consider News Impact", value=True)
|
307 |
|
|
|
|
|
308 |
if st.button("π Run In-Depth Analysis"):
|
309 |
st.session_state['run_clicked'] = True
|
310 |
|
|
|
329 |
stock_data = fetch_stock_data(stock_selection)
|
330 |
|
331 |
if not stock_data.empty:
|
|
|
|
|
|
|
|
|
|
|
332 |
# Stock Price Chart
|
333 |
st.subheader("π Stock Price Trends")
|
334 |
st.plotly_chart(create_candlestick_chart(stock_data), use_container_width=True)
|
|
|
435 |
|
436 |
# Footer
|
437 |
st.markdown('<div class="footer">Β© Theaimart 2024 | Advanced Stock Analysis Tool</div>', unsafe_allow_html=True)
|
438 |
+
st.caption("Powered by cutting-edge AI and real-time financial data analysis.")
|