Spaces:
Sleeping
Sleeping
import os | |
import asyncio | |
import logging | |
from datetime import datetime, timedelta | |
from newsapi.newsapi_client import NewsApiClient | |
from textblob import TextBlob | |
import yfinance as yf | |
import pandas as pd | |
import ta | |
import gradio as gr | |
# Set up logging | |
logging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s') | |
# Retrieve API key from environment variables | |
NEWSAPI_KEY = os.getenv("NEWSAPI_KEY") | |
# Fetch financial news | |
def fetch_financial_news(stock_symbol=None, page_size=5, days=2): | |
try: | |
newsapi = NewsApiClient(api_key=NEWSAPI_KEY) | |
query = stock_symbol if stock_symbol else "financial news" | |
end_date = datetime.now() | |
start_date = end_date - timedelta(days=days) | |
articles = newsapi.get_everything( | |
q=query, | |
language='en', | |
from_param=start_date.strftime('%Y-%m-%d'), | |
to=end_date.strftime('%Y-%m-%d'), | |
sort_by='publishedAt', | |
page_size=page_size | |
) | |
results = [] | |
for article in articles.get('articles', []): | |
title = article.get('title', '[Title Unavailable]') | |
description = article.get('description', '[Description Unavailable]') | |
url = article.get('url', 'URL Unavailable') | |
results.append(f"Title: {title}\nDescription: {description}\nURL: {url}") | |
return "\n\n".join(results) | |
except Exception as e: | |
return f"Error fetching news: {e}" | |
# Perform sentiment analysis | |
def analyze_sentiment(text): | |
try: | |
analysis = TextBlob(text) | |
polarity = analysis.sentiment.polarity | |
if polarity > 0.1: | |
return "Positive" | |
elif polarity < -0.1: | |
return "Negative" | |
else: | |
return "Neutral" | |
except Exception as e: | |
return f"Error analyzing sentiment: {e}" | |
# Fetch technical data | |
def fetch_technical_data(stock_symbol): | |
try: | |
stock = yf.Ticker(stock_symbol) | |
data = stock.history(period="1y") | |
if data.empty: | |
return "No data found for this stock symbol." | |
data['RSI'] = ta.momentum.RSIIndicator(data['Close']).rsi() | |
macd = ta.trend.MACD(data['Close']) | |
data['MACD'] = macd.macd() | |
data['MACD_Signal'] = macd.macd_signal() | |
data['SMA_50'] = data['Close'].rolling(window=50).mean() | |
data['SMA_200'] = data['Close'].rolling(window=200).mean() | |
latest_technical_data = { | |
"RSI": data['RSI'].iloc[-1], | |
"MACD": data['MACD'].iloc[-1], | |
"MACD Signal": data['MACD_Signal'].iloc[-1], | |
"50 Day SMA": data['SMA_50'].iloc[-1], | |
"200 Day SMA": data['SMA_200'].iloc[-1], | |
} | |
return pd.Series(latest_technical_data).to_string() | |
except Exception as e: | |
return f"Error fetching technical data: {e}" | |
# Define Gradio interface | |
def analyze_stock(stock_symbol): | |
news = fetch_financial_news(stock_symbol) | |
technical_data = fetch_technical_data(stock_symbol) | |
return news, technical_data | |
with gr.Blocks() as demo: | |
gr.Markdown("## Financial News and Technical Analysis Tool") | |
stock_input = gr.Textbox(label="Enter Stock Symbol (e.g., AAPL, TSLA)") | |
news_output = gr.Textbox(label="Financial News", interactive=False) | |
tech_output = gr.Textbox(label="Technical Analysis", interactive=False) | |
analyze_button = gr.Button("Analyze") | |
analyze_button.click(analyze_stock, inputs=[stock_input], outputs=[news_output, tech_output]) | |
if __name__ == "__main__": | |
demo.launch() | |