TanishqO0F commited on
Commit
70b86a2
·
verified ·
1 Parent(s): b25e082

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -29
app.py CHANGED
@@ -6,6 +6,17 @@ from transformers import pipeline
6
  import plotly.express as px
7
  from datetime import datetime, timedelta
8
 
 
 
 
 
 
 
 
 
 
 
 
9
  # Sentiment Analysis Model
10
  sentiment_model = pipeline(model="finiteautomata/bertweet-base-sentiment-analysis")
11
 
@@ -52,31 +63,24 @@ def analyze_sentiment(text):
52
  result = sentiment_model(text)[0]
53
  return result['label'], result['score']
54
 
55
- # Function to fetch stock data from Alpha Vantage API
56
- def fetch_stock_data(company_name):
57
  url = "https://alpha-vantage.p.rapidapi.com/query"
58
- querystring = {"function": "TIME_SERIES_DAILY", "symbol": company_name, "outputsize": "compact", "datatype": "json"}
59
  headers = {
60
  "x-rapidapi-key": "e078dae417mshb13ddc2d8149768p1608e9jsn888ce49e8554",
61
  "x-rapidapi-host": "alpha-vantage.p.rapidapi.com"
62
  }
63
-
64
- try:
65
- response = requests.get(url, headers=headers, params=querystring)
66
- response.raise_for_status()
67
- data = response.json()
68
- except requests.RequestException as e:
69
- print(f"Error fetching stock data: {e}")
70
- return None
71
 
72
  if "Time Series (Daily)" not in data:
73
- return None
74
 
75
- stock_data = data["Time Series (Daily)"]
76
- df = pd.DataFrame.from_dict(stock_data, orient='index')
77
- df.index = pd.to_datetime(df.index)
78
- df = df.astype(float)
79
- return df
80
 
81
  # Main function to process news and perform analysis
82
  def news_and_analysis(query):
@@ -100,18 +104,14 @@ def news_and_analysis(query):
100
  labels={'Time': 'Publication Time', 'Sentiment_Score': 'Sentiment Score'}
101
  )
102
 
103
- # Check if the input query is a company name (heuristic: if it's more than one word)
104
- if len(query.split()) > 1:
105
- stock_df = fetch_stock_data(query)
106
- if stock_df is not None:
107
- stock_fig = px.line(
108
- stock_df,
109
- x=stock_df.index,
110
- y='4. close',
111
- title=f'{query} Stock Price Over Time',
112
- labels={'index': 'Date', '4. close': 'Closing Price'}
113
- )
114
  return news_df, sentiment_fig, stock_fig
 
115
  return news_df, sentiment_fig, None
116
 
117
  # Gradio interface
@@ -133,7 +133,7 @@ with gr.Blocks() as demo:
133
  with gr.Column():
134
  news_output = gr.DataFrame(label="News and Sentiment Analysis")
135
  sentiment_plot = gr.Plot(label="Sentiment Analysis")
136
- stock_plot = gr.Plot(label="Stock Price Analysis")
137
 
138
  analyze_btn.click(
139
  news_and_analysis,
 
6
  import plotly.express as px
7
  from datetime import datetime, timedelta
8
 
9
+ # Load the Excel file with company names and symbols
10
+ file_path = '/Top 2000 Valued Companies with Ticker Symbols.xlsx'
11
+ companies_df = pd.read_excel(file_path)
12
+
13
+ # Function to get stock symbol for a company name
14
+ def get_stock_symbol(company_name):
15
+ match = companies_df[companies_df['Name'].str.contains(company_name, case=False, na=False)]
16
+ if not match.empty:
17
+ return match.iloc[0]['Symbol']
18
+ return None
19
+
20
  # Sentiment Analysis Model
21
  sentiment_model = pipeline(model="finiteautomata/bertweet-base-sentiment-analysis")
22
 
 
63
  result = sentiment_model(text)[0]
64
  return result['label'], result['score']
65
 
66
+ # Function to fetch stock data
67
+ def fetch_stock_data(symbol):
68
  url = "https://alpha-vantage.p.rapidapi.com/query"
69
+ querystring = {"function":"TIME_SERIES_DAILY", "symbol":symbol, "outputsize":"compact", "datatype":"json"}
70
  headers = {
71
  "x-rapidapi-key": "e078dae417mshb13ddc2d8149768p1608e9jsn888ce49e8554",
72
  "x-rapidapi-host": "alpha-vantage.p.rapidapi.com"
73
  }
74
+ response = requests.get(url, headers=headers, params=querystring)
75
+ data = response.json()
 
 
 
 
 
 
76
 
77
  if "Time Series (Daily)" not in data:
78
+ return pd.DataFrame()
79
 
80
+ stock_data = pd.DataFrame(data["Time Series (Daily)"]).T
81
+ stock_data.index = pd.to_datetime(stock_data.index)
82
+ stock_data.columns = ["Open", "High", "Low", "Close", "Volume"]
83
+ return stock_data
 
84
 
85
  # Main function to process news and perform analysis
86
  def news_and_analysis(query):
 
104
  labels={'Time': 'Publication Time', 'Sentiment_Score': 'Sentiment Score'}
105
  )
106
 
107
+ # Check if query is a company name and fetch stock data
108
+ stock_symbol = get_stock_symbol(query)
109
+ if stock_symbol:
110
+ stock_data = fetch_stock_data(stock_symbol)
111
+ if not stock_data.empty:
112
+ stock_fig = px.line(stock_data, x=stock_data.index, y='Close', title=f'{stock_symbol} Stock Price')
 
 
 
 
 
113
  return news_df, sentiment_fig, stock_fig
114
+
115
  return news_df, sentiment_fig, None
116
 
117
  # Gradio interface
 
133
  with gr.Column():
134
  news_output = gr.DataFrame(label="News and Sentiment Analysis")
135
  sentiment_plot = gr.Plot(label="Sentiment Analysis")
136
+ stock_plot = gr.Plot(label="Stock Price Movement")
137
 
138
  analyze_btn.click(
139
  news_and_analysis,