Benjamin Consolvo commited on
Commit
1c9aec6
·
1 Parent(s): b44b4b2

yfinance headlines

Browse files
Files changed (1) hide show
  1. app.py +42 -54
app.py CHANGED
@@ -357,6 +357,48 @@ class TradingApp:
357
  st.header("Manual Trade")
358
  symbol = st.text_input('Enter stock symbol')
359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  # Fetch the current stock price dynamically using Alpaca's API
361
  def get_stock_price(symbol):
362
  try:
@@ -416,60 +458,6 @@ class TradingApp:
416
  else:
417
  st.error("Please enter a valid stock symbol and trade details.")
418
 
419
- # --- Sentiment Check Feature ---
420
- sentiment_result = None
421
- article_headlines = []
422
- if st.button("Check Sentiment"):
423
- if symbol:
424
- try:
425
- # Use NewsSentiment to get sentiment and articles
426
- sentiment_dict = self.sentiment.get_news_sentiment([symbol])
427
- sentiment_result = sentiment_dict.get(symbol)
428
- # Try to fetch article headlines
429
- try:
430
- articles = self.sentiment.newsapi.get_everything(q=symbol, language='en', sort_by='publishedAt', page=1)
431
- article_headlines = [a['title'] for a in articles.get('articles', [])[:5]]
432
- except Exception as e:
433
- article_headlines = []
434
- except Exception as e:
435
- sentiment_result = None
436
- article_headlines = []
437
- else:
438
- sentiment_result = None
439
- article_headlines = []
440
-
441
- if sentiment_result is not None:
442
- st.markdown(f"**Sentiment for {symbol.upper()}:** {sentiment_result if sentiment_result in ['Positive', 'Negative', 'Neutral'] else 'No sentiment available'}")
443
- elif sentiment_result is None and st.session_state.get("Check Sentiment"):
444
- st.markdown("**Sentiment:** No sentiment available")
445
-
446
- if article_headlines:
447
- st.markdown("**Recent Headlines:**")
448
- for headline in article_headlines:
449
- st.write(f"- {headline}")
450
- elif sentiment_result is not None and not article_headlines:
451
- st.markdown("_No headlines available._")
452
-
453
- # Display portfolio information in the sidebar
454
- st.header("Alpaca Cash Portfolio")
455
-
456
- def refresh_portfolio():
457
- account = self.alpaca.alpaca.get_account()
458
- portfolio_data = {
459
- "Metric": ["Cash Balance", "Buying Power", "Equity", "Portfolio Value"],
460
- "Value": [
461
- f"${int(float(account.cash)):,.0f}",
462
- f"${int(float(account.buying_power)):,.0f}",
463
- f"${int(float(account.equity)):,.0f}",
464
- f"${int(float(account.portfolio_value)):,.0f}"
465
- ]
466
- }
467
- df = pd.DataFrame(portfolio_data)
468
- st.table(df.to_dict(orient="records")) # Convert DataFrame to a list of dictionaries
469
-
470
- refresh_portfolio()
471
- st.button("Refresh Portfolio", on_click=refresh_portfolio)
472
-
473
  def auto_trade_based_on_sentiment(self, sentiment):
474
  """Execute trades based on sentiment analysis and return actions taken."""
475
  actions = self._execute_sentiment_trades(sentiment)
 
357
  st.header("Manual Trade")
358
  symbol = st.text_input('Enter stock symbol')
359
 
360
+ # --- Sentiment Check Feature (moved up) ---
361
+ sentiment_result = None
362
+ article_headlines = []
363
+ if st.button("Check Sentiment"):
364
+ if symbol:
365
+ try:
366
+ # Use NewsSentiment to get sentiment
367
+ sentiment_dict = self.sentiment.get_news_sentiment([symbol])
368
+ sentiment_result = sentiment_dict.get(symbol)
369
+ # Try NewsAPI headlines first, fallback to yfinance if fails
370
+ try:
371
+ articles = self.sentiment.newsapi.get_everything(q=symbol, language='en', sort_by='publishedAt', page=1)
372
+ article_headlines = [a['title'] for a in articles.get('articles', [])[:5]]
373
+ if not article_headlines:
374
+ raise Exception("No NewsAPI headlines")
375
+ except Exception:
376
+ # Fallback to yfinance headlines
377
+ try:
378
+ ticker = yf.Ticker(symbol)
379
+ news_items = ticker.news if hasattr(ticker, "news") else []
380
+ article_headlines = [item.get('title') for item in news_items[:5] if item.get('title')]
381
+ except Exception:
382
+ article_headlines = []
383
+ except Exception as e:
384
+ sentiment_result = None
385
+ article_headlines = []
386
+ else:
387
+ sentiment_result = None
388
+ article_headlines = []
389
+
390
+ if sentiment_result is not None:
391
+ st.markdown(f"**Sentiment for {symbol.upper()}:** {sentiment_result if sentiment_result in ['Positive', 'Negative', 'Neutral'] else 'No sentiment available'}")
392
+ elif sentiment_result is None and st.session_state.get("Check Sentiment"):
393
+ st.markdown("**Sentiment:** No sentiment available")
394
+
395
+ if article_headlines:
396
+ st.markdown("**Recent Headlines:**")
397
+ for headline in article_headlines:
398
+ st.write(f"- {headline}")
399
+ elif sentiment_result is not None and not article_headlines:
400
+ st.markdown("_No headlines available._")
401
+
402
  # Fetch the current stock price dynamically using Alpaca's API
403
  def get_stock_price(symbol):
404
  try:
 
458
  else:
459
  st.error("Please enter a valid stock symbol and trade details.")
460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  def auto_trade_based_on_sentiment(self, sentiment):
462
  """Execute trades based on sentiment analysis and return actions taken."""
463
  actions = self._execute_sentiment_trades(sentiment)