shivrajkarewar commited on
Commit
9f841f8
·
verified ·
1 Parent(s): 27a2d0d

Update app.py

Browse files

Added the News from NEWAPI + fetching Technical data from yf and then TA from Pandas TA. Integrated this code with the Gradio app for implementation on Huggingface.

Files changed (1) hide show
  1. app.py +99 -59
app.py CHANGED
@@ -1,64 +1,104 @@
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
  demo.launch()
 
1
+ import os
2
+ import asyncio
3
+ import logging
4
+ from datetime import datetime, timedelta
5
+ from newsapi.newsapi_client import NewsApiClient
6
+ from textblob import TextBlob
7
+ 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 key from environment variables
16
+ NEWSAPI_KEY = os.getenv("NEWSAPI_KEY")
17
+
18
+ # Fetch financial news
19
+ def fetch_financial_news(stock_symbol=None, page_size=5, days=2):
20
+ try:
21
+ newsapi = NewsApiClient(api_key=NEWSAPI_KEY)
22
+ query = stock_symbol if stock_symbol else "financial news"
23
+ end_date = datetime.now()
24
+ start_date = end_date - timedelta(days=days)
25
+
26
+ articles = newsapi.get_everything(
27
+ q=query,
28
+ language='en',
29
+ from_param=start_date.strftime('%Y-%m-%d'),
30
+ to=end_date.strftime('%Y-%m-%d'),
31
+ sort_by='publishedAt',
32
+ page_size=page_size
33
+ )
34
+
35
+ results = []
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
+ results.append(f"Title: {title}\nDescription: {description}\nURL: {url}")
41
+
42
+ return "\n\n".join(results)
43
+ except Exception as e:
44
+ return f"Error fetching news: {e}"
45
+
46
+ # Perform sentiment analysis
47
+ def analyze_sentiment(text):
48
+ try:
49
+ analysis = TextBlob(text)
50
+ polarity = analysis.sentiment.polarity
51
+ if polarity > 0.1:
52
+ return "Positive"
53
+ elif polarity < -0.1:
54
+ return "Negative"
55
+ else:
56
+ return "Neutral"
57
+ except Exception as e:
58
+ return f"Error analyzing sentiment: {e}"
59
+
60
+ # Fetch technical data
61
+ def fetch_technical_data(stock_symbol):
62
+ try:
63
+ stock = yf.Ticker(stock_symbol)
64
+ data = stock.history(period="1y")
65
+
66
+ if data.empty:
67
+ return "No data found for this stock symbol."
68
+
69
+ data['RSI'] = ta.momentum.RSIIndicator(data['Close']).rsi()
70
+ macd = ta.trend.MACD(data['Close'])
71
+ data['MACD'] = macd.macd()
72
+ data['MACD_Signal'] = macd.macd_signal()
73
+ data['SMA_50'] = data['Close'].rolling(window=50).mean()
74
+ data['SMA_200'] = data['Close'].rolling(window=200).mean()
75
+
76
+ latest_technical_data = {
77
+ "RSI": data['RSI'].iloc[-1],
78
+ "MACD": data['MACD'].iloc[-1],
79
+ "MACD Signal": data['MACD_Signal'].iloc[-1],
80
+ "50 Day SMA": data['SMA_50'].iloc[-1],
81
+ "200 Day SMA": data['SMA_200'].iloc[-1],
82
+ }
83
+
84
+ return pd.Series(latest_technical_data).to_string()
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
+ news = fetch_financial_news(stock_symbol)
91
+ technical_data = fetch_technical_data(stock_symbol)
92
+ return news, technical_data
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
+ analyze_button.click(analyze_stock, inputs=[stock_input], outputs=[news_output, tech_output])
102
 
103
  if __name__ == "__main__":
104
  demo.launch()