Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -2,12 +2,6 @@ import pandas as pd
|
|
2 |
import numpy as np
|
3 |
import gradio as gr
|
4 |
import matplotlib.pyplot as plt
|
5 |
-
import requests
|
6 |
-
import os
|
7 |
-
from transformers import pipeline
|
8 |
-
|
9 |
-
# Initialize Summarizer
|
10 |
-
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
11 |
|
12 |
# Simple DCF Calculator Setup
|
13 |
def discounted_cash_flow(fcf, growth_rate, discount_rate, terminal_growth_rate, forecast_years=5):
|
@@ -30,64 +24,17 @@ def discounted_cash_flow(fcf, growth_rate, discount_rate, terminal_growth_rate,
|
|
30 |
|
31 |
return fcf_forecast, present_values, terminal_value, terminal_value_pv, total_value
|
32 |
|
33 |
-
def
|
34 |
-
api_key = os.getenv("POLYGON_API_KEY")
|
35 |
-
url = f"https://api.polygon.io/vX/reference/financials?ticker={symbol}&apiKey={api_key}"
|
36 |
-
try:
|
37 |
-
response = requests.get(url)
|
38 |
-
response.raise_for_status()
|
39 |
-
data = response.json()
|
40 |
-
fcf = data['results'][0]['financials']['cash_flow_statement']['free_cash_flow']['value']
|
41 |
-
return float(fcf)
|
42 |
-
except Exception as e:
|
43 |
-
print(f"DEBUG: Error fetching FCF for {symbol}: {e}")
|
44 |
-
return None
|
45 |
-
|
46 |
-
def get_current_stock_price(symbol):
|
47 |
-
api_key = os.getenv("POLYGON_API_KEY")
|
48 |
-
url = f"https://api.polygon.io/v2/aggs/ticker/{symbol}/prev?adjusted=true&apiKey={api_key}"
|
49 |
-
try:
|
50 |
-
response = requests.get(url)
|
51 |
-
response.raise_for_status()
|
52 |
-
data = response.json()
|
53 |
-
price = data['results'][0]['c'] # 'c' = close price
|
54 |
-
return float(price)
|
55 |
-
except Exception as e:
|
56 |
-
print(f"DEBUG: Error fetching current price for {symbol}: {e}")
|
57 |
-
return None
|
58 |
-
|
59 |
-
def generate_summary(symbol, intrinsic_value, market_price):
|
60 |
-
verdict = "undervalued ✅" if intrinsic_value > market_price else "overvalued ⚠️"
|
61 |
-
text = (
|
62 |
-
f"Based on a DCF analysis, the intrinsic value of {symbol} is estimated to be "
|
63 |
-
f"${intrinsic_value:,.2f} compared to its current market price of ${market_price:,.2f}. "
|
64 |
-
f"The stock appears {verdict}."
|
65 |
-
)
|
66 |
-
summary = summarizer(text, max_length=100, min_length=30, do_sample=False)[0]['summary_text']
|
67 |
-
return summary
|
68 |
-
|
69 |
-
def dcf_interface(symbol, growth_rate, discount_rate, terminal_growth_rate, forecast_years):
|
70 |
-
fcf = get_company_fcf(symbol)
|
71 |
-
if fcf is None:
|
72 |
-
empty_df = pd.DataFrame({"Error": ["Invalid symbol or no data available"]})
|
73 |
-
|
74 |
-
fig, ax = plt.subplots()
|
75 |
-
ax.text(0.5, 0.5, 'Error: Invalid Symbol', fontsize=12, ha='center')
|
76 |
-
ax.axis('off')
|
77 |
-
|
78 |
-
error_message = "⚠️ Error fetching financial data. Please check the symbol or try another company."
|
79 |
-
return empty_df, fig, error_message
|
80 |
-
|
81 |
fcf_forecast, present_values, terminal_value, terminal_value_pv, total_intrinsic_value = discounted_cash_flow(
|
82 |
fcf, growth_rate, discount_rate, terminal_growth_rate, forecast_years
|
83 |
)
|
84 |
-
|
85 |
df = pd.DataFrame({
|
86 |
'Year': list(range(1, forecast_years + 1)),
|
87 |
'Forecasted FCF ($)': fcf_forecast,
|
88 |
'Present Value of FCF ($)': present_values
|
89 |
})
|
90 |
|
|
|
91 |
fig, ax = plt.subplots()
|
92 |
ax.plot(df['Year'], df['Forecasted FCF ($)'], marker='o')
|
93 |
ax.set_title('Forecasted Free Cash Flow Over Time')
|
@@ -95,17 +42,17 @@ def dcf_interface(symbol, growth_rate, discount_rate, terminal_growth_rate, fore
|
|
95 |
ax.set_ylabel('Free Cash Flow ($)')
|
96 |
ax.grid(True)
|
97 |
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
return df, fig, summary
|
104 |
|
105 |
iface = gr.Interface(
|
106 |
fn=dcf_interface,
|
107 |
inputs=[
|
108 |
-
gr.
|
109 |
gr.Number(label="Annual Growth Rate (e.g., 0.06 for 6%)"),
|
110 |
gr.Number(label="Discount Rate (e.g., 0.08 for 8%)"),
|
111 |
gr.Number(label="Terminal Growth Rate (e.g., 0.025 for 2.5%)"),
|
@@ -114,13 +61,13 @@ iface = gr.Interface(
|
|
114 |
outputs=[
|
115 |
gr.Dataframe(label="DCF Forecast Table"),
|
116 |
gr.Plot(label="Free Cash Flow Forecast Chart"),
|
117 |
-
gr.Textbox(label="
|
118 |
],
|
119 |
examples=[
|
120 |
-
[
|
121 |
],
|
122 |
-
title="
|
123 |
-
description="
|
124 |
)
|
125 |
|
126 |
if __name__ == "__main__":
|
|
|
2 |
import numpy as np
|
3 |
import gradio as gr
|
4 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
# Simple DCF Calculator Setup
|
7 |
def discounted_cash_flow(fcf, growth_rate, discount_rate, terminal_growth_rate, forecast_years=5):
|
|
|
24 |
|
25 |
return fcf_forecast, present_values, terminal_value, terminal_value_pv, total_value
|
26 |
|
27 |
+
def dcf_interface(fcf, growth_rate, discount_rate, terminal_growth_rate, forecast_years):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
fcf_forecast, present_values, terminal_value, terminal_value_pv, total_intrinsic_value = discounted_cash_flow(
|
29 |
fcf, growth_rate, discount_rate, terminal_growth_rate, forecast_years
|
30 |
)
|
|
|
31 |
df = pd.DataFrame({
|
32 |
'Year': list(range(1, forecast_years + 1)),
|
33 |
'Forecasted FCF ($)': fcf_forecast,
|
34 |
'Present Value of FCF ($)': present_values
|
35 |
})
|
36 |
|
37 |
+
# Plot FCF
|
38 |
fig, ax = plt.subplots()
|
39 |
ax.plot(df['Year'], df['Forecasted FCF ($)'], marker='o')
|
40 |
ax.set_title('Forecasted Free Cash Flow Over Time')
|
|
|
42 |
ax.set_ylabel('Free Cash Flow ($)')
|
43 |
ax.grid(True)
|
44 |
|
45 |
+
summary = f"""
|
46 |
+
🏦 Total Intrinsic Value Estimate: ${total_intrinsic_value:,.2f}
|
47 |
+
Terminal Value (undiscounted): ${terminal_value:,.2f}
|
48 |
+
Present Value of Terminal Value: ${terminal_value_pv:,.2f}
|
49 |
+
"""
|
50 |
return df, fig, summary
|
51 |
|
52 |
iface = gr.Interface(
|
53 |
fn=dcf_interface,
|
54 |
inputs=[
|
55 |
+
gr.Number(label="Initial Free Cash Flow ($)"),
|
56 |
gr.Number(label="Annual Growth Rate (e.g., 0.06 for 6%)"),
|
57 |
gr.Number(label="Discount Rate (e.g., 0.08 for 8%)"),
|
58 |
gr.Number(label="Terminal Growth Rate (e.g., 0.025 for 2.5%)"),
|
|
|
61 |
outputs=[
|
62 |
gr.Dataframe(label="DCF Forecast Table"),
|
63 |
gr.Plot(label="Free Cash Flow Forecast Chart"),
|
64 |
+
gr.Textbox(label="Summary")
|
65 |
],
|
66 |
examples=[
|
67 |
+
[100_560_000_000, 0.06, 0.08, 0.025, 5] # Example: Apple
|
68 |
],
|
69 |
+
title="DCF Valuation Calculator",
|
70 |
+
description="Estimate a company's intrinsic value using Discounted Cash Flow (DCF) analysis. Adjust inputs or run a preset example."
|
71 |
)
|
72 |
|
73 |
if __name__ == "__main__":
|