xenjin450's picture
Update app.py
f604625 verified
raw
history blame
4.77 kB
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()