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

Update app.py

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