tournas commited on
Commit
93c5a0a
·
verified ·
1 Parent(s): 352165f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -37
app.py CHANGED
@@ -3,7 +3,9 @@ import datetime
3
  import requests
4
  import pytz
5
  import yaml
 
6
  import os
 
7
  from tools.final_answer import FinalAnswerTool
8
  from Gradio_UI import GradioUI
9
 
@@ -11,52 +13,123 @@ api_key = os.getenv("ALPHAVANTAGE")
11
  if not api_key:
12
  raise ValueError("\u26a0\ufe0f Key is missing! Add it as a Secret in Hugging Face Spaces.")
13
 
14
- @tool
15
- def get_dcf_of_company(company_name: str) -> str:
16
- """A tool that retrieves the DCF of a company based on its name.
 
 
 
 
 
 
 
 
 
17
  Args:
18
- company_name: The name of the company.
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  """
20
  try:
21
- # Step 1: Retrieve the stock ticker symbol
22
- search_url = f'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={company_name}&apikey={api_key}'
23
- response = requests.get(search_url)
24
- data = response.json()
25
 
26
- if 'bestMatches' in data and len(data['bestMatches']) > 0:
27
- symbol = data['bestMatches'][0]['1. symbol']
28
- else:
29
- return f"No stock symbol found for company '{company_name}'."
30
-
31
- # Step 2: Retrieve the company's financial data
32
- overview_url = f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}&apikey={api_key}'
 
33
  response = requests.get(overview_url)
34
- overview = response.json()
 
 
 
 
 
35
 
36
- if not overview:
37
- return f"No financial data found for company with symbol '{symbol}'."
38
-
39
- # Extract necessary data
40
- free_cash_flow = float(overview.get('FreeCashFlow', 0))
41
- wacc = float(overview.get('WeightedAverageCostOfCapital', 0)) / 100
42
- growth_rate = float(overview.get('GrowthRate', 0)) / 100
43
 
44
- if free_cash_flow == 0 or wacc == 0:
45
- return f"Insufficient data to calculate DCF for company '{company_name}'."
46
-
47
- # Step 3: Calculate DCF
48
- dcf_value = 0
49
- years = 5 # Number of years for forecasting
50
 
51
- for year in range(1, years + 1):
52
- future_cash_flow = free_cash_flow * ((1 + growth_rate) ** year)
53
- discounted_cash_flow = future_cash_flow / ((1 + wacc) ** year)
54
- dcf_value += discounted_cash_flow
55
-
56
- return f"The Discounted Cash Flow (DCF) for company '{company_name}' is: ${dcf_value:,.2f}"
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  except Exception as e:
59
- return f"Error calculating DCF for company '{company_name}': {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  final_answer = FinalAnswerTool()
62
 
@@ -77,7 +150,7 @@ agent = CodeAgent(
77
  model=model,
78
  tools=[
79
  final_answer,
80
- get_dcf_of_company # Added the DCF tool here
81
  ],
82
  max_steps=6,
83
  verbosity_level=1,
 
3
  import requests
4
  import pytz
5
  import yaml
6
+ import pandas as pd
7
  import os
8
+ import json
9
  from tools.final_answer import FinalAnswerTool
10
  from Gradio_UI import GradioUI
11
 
 
13
  if not api_key:
14
  raise ValueError("\u26a0\ufe0f Key is missing! Add it as a Secret in Hugging Face Spaces.")
15
 
16
+
17
+ def calculate_dcf_valuation(
18
+ symbol: str,
19
+ api_key: str,
20
+ growth_rate: float = 0.15,
21
+ terminal_growth: float = 0.03,
22
+ discount_rate: float = 0.10,
23
+ years_to_project: int = 5
24
+ ) -> Dict[str, Union[float, str, List[float]]]:
25
+ """
26
+ Calculates the DCF valuation for a given stock symbol using Alpha Vantage data.
27
+
28
  Args:
29
+ symbol: Stock symbol (e.g., 'AAPL')
30
+ api_key: Alpha Vantage API key
31
+ growth_rate: Expected annual growth rate (default: 15%)
32
+ terminal_growth: Terminal growth rate (default: 3%)
33
+ discount_rate: Discount rate (default: 10%)
34
+ years_to_project: Number of years to project (default: 5)
35
+
36
+ Returns:
37
+ Dictionary containing:
38
+ - intrinsic_value: Calculated intrinsic value per share
39
+ - current_price: Current market price
40
+ - recommendation: Buy/Sell/Hold recommendation
41
+ - projected_cash_flows: List of projected cash flows
42
+ - error: Error message if any
43
  """
44
  try:
45
+ # Get cash flow data
46
+ cash_flow_url = f"https://www.alphavantage.co/query?function=CASH_FLOW&symbol={symbol}&apikey={api_key}"
47
+ response = requests.get(cash_flow_url)
48
+ cash_flow_data = response.json()
49
 
50
+ if "annualReports" not in cash_flow_data:
51
+ return {"error": "Unable to fetch cash flow data"}
52
+
53
+ # Get operating cash flow from most recent year
54
+ latest_cash_flow = float(cash_flow_data["annualReports"][0]["operatingCashflow"])
55
+
56
+ # Get shares outstanding
57
+ overview_url = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}&apikey={api_key}"
58
  response = requests.get(overview_url)
59
+ overview_data = response.json()
60
+ shares_outstanding = float(overview_data.get("SharesOutstanding", 0))
61
+
62
+ # Project future cash flows
63
+ projected_cash_flows = []
64
+ current_cash_flow = latest_cash_flow
65
 
66
+ for year in range(years_to_project):
67
+ current_cash_flow *= (1 + growth_rate)
68
+ projected_cash_flows.append(current_cash_flow)
 
 
 
 
69
 
70
+ # Calculate terminal value
71
+ terminal_value = (current_cash_flow * (1 + terminal_growth)) / (discount_rate - terminal_growth)
72
+ projected_cash_flows.append(terminal_value)
 
 
 
73
 
74
+ # Calculate present value of all cash flows
75
+ present_value = 0
76
+ for i, cash_flow in enumerate(projected_cash_flows):
77
+ present_value += cash_flow / ((1 + discount_rate) ** (i + 1))
 
 
78
 
79
+ # Calculate per share value
80
+ intrinsic_value = present_value / shares_outstanding
81
+
82
+ # Get current price
83
+ price_url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={api_key}"
84
+ response = requests.get(price_url)
85
+ price_data = response.json()
86
+ current_price = float(price_data["Global Quote"]["05. price"])
87
+
88
+ # Generate recommendation
89
+ margin_of_safety = 0.2 # 20% margin of safety
90
+ if intrinsic_value * (1 - margin_of_safety) > current_price:
91
+ recommendation = "Buy"
92
+ elif intrinsic_value * (1 + margin_of_safety) < current_price:
93
+ recommendation = "Sell"
94
+ else:
95
+ recommendation = "Hold"
96
+
97
+ return {
98
+ "intrinsic_value": round(intrinsic_value, 2),
99
+ "current_price": round(current_price, 2),
100
+ "recommendation": recommendation,
101
+ "projected_cash_flows": [round(cf, 2) for cf in projected_cash_flows],
102
+ "error": None
103
+ }
104
+
105
  except Exception as e:
106
+ return {"error": f"Error calculating DCF: {str(e)}"}
107
+
108
+ # Example of how to format it as an AI agent tool
109
+ @tool
110
+ def get_stock_dcf_valuation(symbol: str, api_key: str) -> str:
111
+ """
112
+ A tool that calculates the DCF valuation for a given stock symbol.
113
+
114
+ Args:
115
+ symbol: Stock symbol (e.g., 'AAPL')
116
+ api_key: Alpha Vantage API key
117
+
118
+ Returns:
119
+ A string containing the DCF analysis results or error message
120
+ """
121
+ result = calculate_dcf_valuation(symbol, api_key)
122
+
123
+ if result.get("error"):
124
+ return result["error"]
125
+
126
+ return (
127
+ f"DCF Analysis for {symbol}:\n"
128
+ f"Intrinsic Value: ${result['intrinsic_value']}\n"
129
+ f"Current Price: ${result['current_price']}\n"
130
+ f"Recommendation: {result['recommendation']}\n"
131
+ f"Projected Cash Flows: {result['projected_cash_flows']}"
132
+ )
133
 
134
  final_answer = FinalAnswerTool()
135
 
 
150
  model=model,
151
  tools=[
152
  final_answer,
153
+ get_stock_dcf_valuation # Added the DCF tool here
154
  ],
155
  max_steps=6,
156
  verbosity_level=1,