Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -6,6 +6,7 @@ import requests
|
|
6 |
import os
|
7 |
from transformers import pipeline
|
8 |
import datetime
|
|
|
9 |
|
10 |
# Initialize Summarizer
|
11 |
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
@@ -13,6 +14,14 @@ summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
|
13 |
# Polygon API Key
|
14 |
POLYGON_API_KEY = os.getenv("POLYGON_API_KEY")
|
15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
# Helper Functions
|
17 |
def get_company_info(symbol):
|
18 |
api_key = os.getenv("POLYGON_API_KEY")
|
@@ -24,6 +33,7 @@ def get_company_info(symbol):
|
|
24 |
return {
|
25 |
'Name': data.get('name', 'N/A'),
|
26 |
'Industry': data.get('sic_description', 'N/A'),
|
|
|
27 |
'Market Cap': data.get('market_cap', 0),
|
28 |
'Total Revenue': data.get('total_employees', 0) * 100000
|
29 |
}
|
@@ -85,6 +95,18 @@ def calculate_ratios(market_cap, total_revenue, price, dividend_amount, assumed_
|
|
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}, "
|
@@ -108,10 +130,11 @@ def stock_research(symbol, assumed_eps=5.0, growth_rate=0.1, book_value=50000000
|
|
108 |
dates, prices = get_historical_prices(symbol)
|
109 |
|
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")
|
@@ -124,14 +147,26 @@ def stock_research(symbol, assumed_eps=5.0, growth_rate=0.1, book_value=50000000
|
|
124 |
info_table = pd.DataFrame({"Metric": list(info.keys()), "Value": list(info.values())})
|
125 |
ratios_table = pd.DataFrame({"Ratio": list(ratios.keys()), "Value": list(ratios.values())})
|
126 |
|
127 |
-
return summary, info_table, ratios_table, fig
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
with gr.Blocks() as iface:
|
130 |
with gr.Row():
|
131 |
-
symbol = gr.Textbox(label="Stock Symbol (e.g., AAPL)", info="
|
132 |
-
eps = gr.Number(label="Assumed EPS", value=5.0, info="Earnings Per Share (EPS)
|
133 |
-
growth = gr.Number(label="Assumed Growth Rate", value=0.1, info="Expected annual growth rate for PEG
|
134 |
-
book = gr.Number(label="Assumed Book Value", value=500000000, info="
|
135 |
|
136 |
with gr.Tabs():
|
137 |
with gr.Tab("AI Research Summary"):
|
@@ -140,16 +175,26 @@ with gr.Blocks() as iface:
|
|
140 |
output_info = gr.Dataframe()
|
141 |
with gr.Tab("Valuation Ratios"):
|
142 |
output_ratios = gr.Dataframe()
|
|
|
|
|
143 |
with gr.Tab("Historical Price Chart"):
|
144 |
output_chart = gr.Plot()
|
145 |
|
146 |
submit_btn = gr.Button("Run Analysis")
|
|
|
|
|
147 |
|
148 |
submit_btn.click(
|
149 |
fn=stock_research,
|
150 |
inputs=[symbol, eps, growth, book],
|
151 |
-
outputs=[output_summary, output_info, output_ratios, output_chart]
|
|
|
|
|
|
|
|
|
|
|
|
|
152 |
)
|
153 |
|
154 |
if __name__ == "__main__":
|
155 |
-
iface.launch()
|
|
|
6 |
import os
|
7 |
from transformers import pipeline
|
8 |
import datetime
|
9 |
+
import io
|
10 |
|
11 |
# Initialize Summarizer
|
12 |
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
|
|
14 |
# Polygon API Key
|
15 |
POLYGON_API_KEY = os.getenv("POLYGON_API_KEY")
|
16 |
|
17 |
+
# Sector Averages (Hardcoded for now)
|
18 |
+
sector_averages = {
|
19 |
+
"Technology": {"P/E Ratio": 25, "P/S Ratio": 5, "P/B Ratio": 6},
|
20 |
+
"Healthcare": {"P/E Ratio": 20, "P/S Ratio": 4, "P/B Ratio": 3},
|
21 |
+
"Financials": {"P/E Ratio": 15, "P/S Ratio": 2, "P/B Ratio": 1.5},
|
22 |
+
"Energy": {"P/E Ratio": 12, "P/S Ratio": 1.2, "P/B Ratio": 1.3},
|
23 |
+
}
|
24 |
+
|
25 |
# Helper Functions
|
26 |
def get_company_info(symbol):
|
27 |
api_key = os.getenv("POLYGON_API_KEY")
|
|
|
33 |
return {
|
34 |
'Name': data.get('name', 'N/A'),
|
35 |
'Industry': data.get('sic_description', 'N/A'),
|
36 |
+
'Sector': data.get('market', 'N/A'),
|
37 |
'Market Cap': data.get('market_cap', 0),
|
38 |
'Total Revenue': data.get('total_employees', 0) * 100000
|
39 |
}
|
|
|
95 |
'Dividend Yield (%)': dividend_yield
|
96 |
}
|
97 |
|
98 |
+
def compare_to_sector(sector, ratios):
|
99 |
+
averages = sector_averages.get(sector, None)
|
100 |
+
if not averages:
|
101 |
+
return pd.DataFrame({"Metric": ["Sector data not available"], "Value": ["N/A"]})
|
102 |
+
|
103 |
+
comparison = {}
|
104 |
+
for key in averages:
|
105 |
+
stock_value = ratios.get(key, 0)
|
106 |
+
sector_value = averages[key]
|
107 |
+
comparison[key] = f"{stock_value:.2f} vs Sector Avg {sector_value:.2f}"
|
108 |
+
return pd.DataFrame({"Ratio": list(comparison.keys()), "Comparison": list(comparison.values())})
|
109 |
+
|
110 |
def generate_summary(info, ratios):
|
111 |
text = (f"{info['Name']} operates in the {info['Industry']} sector. It has a market capitalization of "
|
112 |
f"${info['Market Cap']:,.2f}. The company exhibits a P/E ratio of {ratios['P/E Ratio']:.2f}, "
|
|
|
130 |
dates, prices = get_historical_prices(symbol)
|
131 |
|
132 |
if not info or not price:
|
133 |
+
return "Error fetching stock information.", None, None, None, None, None
|
134 |
|
135 |
ratios = calculate_ratios(info['Market Cap'], info['Total Revenue'], price, dividends['Dividend Amount'], assumed_eps, growth_rate, book_value)
|
136 |
summary = generate_summary(info, ratios)
|
137 |
+
sector_comp = compare_to_sector(info['Sector'], ratios)
|
138 |
|
139 |
fig, ax = plt.subplots()
|
140 |
ax.plot(dates, prices, label=f"{symbol} Price")
|
|
|
147 |
info_table = pd.DataFrame({"Metric": list(info.keys()), "Value": list(info.values())})
|
148 |
ratios_table = pd.DataFrame({"Ratio": list(ratios.keys()), "Value": list(ratios.values())})
|
149 |
|
150 |
+
return summary, info_table, ratios_table, sector_comp, fig
|
151 |
+
|
152 |
+
def download_report(info_table, ratios_table, sector_comp, summary):
|
153 |
+
buffer = io.StringIO()
|
154 |
+
info_table.to_csv(buffer, index=False)
|
155 |
+
buffer.write("\n")
|
156 |
+
ratios_table.to_csv(buffer, index=False)
|
157 |
+
buffer.write("\n")
|
158 |
+
sector_comp.to_csv(buffer, index=False)
|
159 |
+
buffer.write("\nSummary\n")
|
160 |
+
buffer.write(summary)
|
161 |
+
buffer.seek(0)
|
162 |
+
return buffer
|
163 |
|
164 |
with gr.Blocks() as iface:
|
165 |
with gr.Row():
|
166 |
+
symbol = gr.Textbox(label="Stock Symbol (e.g., AAPL)", info="Ticker symbol of the company to analyze.")
|
167 |
+
eps = gr.Number(label="Assumed EPS", value=5.0, info="Earnings Per Share (EPS) for P/E calculation.")
|
168 |
+
growth = gr.Number(label="Assumed Growth Rate", value=0.1, info="Expected annual growth rate for PEG.")
|
169 |
+
book = gr.Number(label="Assumed Book Value", value=500000000, info="Total net assets for P/B calculation.")
|
170 |
|
171 |
with gr.Tabs():
|
172 |
with gr.Tab("AI Research Summary"):
|
|
|
175 |
output_info = gr.Dataframe()
|
176 |
with gr.Tab("Valuation Ratios"):
|
177 |
output_ratios = gr.Dataframe()
|
178 |
+
with gr.Tab("Sector Comparison"):
|
179 |
+
output_sector = gr.Dataframe()
|
180 |
with gr.Tab("Historical Price Chart"):
|
181 |
output_chart = gr.Plot()
|
182 |
|
183 |
submit_btn = gr.Button("Run Analysis")
|
184 |
+
download_btn = gr.Button("Download Report")
|
185 |
+
file_output = gr.File()
|
186 |
|
187 |
submit_btn.click(
|
188 |
fn=stock_research,
|
189 |
inputs=[symbol, eps, growth, book],
|
190 |
+
outputs=[output_summary, output_info, output_ratios, output_sector, output_chart]
|
191 |
+
)
|
192 |
+
|
193 |
+
download_btn.click(
|
194 |
+
fn=download_report,
|
195 |
+
inputs=[output_info, output_ratios, output_sector, output_summary],
|
196 |
+
outputs=file_output
|
197 |
)
|
198 |
|
199 |
if __name__ == "__main__":
|
200 |
+
iface.launch()
|