File size: 3,557 Bytes
9f841f8
 
 
 
 
 
 
 
 
05dd630
 
9f841f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05dd630
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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()