Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Real-time and historical stock and forex market data via Twelve Data API: quotes, OHLCV time series, and symbol search.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
tools/time_series.py
1"""2Twelve Data Time Series Tools — Historical OHLCV data for stocks and forex.34Provides tools for fetching historical price data and end-of-day prices.5"""67import logging89from core.tool import BaseTool, ToolContext, ToolResult10from .client import get_client, handle_api_error, INTERVALS1112logger = logging.getLogger(__name__)131415class TwelveDataTimeSeriesTools(BaseTool):16"""Get historical OHLCV time series data."""1718@property19def name(self) -> str:20return "twelvedata_time_series"2122@property23def description(self) -> str:24return """Get historical OHLCV (Open, High, Low, Close, Volume) time series data for stocks and forex pairs.2526Use this for historical price analysis, backtesting, and charting. Supports multiple intervals from 1-minute to monthly data.2728Parameters:29- symbol: Stock symbol (e.g., AAPL, MSFT, TSLA) or forex pair (e.g., EUR/USD, GBP/JPY)30- interval: Time interval - 1min, 5min, 15min, 30min, 1h, 4h, 1day, 1week, 1month (default: 1day)31- outputsize: Number of data points to return (1-5000, default: 30). Common values: 30 (compact), 100, 500, 5000 (maximum)32- start_date: (optional) Start date in YYYY-MM-DD format33- end_date: (optional) End date in YYYY-MM-DD format34- prepost: (optional) Include pre/post-market data when available (US/Cboe Europe, Pro+ only)3536Returns: Historical OHLCV data with metadata including symbol, exchange, currency, and interval"""3738@property39def parameters(self) -> dict:40return {41"type": "object",42"properties": {43"symbol": {44"type": "string",45"description": "Stock symbol (AAPL, MSFT) or forex pair (EUR/USD, GBP/JPY)",46},47"interval": {48"type": "string",49"description": "Time interval: 1min, 5min, 15min, 30min, 45min, 1h, 2h, 4h, 8h, 1day, 1week, 1month (default: 1day)",50"enum": INTERVALS,51},52"outputsize": {53"type": "integer",54"description": "Number of data points to return (1-5000). Default 30.",55"minimum": 1,56"maximum": 5000,57},58"start_date": {59"type": "string",60"description": "Start date in YYYY-MM-DD format (optional)",61},62"end_date": {63"type": "string",64"description": "End date in YYYY-MM-DD format (optional)",65},66"prepost": {67"type": "boolean",68"description": "Include pre/post-market data when available (US/Cboe Europe, Pro+ only)",69},70},71"required": ["symbol"],72}7374async def execute(75self,76ctx: ToolContext,77symbol: str = "",78interval: str = "1day",79outputsize: int = 30,80start_date: str = "",81end_date: str = "",82prepost: bool = False,83**kwargs,84) -> ToolResult:85if not symbol:86return ToolResult(success=False, error="'symbol' is required")87if interval not in INTERVALS:88return ToolResult(success=False, error=f"Invalid interval '{interval}'. Must be one of: {', '.join(INTERVALS)}")89try:90data = await get_client().get_time_series(91symbol=symbol,92interval=interval,93outputsize=outputsize,94start_date=start_date if start_date else None,95end_date=end_date if end_date else None,96prepost=prepost,97)98if data.get("status") == "error":99return ToolResult(success=False, error=f"API Error: {data.get('message', 'Unknown error')}")100return ToolResult(success=True, output=data)101except Exception as e:102return handle_api_error(e)103104105class TwelveDataPriceTool(BaseTool):106"""Get latest trading price for a stock or forex pair."""107108@property109def name(self) -> str:110return "twelvedata_price"111112@property113def description(self) -> str:114return """Get the latest available trading price for a stock or forex pair.115116This is a lightweight endpoint for quick price checks without full quote data.117118Parameters:119- symbol: Stock symbol (AAPL, MSFT) or forex pair (EUR/USD, GBP/JPY)120- prepost: (optional) Include pre/post-market data when available (US/Cboe Europe, Pro+ only)121122Returns: Current price value"""123124@property125def parameters(self) -> dict:126return {127"type": "object",128"properties": {129"symbol": {130"type": "string",131"description": "Stock symbol or forex pair",132},133"prepost": {134"type": "boolean",135"description": "Include pre/post-market data when available (US/Cboe Europe, Pro+ only)",136},137},138"required": ["symbol"],139}140141async def execute(self, ctx: ToolContext, symbol: str = "", prepost: bool = False, **kwargs) -> ToolResult:142if not symbol:143return ToolResult(success=False, error="'symbol' is required")144try:145data = await get_client().get_price(symbol=symbol, prepost=prepost)146if data.get("status") == "error":147return ToolResult(success=False, error=f"API Error: {data.get('message', 'Unknown error')}")148return ToolResult(success=True, output=data)149except Exception as e:150return handle_api_error(e)151152153class TwelveDataEODTool(BaseTool):154"""Get end-of-day closing price for a stock or forex pair."""155156@property157def name(self) -> str:158return "twelvedata_eod"159160@property161def description(self) -> str:162return """Get end-of-day (EOD) closing price for a stock or forex pair.163164Useful for daily analysis and reports. Returns the closing price for the most recent trading day or a specific date.165166Parameters:167- symbol: Stock symbol (AAPL, MSFT) or forex pair (EUR/USD, GBP/JPY)168- date: (optional) Specific date in YYYY-MM-DD format (defaults to latest available)169- prepost: (optional) Include pre/post-market data when available (US/Cboe Europe, Pro+ only)170171Returns: EOD price data with close, high, low, open, volume"""172173@property174def parameters(self) -> dict:175return {176"type": "object",177"properties": {178"symbol": {179"type": "string",180"description": "Stock symbol or forex pair",181},182"date": {183"type": "string",184"description": "Specific date in YYYY-MM-DD format (optional)",185},186"prepost": {187"type": "boolean",188"description": "Include pre/post-market data when available (US/Cboe Europe, Pro+ only)",189},190},191"required": ["symbol"],192}193194async def execute(self, ctx: ToolContext, symbol: str = "", date: str = "", prepost: bool = False, **kwargs) -> ToolResult:195if not symbol:196return ToolResult(success=False, error="'symbol' is required")197try:198data = await get_client().get_eod(199symbol=symbol,200date=date if date else None,201prepost=prepost,202)203if data.get("status") == "error":204return ToolResult(success=False, error=f"API Error: {data.get('message', 'Unknown error')}")205return ToolResult(success=True, output=data)206except Exception as e:207return handle_api_error(e)208