Poojashetty357 commited on
Commit
157bd28
Β·
verified Β·
1 Parent(s): ca5a53e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -81
app.py CHANGED
@@ -2,27 +2,13 @@ import os
2
  import requests
3
  import gradio as gr
4
  import openai
5
- import matplotlib.pyplot as plt
6
- from io import BytesIO
7
 
8
  # πŸ” Load secrets from environment
9
  client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
10
  STOCK_API_KEY = os.getenv("STOCK_API_KEY")
11
 
12
- # πŸ” Improved stock symbol fetch with alias support
13
  def get_stock_symbol(company_name):
14
- aliases = {
15
- "facebook": "META",
16
- "google": "GOOGL",
17
- "tesla": "TSLA",
18
- "apple": "AAPL",
19
- "amazon": "AMZN"
20
- }
21
-
22
- name_lower = company_name.lower()
23
- if name_lower in aliases:
24
- return aliases[name_lower]
25
-
26
  url = 'https://www.alphavantage.co/query'
27
  params = {
28
  'function': 'SYMBOL_SEARCH',
@@ -31,12 +17,8 @@ def get_stock_symbol(company_name):
31
  }
32
  r = requests.get(url, params=params).json()
33
  try:
34
- best_match = next(
35
- match for match in r['bestMatches']
36
- if company_name.lower() in match['2. name'].lower()
37
- )
38
- return best_match['1. symbol']
39
- except (StopIteration, KeyError, IndexError):
40
  return None
41
 
42
  # πŸ“ˆ Get real-time stock price and last trading date
@@ -96,51 +78,21 @@ def ask_gpt_summary(company_name, financial_data):
96
  except Exception as e:
97
  return f"GPT Error: {e}"
98
 
99
- # πŸ“Š Generate bar chart of financials
100
- def safe_float(value):
101
- try:
102
- return float(value)
103
- except (ValueError, TypeError):
104
- return 0
105
-
106
- def plot_financials(financial_data):
107
- labels = ['P/E Ratio', 'EPS', 'Market Cap ($B)']
108
- values = [
109
- safe_float(financial_data['P/E Ratio']),
110
- safe_float(financial_data['EPS']),
111
- safe_float(financial_data['Market Cap']) / 1e9
112
- ]
113
- plt.figure(figsize=(6, 3))
114
- bars = plt.barh(labels, values)
115
- for label, bar in zip(labels, bars):
116
- val = bar.get_width()
117
- text = f"${val:.2f}B" if 'Market Cap' in label else f"{val:.2f}"
118
- plt.text(val, bar.get_y() + bar.get_height() / 2, text, va='center')
119
- plt.xlabel('Value')
120
- plt.title('Company Financial Overview')
121
- plt.tight_layout()
122
- buf = BytesIO()
123
- plt.savefig(buf, format='png')
124
- plt.close()
125
- buf.seek(0)
126
- return buf
127
-
128
  # 🎯 Main function
129
  def stock_insight(company_name):
130
  symbol = get_stock_symbol(company_name)
131
  if not symbol:
132
- return f"❌ Could not find stock symbol for '{company_name}'.", "", "", "", "", "", None
133
 
134
  price, last_trade = get_stock_quote(symbol)
135
  if not price:
136
- return f"❌ Could not fetch price for symbol {symbol}.", "", "", "", "", "", None
137
 
138
  overview = get_financial_overview(symbol)
139
  if not overview:
140
- return f"❌ Could not fetch financial data for {symbol}.", "", "", "", "", "", None
141
 
142
  summary = ask_gpt_summary(company_name, overview)
143
- chart_buffer = plot_financials(overview)
144
 
145
  return (
146
  f"βœ… Symbol: {symbol}",
@@ -148,32 +100,23 @@ def stock_insight(company_name):
148
  f"πŸ—“οΈ Last Trading Day: {last_trade}",
149
  f"πŸ“Š P/E Ratio: {overview['P/E Ratio']}\nEPS: {overview['EPS']}\nMarket Cap: ${overview['Market Cap']}",
150
  f"πŸ“ Company Summary: {overview['Description'][:300]}...",
151
- f"πŸ€– GPT Insight: {summary}",
152
- chart_buffer
153
  )
154
 
155
- # πŸ–₯️ Gradio Interface with Blocks
156
- with gr.Blocks() as demo:
157
- gr.Markdown("# πŸ“ˆ Stock Market Assistant")
158
- with gr.Row():
159
- company_input = gr.Textbox(label="Enter Company Name")
160
- search_button = gr.Button("πŸ” Search")
161
-
162
- with gr.Row():
163
- with gr.Column():
164
- symbol_output = gr.Textbox(label="Symbol")
165
- price_output = gr.Textbox(label="Stock Price")
166
- trade_output = gr.Textbox(label="Last Trading Day")
167
- financial_output = gr.Textbox(label="Financial Overview")
168
- with gr.Column():
169
- chart_output = gr.Image(label="πŸ“Š Financial Chart", type="pil")
170
-
171
- company_summary = gr.Textbox(label="Company Summary")
172
- gpt_output = gr.Textbox(label="AI Insight")
173
-
174
- search_button.click(stock_insight, inputs=company_input, outputs=[
175
- symbol_output, price_output, trade_output,
176
- financial_output, company_summary, gpt_output, chart_output
177
- ])
178
-
179
- demo.launch()
 
2
  import requests
3
  import gradio as gr
4
  import openai
 
 
5
 
6
  # πŸ” Load secrets from environment
7
  client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
8
  STOCK_API_KEY = os.getenv("STOCK_API_KEY")
9
 
10
+ # πŸ” Get stock symbol from company name
11
  def get_stock_symbol(company_name):
 
 
 
 
 
 
 
 
 
 
 
 
12
  url = 'https://www.alphavantage.co/query'
13
  params = {
14
  'function': 'SYMBOL_SEARCH',
 
17
  }
18
  r = requests.get(url, params=params).json()
19
  try:
20
+ return r['bestMatches'][0]['1. symbol']
21
+ except (KeyError, IndexError):
 
 
 
 
22
  return None
23
 
24
  # πŸ“ˆ Get real-time stock price and last trading date
 
78
  except Exception as e:
79
  return f"GPT Error: {e}"
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  # 🎯 Main function
82
  def stock_insight(company_name):
83
  symbol = get_stock_symbol(company_name)
84
  if not symbol:
85
+ return f"❌ Could not find stock symbol for '{company_name}'.", "", "", "", "", ""
86
 
87
  price, last_trade = get_stock_quote(symbol)
88
  if not price:
89
+ return f"❌ Could not fetch price for symbol {symbol}.", "", "", "", "", ""
90
 
91
  overview = get_financial_overview(symbol)
92
  if not overview:
93
+ return f"❌ Could not fetch financial data for {symbol}.", "", "", "", "", ""
94
 
95
  summary = ask_gpt_summary(company_name, overview)
 
96
 
97
  return (
98
  f"βœ… Symbol: {symbol}",
 
100
  f"πŸ—“οΈ Last Trading Day: {last_trade}",
101
  f"πŸ“Š P/E Ratio: {overview['P/E Ratio']}\nEPS: {overview['EPS']}\nMarket Cap: ${overview['Market Cap']}",
102
  f"πŸ“ Company Summary: {overview['Description'][:300]}...",
103
+ f"πŸ€– GPT Insight: {summary}"
 
104
  )
105
 
106
+ # πŸ–₯️ Gradio Interface
107
+ demo = gr.Interface(
108
+ fn=stock_insight,
109
+ inputs=gr.Textbox(label="Enter Company Name"),
110
+ outputs=[
111
+ gr.Textbox(label="Symbol"),
112
+ gr.Textbox(label="Stock Price"),
113
+ gr.Textbox(label="Last Trading Day"),
114
+ gr.Textbox(label="Financial Overview"),
115
+ gr.Textbox(label="Company Summary"),
116
+ gr.Textbox(label="AI Insight")
117
+ ],
118
+ title="πŸ“ˆ Stock Market Assistant",
119
+ description="Search by company name to get stock symbol, live price, financial info, last trade date, and AI-based insight."
120
+ )
121
+
122
+ demo.launch()