File size: 3,947 Bytes
9b5b26a
 
c19d193
f604625
8fe992b
f604625
 
9b5b26a
 
f604625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
b4eb62c
f604625
 
 
 
 
b4eb62c
f604625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae7a494
b4eb62c
f604625
ae7a494
b4eb62c
 
e121372
b4eb62c
f604625
b4eb62c
f604625
13d500a
8c01ffb
b4eb62c
9b5b26a
8c01ffb
b4eb62c
861422e
 
9b5b26a
b4eb62c
8c01ffb
8fe992b
b4eb62c
 
8c01ffb
 
 
f604625
b4eb62c
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
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

# 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 historical stock data for a given timeline 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., 'TSLA').
        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 (must be included)
final_answer = FinalAnswerTool()

# Define the model configuration.
# Here we reduce max_tokens to help keep the total token count below the limit.
model = HfApiModel(
    max_tokens=1000,  # Reduced from 2096 to reduce total token count
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
    custom_role_conversions=None,
)

# Optionally, 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 YAML.
with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)
    
# Initialize the CodeAgent with the new yfinance tools.
agent = CodeAgent(
    model=model,
    tools=[final_answer, get_current_stock_price, get_stock_historical_data],
    max_steps=3,  # Reduced steps to limit the chain-of-thought length
    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.",
    prompt_templates=prompt_templates
)

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