Spaces:
Sleeping
Sleeping
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. | |
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. | |
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() | |