pimvic commited on
Commit
de95b1a
·
verified ·
1 Parent(s): 9c82bcf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -23
app.py CHANGED
@@ -3,13 +3,17 @@ import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
- from tools.final_answer import FinalAnswerTool
7
- #import yfinance as yf
8
  import logging
9
  from typing import Optional, Dict, Any
 
10
 
11
  from Gradio_UI import GradioUI
12
 
 
 
 
 
13
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
14
  @tool
15
  def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
@@ -42,9 +46,6 @@ final_answer = FinalAnswerTool()
42
 
43
  @tool
44
  def get_current_stock_price(ticker_symbol: str) -> Optional[Dict[str, Any]]:
45
- logger = logging.getLogger(__name__)
46
- logger.setLevel(logging.DEBUG)
47
-
48
  """
49
  Get the latest stock price for the given ticker symbol by querying Yahoo Finance directly,
50
  then calculate the price change over the last 5 days (percentage and absolute).
@@ -53,30 +54,23 @@ def get_current_stock_price(ticker_symbol: str) -> Optional[Dict[str, Any]]:
53
  ticker_symbol: The stock ticker symbol to fetch the price for.
54
 
55
  Returns:
56
- A dictionary containing:
57
  - "price" : current closing price (float)
58
  - "price_change" : absolute change over 5 days (float)
59
  - "price_change_percent" : percent change over 5 days (float)
60
-
61
- If there's an error or no data is available, returns a dict with an "error" key, e.g.
62
- {"error": "No historical data available for TSLA"}
63
- Or returns None for unexpected issues.
64
  """
65
  try:
66
- # Build the Yahoo Finance “chart” API URL for the last 5 calendar days.
67
  url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker_symbol}"
68
  params = {
69
  "range": "5d",
70
  "interval": "1d",
71
- # We only need daily closes, so the default interval=1d is fine.
72
  }
73
 
74
  resp = requests.get(url, params=params, timeout=10)
75
  resp.raise_for_status()
76
  data = resp.json()
77
 
78
- # Drill into the JSON structure:
79
- # data["chart"]["result"][0]["indicators"]["quote"][0]["close"]
80
  chart = data.get("chart", {})
81
  if not chart or chart.get("error"):
82
  return {"error": f"Yahoo Finance returned an error for {ticker_symbol}."}
@@ -89,23 +83,16 @@ def get_current_stock_price(ticker_symbol: str) -> Optional[Dict[str, Any]]:
89
  if not quote_section:
90
  return {"error": f"No quote information in chart for {ticker_symbol}."}
91
 
92
- closes = quote_section[0].get("close", [])
93
- # The “close” array may contain nulls if the market was closed on a given day.
94
- # Filter out any None values:
95
- closes = [c for c in closes if (c is not None)]
96
 
97
  if len(closes) < 2:
98
- return {"error": f"Not enough close‐price data (need at least 2 days) for {ticker_symbol}."}
99
 
100
- # The “closes” list is chronological; last element is the most recent closing price:
101
  first_price = closes[0]
102
  current_price = closes[-1]
103
-
104
- # Calculate changes:
105
  price_change = current_price - first_price
106
  price_change_percent = (price_change / first_price) * 100 if first_price != 0 else 0.0
107
 
108
- # Round everything to two decimals:
109
  return {
110
  "price": round(current_price, 2),
111
  "price_change": round(price_change, 2),
@@ -125,9 +112,12 @@ def get_current_stock_price(ticker_symbol: str) -> Optional[Dict[str, Any]]:
125
  logger.error(f"Unexpected error fetching price for {ticker_symbol}: {e}")
126
  return None
127
 
 
 
128
  final_answer = FinalAnswerTool()
129
 
130
 
 
131
  # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
132
  # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
133
 
 
3
  import requests
4
  import pytz
5
  import yaml
6
+ import requests
 
7
  import logging
8
  from typing import Optional, Dict, Any
9
+ from tools.final_answer import FinalAnswerTool # Adjust if FinalAnswerTool is defined elsewhere
10
 
11
  from Gradio_UI import GradioUI
12
 
13
+ logger = logging.getLogger(__name__)
14
+ logger.setLevel(logging.DEBUG)
15
+
16
+
17
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
18
  @tool
19
  def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
 
46
 
47
  @tool
48
  def get_current_stock_price(ticker_symbol: str) -> Optional[Dict[str, Any]]:
 
 
 
49
  """
50
  Get the latest stock price for the given ticker symbol by querying Yahoo Finance directly,
51
  then calculate the price change over the last 5 days (percentage and absolute).
 
54
  ticker_symbol: The stock ticker symbol to fetch the price for.
55
 
56
  Returns:
57
+ A dictionary with:
58
  - "price" : current closing price (float)
59
  - "price_change" : absolute change over 5 days (float)
60
  - "price_change_percent" : percent change over 5 days (float)
61
+ If there's an error, returns a dict with an "error" key.
 
 
 
62
  """
63
  try:
 
64
  url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker_symbol}"
65
  params = {
66
  "range": "5d",
67
  "interval": "1d",
 
68
  }
69
 
70
  resp = requests.get(url, params=params, timeout=10)
71
  resp.raise_for_status()
72
  data = resp.json()
73
 
 
 
74
  chart = data.get("chart", {})
75
  if not chart or chart.get("error"):
76
  return {"error": f"Yahoo Finance returned an error for {ticker_symbol}."}
 
83
  if not quote_section:
84
  return {"error": f"No quote information in chart for {ticker_symbol}."}
85
 
86
+ closes = [c for c in quote_section[0].get("close", []) if c is not None]
 
 
 
87
 
88
  if len(closes) < 2:
89
+ return {"error": f"Not enough close‐price data for {ticker_symbol}."}
90
 
 
91
  first_price = closes[0]
92
  current_price = closes[-1]
 
 
93
  price_change = current_price - first_price
94
  price_change_percent = (price_change / first_price) * 100 if first_price != 0 else 0.0
95
 
 
96
  return {
97
  "price": round(current_price, 2),
98
  "price_change": round(price_change, 2),
 
112
  logger.error(f"Unexpected error fetching price for {ticker_symbol}: {e}")
113
  return None
114
 
115
+
116
+ # Required for SmolAgent to emit a final structured response
117
  final_answer = FinalAnswerTool()
118
 
119
 
120
+
121
  # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
122
  # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
123