ai
  • Crypto News
  • Ai
  • eSports
  • Bitcoin
  • Ethereum
  • Blockchain
Home»Ai»A Coding Guide to Build an Autonomous Agentic AI for Time Series Forecasting with Darts and Hugging Face
Ai

A Coding Guide to Build an Autonomous Agentic AI for Time Series Forecasting with Darts and Hugging Face

Share
Facebook Twitter LinkedIn Pinterest Email

In this tutorial, we build an advanced agentic AI system that autonomously handles time series forecasting using the Darts library combined with a lightweight HuggingFace model for reasoning. We design the agent to operate in a perception–reasoning–action cycle, where it first analyzes patterns in the data, then selects an appropriate forecasting model, generates predictions, and finally explains and visualizes the results. By walking through this pipeline, we experience how agentic AI can bring together statistical modeling and natural language reasoning to make forecasting both accurate and interpretable. Check out the FULL CODES here.

!pip install darts transformers pandas matplotlib numpy -q


import pandas as pd
import numpy as np
from darts import TimeSeries
from darts.models import ExponentialSmoothing, NaiveSeasonal, LinearRegressionModel
from darts.metrics import mape, rmse
from transformers import pipeline
import matplotlib.pyplot as plt
from datetime import datetime, timedelta

We begin by installing and importing the essential libraries, including Darts for time series forecasting, Transformers for reasoning, and supporting packages like pandas, NumPy, and matplotlib. With these tools in place, we set up the foundation to build and run our autonomous forecasting agent. Check out the FULL CODES here.

class TimeSeriesAgent:
   """Autonomous agent for time series analysis and forecasting"""
  
   def __init__(self):
       print("🤖 Initializing Agent Brain...")
       self.llm = pipeline("text-generation", model="distilgpt2", max_length=150,
                          do_sample=True, temperature=0.7)
      
       self.models = {
           'exponential_smoothing': ExponentialSmoothing(),
           'naive_seasonal': NaiveSeasonal(K=12),
           'linear_regression': LinearRegressionModel(lags=12)
       }
       self.selected_model = None
       self.forecast = None
      
   def perceive(self, data):
       """Agent perceives and analyzes the time series data"""
       print("\n👁️  PERCEPTION PHASE")
       self.ts = TimeSeries.from_dataframe(data, 'date', 'value', freq='M')
      
       trend = "increasing" if data['value'].iloc[-1] > data['value'].iloc[0] else "decreasing"
       volatility = data['value'].std() / data['value'].mean()
       seasonality = self._detect_seasonality(data['value'])
      
       analysis = {
           'length': len(data),
           'trend': trend,
           'volatility': f"{volatility:.2f}",
           'has_seasonality': seasonality,
           'mean': f"{data['value'].mean():.2f}",
           'range': f"{data['value'].min():.2f} to {data['value'].max():.2f}"
       }
      
       print(f"📊 Data Points: {analysis['length']}")
       print(f"📈 Trend: {analysis['trend'].upper()}")
       print(f"🎲 Volatility: {analysis['volatility']}")
       print(f"🔄 Seasonality: {'Detected' if seasonality else 'Not detected'}")
      
       return analysis
  
   def _detect_seasonality(self, series, threshold=0.3):
       """Simple seasonality detection"""
       if len(series)  threshold if len(acf) > 24 else False
  
   def reason(self, analysis):
       """Agent reasons about which model to use"""
       print("\n🧠 REASONING PHASE")
      
       prompt = f"Time series analysis: {analysis['length']} data points, {analysis['trend']} trend, " \
                f"volatility {analysis['volatility']}, seasonality: {analysis['has_seasonality']}. "
      
       thought = self.llm(prompt, max_length=100, num_return_sequences=1)[0]['generated_text']
       print(f"💭 Agent Thinking: {thought[:150]}...")
      
       if analysis['has_seasonality']:
           self.selected_model="naive_seasonal"
           reason = "Seasonality detected - using Naive Seasonal model"
       elif float(analysis['volatility']) > 0.3:
           self.selected_model="exponential_smoothing"
           reason = "High volatility - using Exponential Smoothing"
       else:
           self.selected_model="linear_regression"
           reason = "Stable trend - using Linear Regression"
      
       print(f"✅ Decision: {reason}")
       return self.selected_model
  
   def act(self, horizon=12):
       """Agent takes action: trains model and generates forecast"""
       print("\n⚡ ACTION PHASE")
      
       train, val = self.ts[:-12], self.ts[-12:]
      
       model = self.models[self.selected_model]
       print(f"🎯 Training {self.selected_model}...")
       model.fit(train)
      
       self.forecast = model.predict(horizon)
      
       if len(val) > 0:
           val_pred = model.predict(len(val))
           accuracy = 100 - mape(val, val_pred)
           print(f"📊 Validation Accuracy: {accuracy:.2f}%")
      
       print(f"🔮 Generated {horizon}-step forecast")
       return self.forecast
  
   def explain(self):
       """Agent explains its predictions"""
       print("\n💬 EXPLANATION PHASE")
      
       forecast_values = self.forecast.values().flatten()
       hist_values = self.ts.values().flatten()
      
       change = ((forecast_values[-1] - hist_values[-1]) / hist_values[-1]) * 100
       direction = "increase" if change > 0 else "decrease"
      
       explanation = f"Based on my analysis using {self.selected_model}, " \
                    f"I predict a {abs(change):.1f}% {direction} in the next period. " \
                    f"Forecast range: {forecast_values.min():.2f} to {forecast_values.max():.2f}. " \
                    f"Historical mean was {hist_values.mean():.2f}."
      
       print(f"📝 {explanation}")
      
       prompt = f"Forecast summary: {explanation} Explain implications:"
       summary = self.llm(prompt, max_length=120)[0]['generated_text']
       print(f"\n🤖 Agent Summary: {summary[:200]}...")
      
       return explanation
  
   def visualize(self):
       """Agent creates visualization of its work"""
       print("\n📊 Generating visualization...")
      
       plt.figure(figsize=(14, 6))
      
       self.ts.plot(label="Historical Data", lw=2)
      
       self.forecast.plot(label=f'Forecast ({self.selected_model})',
                         lw=2, linestyle="--")
      
       plt.title('🤖 Agentic AI Time Series Forecast', fontsize=16, fontweight="bold")
       plt.xlabel('Date', fontsize=12)
       plt.ylabel('Value', fontsize=12)
       plt.legend(loc="best", fontsize=11)
       plt.grid(True, alpha=0.3)
       plt.tight_layout()
       plt.show()

We define a TimeSeriesAgent that thinks with a lightweight HuggingFace model and acts with a small portfolio of Darts models. We perceive patterns (trend, volatility, seasonality), reason to choose the best model, then train, forecast, and validate. Finally, we explain the prediction in plain language and visualize history versus forecast. Check out the FULL CODES here.

🚨 [Recommended Read] ViPE (Video Pose Engine): A Powerful and Versatile 3D Video Annotation Tool for Spatial AI
def create_sample_data():
   """Generate sample time series data"""
   dates = pd.date_range(start="2020-01-01", periods=48, freq='M')
   trend = np.linspace(100, 150, 48)
   seasonality = 10 * np.sin(np.linspace(0, 4*np.pi, 48))
   noise = np.random.normal(0, 3, 48)
   values = trend + seasonality + noise
  
   return pd.DataFrame({'date': dates, 'value': values})

We create a helper function create_sample_data() that generates synthetic time series data with a clear trend, sinusoidal seasonality, and random noise. This allows us to simulate realistic monthly data from 2020 to 2023 for testing and demonstrating the agent’s forecasting workflow. Check out the FULL CODES here.

def main():
   """Main execution: Agent autonomously handles forecasting task"""
   print("="*70)
   print("🚀 AGENTIC AI TIME SERIES FORECASTING SYSTEM")
   print("="*70)
  
   print("\n📥 Loading data...")
   data = create_sample_data()
   print(f"Loaded {len(data)} data points from 2020-01 to 2023-12")
  
   agent = TimeSeriesAgent()
  
   analysis = agent.perceive(data)
   agent.reason(analysis)
   agent.act(horizon=12)
   agent.explain()
   agent.visualize()
  
   print("\n" + "="*70)
   print("✅ AGENT COMPLETED FORECASTING TASK SUCCESSFULLY")
   print("="*70)


if __name__ == "__main__":
   main()

We define the main function that runs the full agentic AI pipeline. We load synthetic time series data, let the TimeSeriesAgent perceive patterns, reason to select the best model, act by training and forecasting, explain the results, and finally visualize them. This completes the end-to-end autonomous perception, reasoning, and action cycle.

In conclusion, we see how an autonomous agent can analyze time series data, reason about model selection, generate forecasts, and explain its predictions in natural language. By combining Darts with HuggingFace, we create a compact yet powerful framework that not only produces accurate forecasts but also clearly communicates insights. We complete the cycle with visualization, reinforcing how agentic AI makes forecasting more intuitive and interactive.


Check out the FULL CODES here. Feel free to check out our GitHub Page for Tutorials, Codes and Notebooks. Also, feel free to follow us on Twitter and don’t forget to join our 100k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.


Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is committed to harnessing the potential of Artificial Intelligence for social good. His most recent endeavor is the launch of an Artificial Intelligence Media Platform, Marktechpost, which stands out for its in-depth coverage of machine learning and deep learning news that is both technically sound and easily understandable by a wide audience. The platform boasts of over 2 million monthly views, illustrating its popularity among audiences.

🙌 Follow MARKTECHPOST: Add us as a preferred source on Google.

Share. Facebook Twitter Pinterest LinkedIn Tumblr Email

Related Posts

AI maps how a new antibiotic targets gut bacteria | MIT News

octobre 3, 2025

The Download: using AI to discover “zero day” vulnerabilities, and Apple’s ICE app removal

octobre 3, 2025

How to Build an Advanced Voice AI Pipeline with WhisperX for Transcription, Alignment, Analysis, and Export?

octobre 3, 2025

Lincoln Lab unveils the most powerful AI supercomputer at any US university | MIT News

octobre 3, 2025
Add A Comment

Comments are closed.

Top Posts

SwissCryptoDaily.ch delivers the latest cryptocurrency news, market insights, and expert analysis. Stay informed with daily updates from the world of blockchain and digital assets.

We're social. Connect with us:

Facebook X (Twitter) Instagram Pinterest YouTube
Top Insights

YEKINDAR Performs Heroics to Save FURIA from ESL Pro League Embarrassment

octobre 4, 2025

SEC Hit By 30+ ETF Applications On Friday

octobre 4, 2025

KC’s Kameto claim LEC teams didn’t agree to Los Ratones joining

octobre 4, 2025
Get Informed

Subscribe to Updates

Get the latest creative news from FooBar about art, design and business.

Facebook X (Twitter) Instagram Pinterest
  • About us
  • Get In Touch
  • Cookies Policy
  • Privacy-Policy
  • Terms and Conditions
© 2025 Swisscryptodaily.ch.

Type above and press Enter to search. Press Esc to cancel.