File size: 4,769 Bytes
9b5b26a
 
c19d193
f604625
8fe992b
f604625
 
9b5b26a
 
f604625
9b5b26a
f604625
 
9b5b26a
 
 
 
 
 
f604625
9b5b26a
 
f604625
9b5b26a
f604625
9b5b26a
 
 
 
 
 
 
8c01ffb
f604625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
f604625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae7a494
f604625
 
ae7a494
f604625
e121372
f604625
 
 
 
13d500a
8c01ffb
f604625
9b5b26a
8c01ffb
f604625
861422e
 
9b5b26a
f604625
8c01ffb
8fe992b
f604625
8c01ffb
 
 
 
f604625
 
861422e
8fe992b
 
f604625
 
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
import datetime
import pytz
import yaml
import yfinance as yf

from smolagents import CodeAgent, HfApiModel, load_tool, tool
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI

# A dummy tool that does nothing (for demonstration)
@tool
def my_custom_tool(arg1: str, arg2: int) -> str:
    """A tool that does nothing yet.
    Args:
        arg1: the first argument
        arg2: the second argument
    """
    return "What magic will you build ?"

# Tool to get the current time in a given timezone.
@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """Fetches the current local time in the specified timezone.
    Args:
        timezone: A valid timezone string (e.g., 'America/New_York').
    """
    try:
        tz = pytz.timezone(timezone)
        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
        return f"The current local time in {timezone} is: {local_time}"
    except Exception as e:
        return f"Error fetching time for timezone '{timezone}': {str(e)}"

# Tool to fetch the current stock price using yfinance.
@tool
def get_current_stock_price(symbol: str) -> str:
    """Fetches the current stock price for the given stock symbol.
    
    Args:
        symbol: The stock ticker symbol (e.g., 'AAPL').
        
    Returns:
        A string reporting the current stock price.
    """
    try:
        ticker = yf.Ticker(symbol)
        price = ticker.info.get("regularMarketPrice", None)
        if price is None:
            return f"Could not fetch current price for {symbol}."
        return f"The current price of {symbol} is {price:.2f} USD."
    except Exception as e:
        return f"Error fetching current price for {symbol}: {str(e)}"

# Tool to fetch and summarize historical stock data using yfinance.
@tool
def get_stock_historical_data(symbol: str, timeline: str) -> str:
    """Fetches historical stock data for a given symbol and timeline.
    
    Args:
        symbol: The stock ticker symbol (e.g., 'AAPL').
        timeline: The timeframe for data. Acceptable values: '1h', '1day', '1week', '1year'.
        
    Returns:
        A summary string of the historical price data.
    """
    try:
        ticker = yf.Ticker(symbol)
        if timeline == "1h":
            # For 1h data, fetch 1 day of data at 1-minute intervals and take the last 60 minutes.
            df = ticker.history(period="1d", interval="1m").tail(60)
        elif timeline == "1day":
            df = ticker.history(period="1d", interval="5m")
        elif timeline == "1week":
            df = ticker.history(period="7d", interval="30m")
        elif timeline == "1year":
            df = ticker.history(period="1y", interval="1d")
        else:
            return f"Timeline '{timeline}' is not supported. Use '1h', '1day', '1week', or '1year'."
        
        if df.empty:
            return f"No historical data available for {symbol} over timeline {timeline}."
        
        start_price = df['Close'].iloc[0]
        end_price = df['Close'].iloc[-1]
        min_price = df['Close'].min()
        max_price = df['Close'].max()
        summary = (
            f"For {symbol} over {timeline}:\n"
            f"Start Price: {start_price:.2f} USD\n"
            f"End Price: {end_price:.2f} USD\n"
            f"Min Price: {min_price:.2f} USD\n"
            f"Max Price: {max_price:.2f} USD"
        )
        return summary
    except Exception as e:
        return f"Error fetching historical data for {symbol} over {timeline}: {str(e)}"

# Final answer tool that should always be included.
final_answer = FinalAnswerTool()

# Define the model with appropriate configuration.
model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',  # if overloaded, consider an alternative endpoint
    custom_role_conversions=None,
)

# Optional: Load an additional tool from the Hub (e.g., a text-to-image tool)
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)

# Load prompt templates from a YAML file.
with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)
    
# Initialize the CodeAgent with the new yfinance tools along with other tools.
agent = CodeAgent(
    model=model,
    tools=[final_answer, get_current_time_in_timezone, get_current_stock_price, get_stock_historical_data, my_custom_tool],
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name="TradingAgent",
    description="An AI agent that analyzes stock data using yfinance and advises on long-term trading decisions (buy, sell, or hold).",
    prompt_templates=prompt_templates
)

# Launch the Gradio UI to interact with the agent.
GradioUI(agent).launch()