shaheerawan3 commited on
Commit
638732f
Β·
verified Β·
1 Parent(s): efbadd7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -81
app.py CHANGED
@@ -8,8 +8,8 @@ import requests
8
  from bs4 import BeautifulSoup
9
  import pandas_ta as ta
10
  from pypfopt import EfficientFrontier, risk_models, expected_returns
11
- from prophet import Prophet
12
- from statsmodels.tsa.arima.model import ARIMA
13
  import warnings
14
 
15
  warnings.filterwarnings("ignore")
@@ -43,8 +43,6 @@ class EnhancedTechnicalAnalysis:
43
  if self.model:
44
  preds = self.model.predict(self.data[['Close']].values)
45
  self.data['DL_Prediction'] = preds.flatten()
46
- else:
47
- self.data['DL_Prediction'] = self._fallback_prediction()
48
  self.data['Volatility_Cluster'] = self._detect_volatility_clusters()
49
  return self.data.dropna(axis=1, how='all')
50
  except Exception as e:
@@ -55,34 +53,6 @@ class EnhancedTechnicalAnalysis:
55
  returns = self.data['Close'].pct_change()
56
  return (returns.rolling(20).std() > returns.std()).astype(int)
57
 
58
- def _fallback_prediction(self) -> pd.Series:
59
- # Fallback prediction using ARIMA
60
- try:
61
- model = ARIMA(self.data['Close'], order=(5, 1, 0))
62
- model_fit = model.fit()
63
- future_preds = model_fit.forecast(steps=5)
64
- return pd.Series(future_preds, index=self.data.index[-5:])
65
- except:
66
- return pd.Series([self.data['Close'].iloc[-1]] * 5, index=self.data.index[-5:])
67
-
68
- def predict_future_prices(self, n_days: int = 5) -> pd.DataFrame:
69
- try:
70
- if self.model is None:
71
- st.warning("No deep learning model available for predictions. Using fallback method.")
72
- preds = self._fallback_prediction()
73
- else:
74
- last_close = self.data['Close'].values[-1]
75
- preds = []
76
- for _ in range(n_days):
77
- pred = self.model.predict(np.array([[last_close]]))
78
- preds.append(pred[0][0])
79
- last_close = pred[0][0] # Update last close for next prediction
80
- future_dates = pd.date_range(start=self.data.index[-1] + timedelta(days=1), periods=n_days)
81
- return pd.DataFrame({'Date': future_dates, 'Predicted_Close': preds})
82
- except Exception as e:
83
- st.error(f"Prediction failed: {str(e)}")
84
- return pd.DataFrame()
85
-
86
  # Market Data Integrator
87
  class MarketDataIntegrator:
88
  """Enhanced market data integration with fixed market movers"""
@@ -93,6 +63,7 @@ class MarketDataIntegrator:
93
 
94
  def get_market_movers(self) -> Dict:
95
  try:
 
96
  gainers = yf.Ticker("^GSPC").info.get('most_actively_traded', [])[:5]
97
  losers = yf.Ticker("^GSPC").info.get('most_actively_traded', [])[-5:]
98
  active = yf.Ticker("^GSPC").info.get('most_actively_traded', [])[:5]
@@ -231,7 +202,7 @@ class TradingAssistant:
231
  # Main Application
232
  def main():
233
  st.set_page_config(page_title="AI Trading Pro", layout="wide", page_icon="πŸ“ˆ")
234
- st.title("πŸš€ AI Trading Pro - Advanced Trading Solution")
235
 
236
  market_data = MarketDataIntegrator()
237
  trading_engine = TradingAssistant()
@@ -242,14 +213,12 @@ def main():
242
  asset_type = st.selectbox("Asset Class", list(trading_engine.asset_options.keys()))
243
  symbol = st.selectbox("Symbol", trading_engine.asset_options[asset_type])
244
  timeframe = st.select_slider("Analysis Period", options=["1D", "1W", "1M", "3M", "1Y"], value="1M")
245
- prediction_days = st.slider("Prediction Horizon (Days)", 1, 30, 5)
246
- capital = st.number_input("Initial Capital ($)", min_value=100, value=10000)
247
- enable_portfolio = st.checkbox("Portfolio Optimization")
248
- show_education = st.checkbox("Tutorial Mode")
249
- risk_level = st.select_slider("Risk Profile", ["Low", "Medium", "High"])
250
- contact_info = st.text("πŸ“ž Contact: +0335-xxxxxxx")
251
 
252
- tab_analysis, tab_prediction, tab_portfolio, tab_learn = st.tabs(["Analysis", "Prediction", "Portfolio", "Academy"])
253
 
254
  with tab_analysis:
255
  if st.button("Run Analysis"):
@@ -259,6 +228,14 @@ def main():
259
  if data.empty:
260
  st.error("No data available for the selected symbol and timeframe.")
261
  return
 
 
 
 
 
 
 
 
262
  fig = go.Figure()
263
  fig.add_trace(go.Candlestick(
264
  x=data.index,
@@ -270,50 +247,21 @@ def main():
270
  ))
271
  fig.update_layout(height=600, xaxis_rangeslider_visible=False)
272
  st.plotly_chart(fig, use_container_width=True)
273
- st.write("### Technical Indicators")
274
- analysis = EnhancedTechnicalAnalysis(data).calculate_all_indicators()
275
- st.dataframe(analysis.tail())
 
 
 
 
 
 
 
 
 
276
  except Exception as e:
277
  st.error(f"Analysis failed: {str(e)}")
278
 
279
- with tab_prediction:
280
- if st.button("Generate Predictions"):
281
- with st.spinner("Generating predictions..."):
282
- try:
283
- data = yf.download(symbol, period="1y")
284
- if data.empty:
285
- st.error("No data available for the selected symbol.")
286
- return
287
- analyzer = EnhancedTechnicalAnalysis(data)
288
- future_prices = analyzer.predict_future_prices(prediction_days)
289
- if future_prices.empty:
290
- st.warning("No predictions available.")
291
- return
292
- fig = go.Figure()
293
- fig.add_trace(go.Scatter(
294
- x=data.index,
295
- y=data['Close'],
296
- mode='lines',
297
- name='Historical Prices'
298
- ))
299
- fig.add_trace(go.Scatter(
300
- x=future_prices['Date'],
301
- y=future_prices['Predicted_Close'],
302
- mode='lines',
303
- name='Predicted Prices'
304
- ))
305
- fig.update_layout(
306
- title="Historical and Predicted Prices",
307
- height=600,
308
- xaxis_title="Date",
309
- yaxis_title="Price"
310
- )
311
- st.plotly_chart(fig, use_container_width=True)
312
- st.write("### Future Price Predictions")
313
- st.dataframe(future_prices)
314
- except Exception as e:
315
- st.error(f"Prediction failed: {str(e)}")
316
-
317
  with tab_portfolio:
318
  if enable_portfolio:
319
  st.subheader("βš–οΈ Portfolio Optimization")
 
8
  from bs4 import BeautifulSoup
9
  import pandas_ta as ta
10
  from pypfopt import EfficientFrontier, risk_models, expected_returns
11
+ from typing import Dict
12
+ import tensorflow as tf
13
  import warnings
14
 
15
  warnings.filterwarnings("ignore")
 
43
  if self.model:
44
  preds = self.model.predict(self.data[['Close']].values)
45
  self.data['DL_Prediction'] = preds.flatten()
 
 
46
  self.data['Volatility_Cluster'] = self._detect_volatility_clusters()
47
  return self.data.dropna(axis=1, how='all')
48
  except Exception as e:
 
53
  returns = self.data['Close'].pct_change()
54
  return (returns.rolling(20).std() > returns.std()).astype(int)
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  # Market Data Integrator
57
  class MarketDataIntegrator:
58
  """Enhanced market data integration with fixed market movers"""
 
63
 
64
  def get_market_movers(self) -> Dict:
65
  try:
66
+ # Using Yahoo Finance API for more reliable data
67
  gainers = yf.Ticker("^GSPC").info.get('most_actively_traded', [])[:5]
68
  losers = yf.Ticker("^GSPC").info.get('most_actively_traded', [])[-5:]
69
  active = yf.Ticker("^GSPC").info.get('most_actively_traded', [])[:5]
 
202
  # Main Application
203
  def main():
204
  st.set_page_config(page_title="AI Trading Pro", layout="wide", page_icon="πŸ“ˆ")
205
+ st.title("πŸš€ AI Trading Pro - Enhanced Trading Solution")
206
 
207
  market_data = MarketDataIntegrator()
208
  trading_engine = TradingAssistant()
 
213
  asset_type = st.selectbox("Asset Class", list(trading_engine.asset_options.keys()))
214
  symbol = st.selectbox("Symbol", trading_engine.asset_options[asset_type])
215
  timeframe = st.select_slider("Analysis Period", options=["1D", "1W", "1M", "3M", "1Y"], value="1M")
216
+ with st.expander("πŸ”§ Advanced Tools"):
217
+ enable_portfolio = st.checkbox("Portfolio Optimization")
218
+ show_education = st.checkbox("Tutorial Mode")
219
+ risk_level = st.select_slider("Risk Profile", ["Low", "Medium", "High"])
 
 
220
 
221
+ tab_analysis, tab_portfolio, tab_learn = st.tabs(["Analysis", "Portfolio", "Academy"])
222
 
223
  with tab_analysis:
224
  if st.button("Run Analysis"):
 
228
  if data.empty:
229
  st.error("No data available for the selected symbol and timeframe.")
230
  return
231
+ analysis = trading_engine.generate_signal(symbol, data)
232
+ movers = market_data.get_market_movers()
233
+ sentiment = market_data.get_market_sentiment(symbol)
234
+ col1, col2, col3, col4 = st.columns(4)
235
+ col1.metric("Price", f"${data['Close'].iloc[-1]:.2f}")
236
+ col2.metric("Signal", analysis['signal'])
237
+ col3.metric("RSI", f"{analysis['details']['RSI']:.1f}")
238
+ col4.metric("Sentiment", f"{sentiment:.2f}")
239
  fig = go.Figure()
240
  fig.add_trace(go.Candlestick(
241
  x=data.index,
 
247
  ))
248
  fig.update_layout(height=600, xaxis_rangeslider_visible=False)
249
  st.plotly_chart(fig, use_container_width=True)
250
+ with st.expander("πŸ“ˆ Market Movers"):
251
+ cols = st.columns(3)
252
+ cols[0].subheader("Top Gainers")
253
+ cols[1].subheader("Top Losers")
254
+ cols[2].subheader("Most Active")
255
+ for i in range(5):
256
+ if i < len(movers['gainers']):
257
+ cols[0].write(f"{i+1}. {movers['gainers'][i]}")
258
+ if i < len(movers['losers']):
259
+ cols[1].write(f"{i+1}. {movers['losers'][i]}")
260
+ if i < len(movers['active']):
261
+ cols[2].write(f"{i+1}. {movers['active'][i]}")
262
  except Exception as e:
263
  st.error(f"Analysis failed: {str(e)}")
264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  with tab_portfolio:
266
  if enable_portfolio:
267
  st.subheader("βš–οΈ Portfolio Optimization")