File size: 8,837 Bytes
226b286
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import os
import requests
import yfinance as yf

from agents import function_tool
from datetime import datetime, timedelta



# Load environment variables



# ============================================================
# 🔹 YAHOO FINANCE TOOLSET
# ============================================================
def _get_summary(symbol: str, period: str = "1d", interval: str = "1h") -> str:
    print(f"[DEBUG] get_summary called for symbol='{symbol}', period='{period}', interval='{interval}'")
    try:
        ticker = yf.Ticker(symbol)

        # Calculate start and end dates based on period
        end_date = datetime.today()
        if period.endswith("d"):
            days = int(period[:-1])
        elif period.endswith("mo"):
            days = int(period[:-2]) * 30
        elif period.endswith("y"):
            days = int(period[:-1]) * 365
        else:
            days = 30  # default 1 month
        start_date = end_date - timedelta(days=days)

        # Fetch recent data explicitly
        data = ticker.history(
            start=start_date.strftime("%Y-%m-%d"),
            end=end_date.strftime("%Y-%m-%d"),
            interval=interval
        )

        if data.empty:
            return f"No data found for symbol '{symbol}'."

        latest = data.iloc[-1]
        current_price = round(latest["Close"], 2)
        open_price = round(latest["Open"], 2)
        change = round(current_price - open_price, 2)
        pct_change = round((change / open_price) * 100, 2)

        info = ticker.info
        long_name = info.get("longName", symbol)
        currency = info.get("currency", "USD")

        formatted = [
            f"📈 {long_name} ({symbol})",
            f"Current Price: {current_price} {currency}",
            f"Change: {change} ({pct_change}%)",
            f"Open: {open_price} | High: {round(latest['High'], 2)} | Low: {round(latest['Low'], 2)}",
            f"Volume: {int(latest['Volume'])}",
            f"Period: {period} | Interval: {interval}",
        ]
        return "\n".join(formatted)

    except Exception as e:
        return f"Error fetching data for '{symbol}': {e}"

def _get_market_sentiment(symbol: str, period: str = "1mo") -> str:
    print(f"[DEBUG] get_market_sentiment called for symbol='{symbol}', period='{period}'")
    try:
        ticker = yf.Ticker(symbol)

        # Calculate start/end dynamically
        end_date = datetime.today()
        if period.endswith("d"):
            days = int(period[:-1])
        elif period.endswith("mo"):
            days = int(period[:-2]) * 30
        elif period.endswith("y"):
            days = int(period[:-1]) * 365
        else:
            days = 30
        start_date = end_date - timedelta(days=days)

        data = ticker.history(
            start=start_date.strftime("%Y-%m-%d"),
            end=end_date.strftime("%Y-%m-%d")
        )

        if data.empty:
            return f"No data for {symbol}."

        recent_change = data["Close"].iloc[-1] - data["Close"].iloc[0]
        pct_change = (recent_change / data["Close"].iloc[0]) * 100

        sentiment = "Neutral"
        if pct_change > 2:
            sentiment = "Bullish"
        elif pct_change < -2:
            sentiment = "Bearish"

        return f"{symbol} market sentiment ({period}): {sentiment} ({pct_change:.2f}% change)"

    except Exception as e:
        return f"Error fetching market sentiment for '{symbol}': {e}"

def _get_history(symbol: str, period: str = "1mo") -> str:
    print(f"[DEBUG] get_history called for symbol='{symbol}', period='{period}'")
    try:
        ticker = yf.Ticker(symbol)

        # Calculate start/end dynamically
        end_date = datetime.today()
        if period.endswith("d"):
            days = int(period[:-1])
        elif period.endswith("mo"):
            days = int(period[:-2]) * 30
        elif period.endswith("y"):
            days = int(period[:-1]) * 365
        else:
            days = 30
        start_date = end_date - timedelta(days=days)

        data = ticker.history(
            start=start_date.strftime("%Y-%m-%d"),
            end=end_date.strftime("%Y-%m-%d")
        )

        if data.empty:
            return f"No historical data found for '{symbol}'."
        return f"Historical data for {symbol} ({period}):\n{data.tail(5).to_string()}"

    except Exception as e:
        return f"Error fetching historical data for '{symbol}': {e}"

def _get_analyst_recommendations(symbol: str) -> str:
    print(f"[DEBUG] get_analyst_recommendations called for symbol='{symbol}'")
    try:
        ticker = yf.Ticker(symbol)
        recs = ticker.recommendations
        if recs is None or recs.empty:
             return f"No analyst recommendations found for {symbol}."
        
        # Format the last few recommendations
        latest = recs.tail(5)
        return f"Analyst Recommendations for {symbol}:\n{latest.to_string()}"
    except Exception as e:
         return f"Error fetching recommendations for '{symbol}': {e}"

def _get_earnings_calendar(symbol: str) -> str:
    print(f"[DEBUG] get_earnings_calendar called for symbol='{symbol}'")
    try:
        ticker = yf.Ticker(symbol)
        calendar = ticker.calendar
        if calendar is None:
            return f"No earnings calendar found for {symbol}."
        
        # Handle dict (new yfinance) or DataFrame (old yfinance)
        if isinstance(calendar, dict):
             if not calendar:
                 return f"No earnings calendar found for {symbol}."
        elif hasattr(calendar, 'empty') and calendar.empty:
             return f"No earnings calendar found for {symbol}."
            
        return f"Earnings Calendar for {symbol}:\n{calendar}"
    except Exception as e:
         return f"Error fetching earnings calendar for '{symbol}': {e}"
           
@function_tool
def get_summary(symbol: str, period: str = "1d", interval: str = "1h") -> str:
    """
    Fetch the latest summary information and intraday price data for a given ticker.
    Ensures recent data is retrieved by calculating start/end dates dynamically.

    Parameters:
    -----------
    symbol : str
        The ticker symbol (e.g., "AAPL", "GOOG", "BTC-USD").
    period : str, optional (default="1d")
        Time range for price data. Examples: "1d", "5d", "1mo", "3mo".
    interval : str, optional (default="1h")
        Granularity of the data. Examples: "1m", "5m", "1h", "1d".

    Returns:
    --------
    str
        A formatted string containing:
        - Company/ticker name
        - Current price and change
        - Open, High, Low prices
        - Volume
        - Period and interval used
    """
    return _get_summary(symbol, period, interval)
    
@function_tool
def get_market_sentiment(symbol: str, period: str = "1mo") -> str:
    """
    Analyze recent price changes and provide a simple market sentiment.
    Uses dynamic start/end dates to ensure recent data.

    This tool computes the percentage change over the specified period and
    classifies the sentiment as:
    - Bullish (if price increased >2%)
    - Bearish (if price decreased >2%)
    - Neutral (otherwise)

    Parameters:
    -----------
    symbol : str
        The ticker symbol (e.g., "AAPL", "GOOG", "BTC-USD").
    period : str, optional (default="1mo")
        Time range to analyze. Examples: "7d", "1mo", "3mo".

    Returns:
    --------
    str
        A human-readable sentiment string including percentage change.
    """
    return _get_market_sentiment(symbol, period)

@function_tool
def get_history(symbol: str, period: str = "1mo") -> str:
    """
    Fetch historical price data for a given ticker.
    Ensures recent data is retrieved dynamically using start/end dates.

    Parameters:
    -----------
    symbol : str
        The ticker symbol (e.g., "AAPL", "GOOG", "BTC-USD").
    period : str, optional (default="1mo")
        The length of historical data to retrieve. Examples: "1d", "5d", "1mo", "3mo", "1y", "5y".

    Returns:
    --------
    str
        A formatted string showing the last 5 rows of historical prices (Open, High, Low, Close, Volume).
    """
    return _get_history(symbol, period)

@function_tool
def get_analyst_recommendations(symbol: str) -> str:
    """
    Fetch analyst recommendations for a given ticker.
    
    Parameters:
    -----------
    symbol : str
        The ticker symbol.

    Returns:
    --------
    str
        Formatted string string of analyst recommendations.
    """
    return _get_analyst_recommendations(symbol)

@function_tool
def get_earnings_calendar(symbol: str) -> str:
    """
    Fetch the next earnings date for a ticker.

    Parameters:
    -----------
    symbol : str
        The ticker symbol.

    Returns:
    --------
    str
        Next earnings date info.
    """
    return _get_earnings_calendar(symbol)