CCockrum commited on
Commit
dd6ec15
·
verified ·
1 Parent(s): 00c2ebd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -116
app.py CHANGED
@@ -90,123 +90,24 @@ def get_historical_prices(symbol):
90
  print(f"DEBUG: Error fetching historical prices: {e}")
91
  return [], []
92
 
93
- def calculate_ratios(market_cap, total_revenue, price, dividend_amount, assumed_eps=5.0, growth_rate=0.1, book_value=500000000):
94
- pe_ratio = price / assumed_eps if assumed_eps else 0
95
- ps_ratio = market_cap / total_revenue if total_revenue else 0
96
- pb_ratio = market_cap / book_value if book_value else 0
97
- peg_ratio = pe_ratio / (growth_rate * 100) if growth_rate else 0
98
- dividend_yield = (dividend_amount / price) * 100 if price else 0
99
- return {
100
- 'P/E Ratio': pe_ratio,
101
- 'P/S Ratio': ps_ratio,
102
- 'P/B Ratio': pb_ratio,
103
- 'PEG Ratio': peg_ratio,
104
- 'Dividend Yield (%)': dividend_yield
105
- }
106
-
107
- def compare_to_sector(sector, ratios):
108
- averages = sector_averages.get(sector, None)
109
- if not averages:
110
- return pd.DataFrame({"Metric": ["Sector data not available"], "Value": ["N/A"]})
111
- comparison = {}
112
- for key in averages:
113
- stock_value = ratios.get(key, 0)
114
- sector_value = averages[key]
115
- comparison[key] = f"{stock_value:.2f} vs Sector Avg {sector_value:.2f}"
116
- return pd.DataFrame({"Ratio": list(comparison.keys()), "Comparison": list(comparison.values())})
117
-
118
  def generate_summary(info, ratios):
119
- text = (
120
- f"{info['Name']} operates in the {info['Industry']} sector. It has a market capitalization of "
121
- f"${info['Market Cap']:,.2f}. The company exhibits a P/E ratio of {ratios['P/E Ratio']:.2f}, "
122
- f"P/S ratio of {ratios['P/S Ratio']:.2f}, and P/B ratio of {ratios['P/B Ratio']:.2f}. "
123
- f"Its dividend yield is {ratios['Dividend Yield (%)']:.2f}%. "
124
- f"This suggests a {'potential undervaluation' if ratios['P/E Ratio'] < 20 else 'higher valuation'} relative to the market."
 
 
 
 
 
 
 
 
 
125
  )
126
- summary = summarizer(text, max_length=120, min_length=30, do_sample=False)[0]['summary_text']
127
  return summary
128
 
129
- def stock_research(symbol, assumed_eps=5.0, growth_rate=0.1, book_value=500000000):
130
- if assumed_eps is None:
131
- assumed_eps = 5.0
132
- if growth_rate is None:
133
- growth_rate = 0.1
134
- if book_value is None:
135
- book_value = 500000000
136
-
137
- info = get_company_info(symbol)
138
- price = get_current_price(symbol)
139
- dividends = get_dividends(symbol)
140
- dates, prices = get_historical_prices(symbol)
141
-
142
- if not info or not price:
143
- return "Error fetching stock information.", None, None, None, None, None
144
-
145
- ratios = calculate_ratios(info['Market Cap'], info['Total Revenue'], price, dividends['Dividend Amount'], assumed_eps, growth_rate, book_value)
146
- summary = generate_summary(info, ratios)
147
- sector_comp = compare_to_sector(info['Sector'], ratios)
148
-
149
- fig, ax = plt.subplots()
150
- ax.plot(dates, prices, label=f"{symbol} Price")
151
- ax.set_title(f"{symbol} Historical Price (1 Year)")
152
- ax.set_xlabel("Date")
153
- ax.set_ylabel("Price ($)")
154
- ax.legend()
155
- ax.grid(True)
156
-
157
- info_table = pd.DataFrame({"Metric": list(info.keys()), "Value": list(info.values())})
158
- ratios_table = pd.DataFrame({"Ratio": list(ratios.keys()), "Value": list(ratios.values())})
159
-
160
- return summary, info_table, ratios_table, sector_comp, fig
161
-
162
- def download_report(info_table, ratios_table, sector_comp, summary):
163
- with tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode='w') as f:
164
- info_table.to_csv(f, index=False)
165
- f.write("\n")
166
- ratios_table.to_csv(f, index=False)
167
- f.write("\n")
168
- sector_comp.to_csv(f, index=False)
169
- f.write("\nSummary\n")
170
- f.write(summary)
171
- file_path = f.name
172
- return file_path
173
-
174
- # Gradio UI
175
- with gr.Blocks() as iface:
176
- with gr.Row():
177
- symbol = gr.Textbox(label="Stock Symbol (e.g., AAPL)", info="Ticker symbol of the company to analyze.")
178
- eps = gr.Number(label="Assumed EPS", value=5.0, info="Earnings Per Share (EPS) for P/E calculation.")
179
- growth = gr.Number(label="Assumed Growth Rate", value=0.1, info="Expected annual growth rate for PEG.")
180
- book = gr.Number(label="Assumed Book Value", value=500000000, info="Total net assets for P/B calculation.")
181
-
182
- with gr.Tabs():
183
- with gr.Tab("AI Research Summary"):
184
- output_summary = gr.Textbox()
185
- with gr.Tab("Company Snapshot"):
186
- output_info = gr.Dataframe()
187
- with gr.Tab("Valuation Ratios"):
188
- output_ratios = gr.Dataframe()
189
- with gr.Tab("Sector Comparison"):
190
- output_sector = gr.Dataframe()
191
- with gr.Tab("Historical Price Chart"):
192
- output_chart = gr.Plot()
193
-
194
- submit_btn = gr.Button("Run Analysis")
195
- download_btn = gr.Button("Download Report")
196
- file_output = gr.File()
197
-
198
- submit_btn.click(
199
- fn=stock_research,
200
- inputs=[symbol, eps, growth, book],
201
- outputs=[output_summary, output_info, output_ratios, output_sector, output_chart]
202
- )
203
-
204
- download_btn.click(
205
- fn=download_report,
206
- inputs=[output_info, output_ratios, output_sector, output_summary],
207
- outputs=file_output
208
- )
209
-
210
- if __name__ == "__main__":
211
- iface.launch()
212
-
 
90
  print(f"DEBUG: Error fetching historical prices: {e}")
91
  return [], []
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  def generate_summary(info, ratios):
94
+ recommendation = "Hold"
95
+ if ratios['P/E Ratio'] < 15 and ratios['P/B Ratio'] < 2:
96
+ recommendation = "Buy"
97
+ elif ratios['P/E Ratio'] > 30 and ratios['P/B Ratio'] > 5:
98
+ recommendation = "Sell"
99
+
100
+ prompt = (
101
+ f"Write a professional financial analysis about the company {info['Name']}. "
102
+ f"{info['Name']} operates in the {info['Industry']} industry within the {info['Sector']} sector. "
103
+ f"It has a market capitalization of approximately ${info['Market Cap']:,.2f}. "
104
+ f"The Price-to-Earnings (P/E) ratio is {ratios['P/E Ratio']:.2f}, "
105
+ f"Price-to-Sales (P/S) ratio is {ratios['P/S Ratio']:.2f}, "
106
+ f"Price-to-Book (P/B) ratio is {ratios['P/B Ratio']:.2f}, "
107
+ f"PEG ratio is {ratios['PEG Ratio']:.2f}, and dividend yield is {ratios['Dividend Yield (%)']:.2f}%. "
108
+ f"Based on these metrics, the recommended investment action is: {recommendation}."
109
  )
110
+ summary = summarizer(prompt, max_length=180, min_length=80, do_sample=False)[0]['summary_text']
111
  return summary
112
 
113
+ # (Rest of the code remains the same)