Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -15,13 +15,10 @@ POLYGON_API_KEY = os.getenv("POLYGON_API_KEY")
|
|
15 |
|
16 |
# Helper Functions
|
17 |
def get_company_info(symbol):
|
18 |
-
|
19 |
-
url = f"https://api.polygon.io/v3/reference/tickers/{symbol}?apiKey={
|
20 |
-
print(f"DEBUG: Fetching company info URL: {url}")
|
21 |
try:
|
22 |
response = requests.get(url)
|
23 |
-
print(f"DEBUG: Response Status: {response.status_code}")
|
24 |
-
print(f"DEBUG: Response JSON: {response.json()}")
|
25 |
response.raise_for_status()
|
26 |
data = response.json()['results']
|
27 |
return {
|
@@ -36,11 +33,8 @@ def get_company_info(symbol):
|
|
36 |
|
37 |
def get_current_price(symbol):
|
38 |
url = f"https://api.polygon.io/v2/aggs/ticker/{symbol}/prev?adjusted=true&apiKey={POLYGON_API_KEY}"
|
39 |
-
print(f"DEBUG: Fetching current price URL: {url}")
|
40 |
try:
|
41 |
response = requests.get(url)
|
42 |
-
print(f"DEBUG: Response Status: {response.status_code}")
|
43 |
-
print(f"DEBUG: Response JSON: {response.json()}")
|
44 |
response.raise_for_status()
|
45 |
data = response.json()['results'][0]
|
46 |
return float(data['c'])
|
@@ -50,11 +44,8 @@ def get_current_price(symbol):
|
|
50 |
|
51 |
def get_dividends(symbol):
|
52 |
url = f"https://api.polygon.io/v3/reference/dividends?ticker={symbol}&apiKey={POLYGON_API_KEY}"
|
53 |
-
print(f"DEBUG: Fetching dividends URL: {url}")
|
54 |
try:
|
55 |
response = requests.get(url)
|
56 |
-
print(f"DEBUG: Response Status: {response.status_code}")
|
57 |
-
print(f"DEBUG: Response JSON: {response.json()}")
|
58 |
response.raise_for_status()
|
59 |
data = response.json()['results'][0]
|
60 |
return {
|
@@ -69,11 +60,8 @@ def get_historical_prices(symbol):
|
|
69 |
end = datetime.date.today()
|
70 |
start = end - datetime.timedelta(days=365)
|
71 |
url = f"https://api.polygon.io/v2/aggs/ticker/{symbol}/range/1/day/{start}/{end}?adjusted=true&sort=asc&apiKey={POLYGON_API_KEY}"
|
72 |
-
print(f"DEBUG: Fetching historical prices URL: {url}")
|
73 |
try:
|
74 |
response = requests.get(url)
|
75 |
-
print(f"DEBUG: Response Status: {response.status_code}")
|
76 |
-
print(f"DEBUG: Response JSON: {response.json()}")
|
77 |
response.raise_for_status()
|
78 |
results = response.json()['results']
|
79 |
dates = [datetime.datetime.fromtimestamp(r['t']/1000) for r in results]
|
@@ -83,28 +71,30 @@ def get_historical_prices(symbol):
|
|
83 |
print(f"DEBUG: Error fetching historical prices: {e}")
|
84 |
return [], []
|
85 |
|
86 |
-
def calculate_ratios(market_cap, total_revenue, price, assumed_eps=5.0, growth_rate=0.1, book_value=500000000):
|
87 |
pe_ratio = price / assumed_eps if assumed_eps else 0
|
88 |
ps_ratio = market_cap / total_revenue if total_revenue else 0
|
89 |
pb_ratio = market_cap / book_value if book_value else 0
|
90 |
peg_ratio = pe_ratio / (growth_rate * 100) if growth_rate else 0
|
|
|
91 |
return {
|
92 |
'P/E Ratio': pe_ratio,
|
93 |
'P/S Ratio': ps_ratio,
|
94 |
'P/B Ratio': pb_ratio,
|
95 |
-
'PEG Ratio': peg_ratio
|
|
|
96 |
}
|
97 |
|
98 |
def generate_summary(info, ratios):
|
99 |
text = (f"{info['Name']} operates in the {info['Industry']} sector. It has a market capitalization of "
|
100 |
f"${info['Market Cap']:,.2f}. The company exhibits a P/E ratio of {ratios['P/E Ratio']:.2f}, "
|
101 |
f"P/S ratio of {ratios['P/S Ratio']:.2f}, and P/B ratio of {ratios['P/B Ratio']:.2f}. "
|
|
|
102 |
f"This suggests a {'potential undervaluation' if ratios['P/E Ratio'] < 20 else 'higher valuation'} relative to the market.")
|
103 |
summary = summarizer(text, max_length=120, min_length=30, do_sample=False)[0]['summary_text']
|
104 |
return summary
|
105 |
|
106 |
def stock_research(symbol, assumed_eps=5.0, growth_rate=0.1, book_value=500000000):
|
107 |
-
# Safeguard against None values
|
108 |
if assumed_eps is None:
|
109 |
assumed_eps = 5.0
|
110 |
if growth_rate is None:
|
@@ -120,10 +110,9 @@ def stock_research(symbol, assumed_eps=5.0, growth_rate=0.1, book_value=50000000
|
|
120 |
if not info or not price:
|
121 |
return "Error fetching stock information.", None, None, None
|
122 |
|
123 |
-
ratios = calculate_ratios(info['Market Cap'], info['Total Revenue'], price, assumed_eps, growth_rate, book_value)
|
124 |
summary = generate_summary(info, ratios)
|
125 |
|
126 |
-
# Create historical price chart
|
127 |
fig, ax = plt.subplots()
|
128 |
ax.plot(dates, prices, label=f"{symbol} Price")
|
129 |
ax.set_title(f"{symbol} Historical Price (1 Year)")
|
@@ -137,23 +126,38 @@ def stock_research(symbol, assumed_eps=5.0, growth_rate=0.1, book_value=50000000
|
|
137 |
|
138 |
return summary, info_table, ratios_table, fig
|
139 |
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
gr.
|
151 |
-
gr.
|
152 |
-
gr.
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
|
158 |
if __name__ == "__main__":
|
159 |
iface.launch()
|
|
|
15 |
|
16 |
# Helper Functions
|
17 |
def get_company_info(symbol):
|
18 |
+
api_key = os.getenv("POLYGON_API_KEY")
|
19 |
+
url = f"https://api.polygon.io/v3/reference/tickers/{symbol}?apiKey={api_key}"
|
|
|
20 |
try:
|
21 |
response = requests.get(url)
|
|
|
|
|
22 |
response.raise_for_status()
|
23 |
data = response.json()['results']
|
24 |
return {
|
|
|
33 |
|
34 |
def get_current_price(symbol):
|
35 |
url = f"https://api.polygon.io/v2/aggs/ticker/{symbol}/prev?adjusted=true&apiKey={POLYGON_API_KEY}"
|
|
|
36 |
try:
|
37 |
response = requests.get(url)
|
|
|
|
|
38 |
response.raise_for_status()
|
39 |
data = response.json()['results'][0]
|
40 |
return float(data['c'])
|
|
|
44 |
|
45 |
def get_dividends(symbol):
|
46 |
url = f"https://api.polygon.io/v3/reference/dividends?ticker={symbol}&apiKey={POLYGON_API_KEY}"
|
|
|
47 |
try:
|
48 |
response = requests.get(url)
|
|
|
|
|
49 |
response.raise_for_status()
|
50 |
data = response.json()['results'][0]
|
51 |
return {
|
|
|
60 |
end = datetime.date.today()
|
61 |
start = end - datetime.timedelta(days=365)
|
62 |
url = f"https://api.polygon.io/v2/aggs/ticker/{symbol}/range/1/day/{start}/{end}?adjusted=true&sort=asc&apiKey={POLYGON_API_KEY}"
|
|
|
63 |
try:
|
64 |
response = requests.get(url)
|
|
|
|
|
65 |
response.raise_for_status()
|
66 |
results = response.json()['results']
|
67 |
dates = [datetime.datetime.fromtimestamp(r['t']/1000) for r in results]
|
|
|
71 |
print(f"DEBUG: Error fetching historical prices: {e}")
|
72 |
return [], []
|
73 |
|
74 |
+
def calculate_ratios(market_cap, total_revenue, price, dividend_amount, assumed_eps=5.0, growth_rate=0.1, book_value=500000000):
|
75 |
pe_ratio = price / assumed_eps if assumed_eps else 0
|
76 |
ps_ratio = market_cap / total_revenue if total_revenue else 0
|
77 |
pb_ratio = market_cap / book_value if book_value else 0
|
78 |
peg_ratio = pe_ratio / (growth_rate * 100) if growth_rate else 0
|
79 |
+
dividend_yield = (dividend_amount / price) * 100 if price else 0
|
80 |
return {
|
81 |
'P/E Ratio': pe_ratio,
|
82 |
'P/S Ratio': ps_ratio,
|
83 |
'P/B Ratio': pb_ratio,
|
84 |
+
'PEG Ratio': peg_ratio,
|
85 |
+
'Dividend Yield (%)': dividend_yield
|
86 |
}
|
87 |
|
88 |
def generate_summary(info, ratios):
|
89 |
text = (f"{info['Name']} operates in the {info['Industry']} sector. It has a market capitalization of "
|
90 |
f"${info['Market Cap']:,.2f}. The company exhibits a P/E ratio of {ratios['P/E Ratio']:.2f}, "
|
91 |
f"P/S ratio of {ratios['P/S Ratio']:.2f}, and P/B ratio of {ratios['P/B Ratio']:.2f}. "
|
92 |
+
f"Its dividend yield is {ratios['Dividend Yield (%)']:.2f}%. "
|
93 |
f"This suggests a {'potential undervaluation' if ratios['P/E Ratio'] < 20 else 'higher valuation'} relative to the market.")
|
94 |
summary = summarizer(text, max_length=120, min_length=30, do_sample=False)[0]['summary_text']
|
95 |
return summary
|
96 |
|
97 |
def stock_research(symbol, assumed_eps=5.0, growth_rate=0.1, book_value=500000000):
|
|
|
98 |
if assumed_eps is None:
|
99 |
assumed_eps = 5.0
|
100 |
if growth_rate is None:
|
|
|
110 |
if not info or not price:
|
111 |
return "Error fetching stock information.", None, None, None
|
112 |
|
113 |
+
ratios = calculate_ratios(info['Market Cap'], info['Total Revenue'], price, dividends['Dividend Amount'], assumed_eps, growth_rate, book_value)
|
114 |
summary = generate_summary(info, ratios)
|
115 |
|
|
|
116 |
fig, ax = plt.subplots()
|
117 |
ax.plot(dates, prices, label=f"{symbol} Price")
|
118 |
ax.set_title(f"{symbol} Historical Price (1 Year)")
|
|
|
126 |
|
127 |
return summary, info_table, ratios_table, fig
|
128 |
|
129 |
+
with gr.Blocks() as iface:
|
130 |
+
gr.Markdown("""
|
131 |
+
# 📚 Why These Inputs Matter:
|
132 |
+
- **Assumed EPS**: Needed to calculate the Price/Earnings (P/E) Ratio.
|
133 |
+
- **Assumed Growth Rate**: Needed to calculate the Price/Earnings/Growth (PEG) Ratio.
|
134 |
+
- **Assumed Book Value**: Needed to calculate the Price/Book (P/B) Ratio.
|
135 |
+
- **Dividend Info**: Automatically fetched.
|
136 |
+
""")
|
137 |
+
|
138 |
+
with gr.Row():
|
139 |
+
symbol = gr.Textbox(label="Stock Symbol (e.g., AAPL)")
|
140 |
+
eps = gr.Number(label="Assumed EPS", value=5.0)
|
141 |
+
growth = gr.Number(label="Assumed Growth Rate", value=0.1)
|
142 |
+
book = gr.Number(label="Assumed Book Value", value=500000000)
|
143 |
+
|
144 |
+
with gr.Tabs():
|
145 |
+
with gr.Tab("AI Research Summary"):
|
146 |
+
output_summary = gr.Textbox()
|
147 |
+
with gr.Tab("Company Snapshot"):
|
148 |
+
output_info = gr.Dataframe()
|
149 |
+
with gr.Tab("Valuation Ratios"):
|
150 |
+
output_ratios = gr.Dataframe()
|
151 |
+
with gr.Tab("Historical Price Chart"):
|
152 |
+
output_chart = gr.Plot()
|
153 |
+
|
154 |
+
submit_btn = gr.Button("Run Analysis")
|
155 |
+
|
156 |
+
submit_btn.click(
|
157 |
+
fn=stock_research,
|
158 |
+
inputs=[symbol, eps, growth, book],
|
159 |
+
outputs=[output_summary, output_info, output_ratios, output_chart]
|
160 |
+
)
|
161 |
|
162 |
if __name__ == "__main__":
|
163 |
iface.launch()
|