Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
import os
|
| 2 |
-
import asyncio
|
| 3 |
import logging
|
| 4 |
from datetime import datetime, timedelta
|
| 5 |
from newsapi.newsapi_client import NewsApiClient
|
|
@@ -8,15 +7,40 @@ import yfinance as yf
|
|
| 8 |
import pandas as pd
|
| 9 |
import ta
|
| 10 |
import gradio as gr
|
|
|
|
| 11 |
|
| 12 |
# Set up logging
|
| 13 |
logging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 14 |
|
| 15 |
-
# Retrieve API
|
| 16 |
NEWSAPI_KEY = os.getenv("NEWSAPI_KEY")
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
try:
|
| 21 |
newsapi = NewsApiClient(api_key=NEWSAPI_KEY)
|
| 22 |
query = stock_symbol if stock_symbol else "financial news"
|
|
@@ -32,16 +56,21 @@ def fetch_financial_news(stock_symbol=None, page_size=5, days=2):
|
|
| 32 |
page_size=page_size
|
| 33 |
)
|
| 34 |
|
| 35 |
-
|
|
|
|
|
|
|
| 36 |
for article in articles.get('articles', []):
|
| 37 |
title = article.get('title', '[Title Unavailable]')
|
| 38 |
description = article.get('description', '[Description Unavailable]')
|
| 39 |
url = article.get('url', 'URL Unavailable')
|
| 40 |
-
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
except Exception as e:
|
| 44 |
-
return f"Error fetching news: {e}"
|
| 45 |
|
| 46 |
# Perform sentiment analysis
|
| 47 |
def analyze_sentiment(text):
|
|
@@ -85,20 +114,53 @@ def fetch_technical_data(stock_symbol):
|
|
| 85 |
except Exception as e:
|
| 86 |
return f"Error fetching technical data: {e}"
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
# Define Gradio interface
|
| 89 |
def analyze_stock(stock_symbol):
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
| 93 |
|
| 94 |
with gr.Blocks() as demo:
|
| 95 |
gr.Markdown("## Financial News and Technical Analysis Tool")
|
| 96 |
-
stock_input = gr.Textbox(label="Enter Stock Symbol (e.g., AAPL, TSLA)")
|
| 97 |
-
news_output = gr.Textbox(label="Financial News", interactive=False)
|
| 98 |
-
tech_output = gr.Textbox(label="Technical Analysis", interactive=False)
|
| 99 |
-
analyze_button = gr.Button("Analyze")
|
| 100 |
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
if __name__ == "__main__":
|
| 104 |
demo.launch()
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import logging
|
| 3 |
from datetime import datetime, timedelta
|
| 4 |
from newsapi.newsapi_client import NewsApiClient
|
|
|
|
| 7 |
import pandas as pd
|
| 8 |
import ta
|
| 9 |
import gradio as gr
|
| 10 |
+
from groq import Groq
|
| 11 |
|
| 12 |
# Set up logging
|
| 13 |
logging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 14 |
|
| 15 |
+
# Retrieve API keys from environment variables
|
| 16 |
NEWSAPI_KEY = os.getenv("NEWSAPI_KEY")
|
| 17 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 18 |
+
|
| 19 |
+
# Initialize Groq client
|
| 20 |
+
groq_client = Groq(api_key=GROQ_API_KEY)
|
| 21 |
+
|
| 22 |
+
# Use Groq's Llama 3 model for decision making
|
| 23 |
+
MODEL = "llama3-70b-8192"
|
| 24 |
+
|
| 25 |
+
# Define the list of companies and their stock symbols
|
| 26 |
+
top_companies = [
|
| 27 |
+
{"name": "Tesla", "symbol": "TSLA"},
|
| 28 |
+
{"name": "Meta (Facebook)", "symbol": "META"},
|
| 29 |
+
{"name": "Visa", "symbol": "V"},
|
| 30 |
+
{"name": "Procter & Gamble", "symbol": "PG"},
|
| 31 |
+
{"name": "Coca-Cola", "symbol": "KO"},
|
| 32 |
+
{"name": "NVIDIA", "symbol": "NVDA"},
|
| 33 |
+
{"name": "Johnson & Johnson", "symbol": "JNJ"},
|
| 34 |
+
{"name": "Exxon Mobil", "symbol": "XOM"},
|
| 35 |
+
{"name": "Apple", "symbol": "AAPL"},
|
| 36 |
+
{"name": "Microsoft", "symbol": "MSFT"},
|
| 37 |
+
{"name": "Amazon", "symbol": "AMZN"},
|
| 38 |
+
{"name": "Google (Alphabet)", "symbol": "GOOGL"},
|
| 39 |
+
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
# Fetch financial news with sentiment analysis
|
| 43 |
+
def fetch_financial_news_with_sentiment(stock_symbol=None, page_size=5, days=1):
|
| 44 |
try:
|
| 45 |
newsapi = NewsApiClient(api_key=NEWSAPI_KEY)
|
| 46 |
query = stock_symbol if stock_symbol else "financial news"
|
|
|
|
| 56 |
page_size=page_size
|
| 57 |
)
|
| 58 |
|
| 59 |
+
news_results = []
|
| 60 |
+
sentiment_results = []
|
| 61 |
+
|
| 62 |
for article in articles.get('articles', []):
|
| 63 |
title = article.get('title', '[Title Unavailable]')
|
| 64 |
description = article.get('description', '[Description Unavailable]')
|
| 65 |
url = article.get('url', 'URL Unavailable')
|
| 66 |
+
sentiment = analyze_sentiment(title) if title else "Neutral"
|
| 67 |
|
| 68 |
+
news_results.append(f"Title: {title}\nDescription: {description}\nURL: {url}")
|
| 69 |
+
sentiment_results.append(f"Sentiment: {sentiment}")
|
| 70 |
+
|
| 71 |
+
return "\n\n".join(news_results), "\n\n".join(sentiment_results)
|
| 72 |
except Exception as e:
|
| 73 |
+
return f"Error fetching news: {e}", ""
|
| 74 |
|
| 75 |
# Perform sentiment analysis
|
| 76 |
def analyze_sentiment(text):
|
|
|
|
| 114 |
except Exception as e:
|
| 115 |
return f"Error fetching technical data: {e}"
|
| 116 |
|
| 117 |
+
# Generate buy/hold/sell recommendation using Groq
|
| 118 |
+
def generate_recommendation(news, technical_data):
|
| 119 |
+
prompt = f"Based on the following news:\n{news}\nAnd the technical indicators:\n{technical_data}\nWhat would you recommend: Buy, Hold, or Sell? Provide a brief explanation."
|
| 120 |
+
|
| 121 |
+
response = groq_client.chat.completions.create(
|
| 122 |
+
model=MODEL,
|
| 123 |
+
messages=[
|
| 124 |
+
{"role": "system", "content": "You are a financial analyst providing stock recommendations."},
|
| 125 |
+
{"role": "user", "content": prompt}
|
| 126 |
+
],
|
| 127 |
+
max_tokens=150
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
return response.choices[0].message.content.strip()
|
| 131 |
+
|
| 132 |
# Define Gradio interface
|
| 133 |
def analyze_stock(stock_symbol):
|
| 134 |
+
symbol = stock_symbol.split('(')[-1].split(')')[0]
|
| 135 |
+
news, sentiment = fetch_financial_news_with_sentiment(symbol, days=1)
|
| 136 |
+
technical_data = fetch_technical_data(symbol)
|
| 137 |
+
recommendation = generate_recommendation(news, technical_data)
|
| 138 |
+
return news, sentiment, technical_data, recommendation
|
| 139 |
|
| 140 |
with gr.Blocks() as demo:
|
| 141 |
gr.Markdown("## Financial News and Technical Analysis Tool")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
+
with gr.Row():
|
| 144 |
+
stock_input = gr.Dropdown(
|
| 145 |
+
choices=[f"{company['name']} ({company['symbol']})" for company in top_companies],
|
| 146 |
+
label="Enter Stock Symbol (currently supports only a few companies)",
|
| 147 |
+
info="Select a company from the dropdown"
|
| 148 |
+
)
|
| 149 |
+
analyze_button = gr.Button("Analyze")
|
| 150 |
+
|
| 151 |
+
recommendation_output = gr.Textbox(label="Recommendation", interactive=False)
|
| 152 |
+
|
| 153 |
+
with gr.Row():
|
| 154 |
+
news_output = gr.Textbox(label="Financial News", interactive=False, lines=10)
|
| 155 |
+
sentiment_output = gr.Textbox(label="Sentiment Analysis", interactive=False, lines=10)
|
| 156 |
+
technical_output = gr.Textbox(label="Technical Analysis", interactive=False)
|
| 157 |
+
|
| 158 |
+
analyze_button.click(
|
| 159 |
+
analyze_stock,
|
| 160 |
+
inputs=[stock_input],
|
| 161 |
+
outputs=[news_output, sentiment_output, technical_output, recommendation_output]
|
| 162 |
+
)
|
| 163 |
|
| 164 |
if __name__ == "__main__":
|
| 165 |
demo.launch()
|
| 166 |
+
|