CCockrum commited on
Commit
ad9f8c5
·
verified ·
1 Parent(s): fcc1ce5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -35
app.py CHANGED
@@ -1,17 +1,16 @@
1
- import gradio as gr
2
  import pandas as pd
 
 
3
  import requests
 
4
  import datetime
5
  import tempfile
6
- import os
7
- import matplotlib.pyplot as plt
8
  from transformers import pipeline
9
 
10
- # Initialize Models
11
  summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
12
  chat_model = pipeline("text-generation", model="tiiuae/falcon-7b-instruct", max_length=256)
13
 
14
-
15
  # API Key
16
  POLYGON_API_KEY = os.getenv("POLYGON_API_KEY")
17
 
@@ -23,16 +22,7 @@ sector_averages = {
23
  "Energy": {"P/E Ratio": 12, "P/S Ratio": 1.2, "P/B Ratio": 1.3},
24
  }
25
 
26
- # Tooltip dictionary
27
- tooltips = {
28
- "P/E Ratio": "Price/Earnings: Lower can indicate better value.",
29
- "P/S Ratio": "Price/Sales: Lower can indicate better value relative to sales.",
30
- "P/B Ratio": "Price/Book: Lower can indicate undervaluation.",
31
- "PEG Ratio": "Price/Earnings to Growth: Closer to 1 is ideal.",
32
- "Dividend Yield": "Annual dividend income relative to price."
33
- }
34
-
35
- # Helper Functions
36
  def safe_request(url):
37
  try:
38
  response = requests.get(url)
@@ -41,15 +31,15 @@ def safe_request(url):
41
  except:
42
  return None
43
 
 
44
  def get_company_info(symbol):
45
  url = f"https://api.polygon.io/v3/reference/tickers/{symbol}?apiKey={POLYGON_API_KEY}"
46
  response = safe_request(url)
47
  if response:
48
  data = response.json().get('results', {})
49
  sector = data.get('market', 'Technology')
50
- # Dynamic Guess
51
  if sector.lower() == 'stocks':
52
- sector = "Technology"
53
  return {
54
  'Name': data.get('name', 'N/A'),
55
  'Industry': data.get('sic_description', 'N/A'),
@@ -85,6 +75,7 @@ def get_historical_prices(symbol):
85
  return dates, prices
86
  return [], []
87
 
 
88
  def calculate_ratios(market_cap, total_revenue, price, dividend_amount, eps=5.0, growth=0.1, book_value=500000000):
89
  pe = price / eps if eps else 0
90
  ps = market_cap / total_revenue if total_revenue else 0
@@ -112,7 +103,6 @@ def compare_to_sector(sector, ratios):
112
  "Sector Average": [],
113
  "Difference": []
114
  }
115
-
116
  for key in averages:
117
  stock_value = ratios.get(key, 0)
118
  sector_value = averages.get(key, 0)
@@ -133,7 +123,6 @@ def compare_to_sector(sector, ratios):
133
 
134
  return pd.DataFrame(data)
135
 
136
-
137
  def generate_summary(info, ratios):
138
  recommendation = "Hold"
139
  if ratios['P/E Ratio'] < 15 and ratios['P/B Ratio'] < 2 and ratios['PEG Ratio'] < 1.0 and ratios['Dividend Yield'] > 2:
@@ -160,9 +149,6 @@ def answer_investing_question(question):
160
  response = chat_model(question)[0]['generated_text']
161
  return response
162
 
163
-
164
-
165
-
166
  def stock_research(symbol, eps=5.0, growth=0.1, book=500000000):
167
  info = get_company_info(symbol)
168
  price = get_current_price(symbol)
@@ -188,7 +174,7 @@ def stock_research(symbol, eps=5.0, growth=0.1, book=500000000):
188
 
189
  return summary, info_table, ratios_table, sector_comp, fig
190
 
191
- # --- Gradio UI ---
192
  with gr.Blocks(theme="soft") as iface:
193
  with gr.Row():
194
  symbol = gr.Textbox(label="Stock Symbol (e.g., AAPL)")
@@ -220,17 +206,5 @@ with gr.Blocks(theme="soft") as iface:
220
  submit_btn.click(fn=stock_research, inputs=[symbol, eps, growth, book],
221
  outputs=[output_summary, output_info, output_ratios, output_sector, output_chart])
222
 
223
- # Sector Comparison Color Highlight
224
- def style_sector(df):
225
- def highlight(val):
226
- if isinstance(val, (int, float)):
227
- if val < 0:
228
- return 'color: green'
229
- elif val > 0:
230
- return 'color: red'
231
- return ''
232
- return df.style.applymap(highlight, subset=['Difference'])
233
- output_sector.style_fn = style_sector
234
-
235
  if __name__ == "__main__":
236
  iface.launch()
 
 
1
  import pandas as pd
2
+ import matplotlib.pyplot as plt
3
+ import gradio as gr
4
  import requests
5
+ import os
6
  import datetime
7
  import tempfile
 
 
8
  from transformers import pipeline
9
 
10
+ # Initialize Summarizer and Chat Model
11
  summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
12
  chat_model = pipeline("text-generation", model="tiiuae/falcon-7b-instruct", max_length=256)
13
 
 
14
  # API Key
15
  POLYGON_API_KEY = os.getenv("POLYGON_API_KEY")
16
 
 
22
  "Energy": {"P/E Ratio": 12, "P/S Ratio": 1.2, "P/B Ratio": 1.3},
23
  }
24
 
25
+ # Safe Request Function
 
 
 
 
 
 
 
 
 
26
  def safe_request(url):
27
  try:
28
  response = requests.get(url)
 
31
  except:
32
  return None
33
 
34
+ # Fetch Functions
35
  def get_company_info(symbol):
36
  url = f"https://api.polygon.io/v3/reference/tickers/{symbol}?apiKey={POLYGON_API_KEY}"
37
  response = safe_request(url)
38
  if response:
39
  data = response.json().get('results', {})
40
  sector = data.get('market', 'Technology')
 
41
  if sector.lower() == 'stocks':
42
+ sector = 'Technology'
43
  return {
44
  'Name': data.get('name', 'N/A'),
45
  'Industry': data.get('sic_description', 'N/A'),
 
75
  return dates, prices
76
  return [], []
77
 
78
+ # Financial Calculations
79
  def calculate_ratios(market_cap, total_revenue, price, dividend_amount, eps=5.0, growth=0.1, book_value=500000000):
80
  pe = price / eps if eps else 0
81
  ps = market_cap / total_revenue if total_revenue else 0
 
103
  "Sector Average": [],
104
  "Difference": []
105
  }
 
106
  for key in averages:
107
  stock_value = ratios.get(key, 0)
108
  sector_value = averages.get(key, 0)
 
123
 
124
  return pd.DataFrame(data)
125
 
 
126
  def generate_summary(info, ratios):
127
  recommendation = "Hold"
128
  if ratios['P/E Ratio'] < 15 and ratios['P/B Ratio'] < 2 and ratios['PEG Ratio'] < 1.0 and ratios['Dividend Yield'] > 2:
 
149
  response = chat_model(question)[0]['generated_text']
150
  return response
151
 
 
 
 
152
  def stock_research(symbol, eps=5.0, growth=0.1, book=500000000):
153
  info = get_company_info(symbol)
154
  price = get_current_price(symbol)
 
174
 
175
  return summary, info_table, ratios_table, sector_comp, fig
176
 
177
+ # Gradio UI
178
  with gr.Blocks(theme="soft") as iface:
179
  with gr.Row():
180
  symbol = gr.Textbox(label="Stock Symbol (e.g., AAPL)")
 
206
  submit_btn.click(fn=stock_research, inputs=[symbol, eps, growth, book],
207
  outputs=[output_summary, output_info, output_ratios, output_sector, output_chart])
208
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  if __name__ == "__main__":
210
  iface.launch()