tournas commited on
Commit
f0f828c
·
verified ·
1 Parent(s): a88ce85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -21
app.py CHANGED
@@ -3,35 +3,133 @@ import datetime
3
  import requests
4
  import pytz
5
  import yaml
 
 
 
6
  from tools.final_answer import FinalAnswerTool
7
 
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
- # @tool
12
- # def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- # #Keep this format for the description / args / args description but feel free to modify the tool
14
- # """A tool that does nothing yet
15
- # Args:
16
- # arg1: the first argument
17
- # arg2: the second argument
18
- # """
19
- # return "What magic will you build ?"
20
 
21
- @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
 
 
 
 
 
 
 
 
 
 
24
  Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  """
27
  try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
 
37
  final_answer = FinalAnswerTool()
@@ -56,7 +154,7 @@ with open("prompts.yaml", 'r') as stream:
56
  agent = CodeAgent(
57
  model=model,
58
  tools=[final_answer,
59
- get_current_time_in_timezone], ## add your tools here (don't remove final answer)
60
  max_steps=6,
61
  verbosity_level=1,
62
  grammar=None,
 
3
  import requests
4
  import pytz
5
  import yaml
6
+ import pandas as pd
7
+ from typing import Dict, Union, List
8
+ import json
9
  from tools.final_answer import FinalAnswerTool
10
 
11
  from Gradio_UI import GradioUI
12
 
13
+ api_key = os.getenv("ALPHAVANTAGE")
 
 
 
 
 
 
 
 
 
14
 
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
 
135
  final_answer = FinalAnswerTool()
 
154
  agent = CodeAgent(
155
  model=model,
156
  tools=[final_answer,
157
+ get_stock_dcf_valuation], ## add your tools here (don't remove final answer)
158
  max_steps=6,
159
  verbosity_level=1,
160
  grammar=None,