AI

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

In this tutorial, we create an advanced AIC system that deals with temporal chains independently using Arrows Library along with a lightweight embracing model for thinking. We design the agent to work in the perception and construction course, as it first analyzes the patterns in data, then chooses the appropriate prediction form, generates predictions, and finally explains and visualizes the results. By walking through this pipeline, we test how artificial intelligence agent can collect statistical modeling and natural linguistic logic to make prediction accurate and interpretation. verify 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 start to install and import basic libraries, including arrows to predict a time chain, thinking transformers, and support beams such as Pandas, Numby and MATPLOTLIB. With these tools, we created the basis for building an independent prediction agent. verify 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) < 24:
           return False
       acf = np.correlate(series - series.mean(), series - series.mean(), mode="full")
       acf = acf[len(acf)//2:]
       acf /= acf[0]
       return np.max(acf[12:24]) > 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 group of time considering with a lightweight embracing model and behaves with a small set of arrows models. We realize patterns (direction, fluctuation, seasonal), reason for choosing the best model, then training, prediction, and validation. Finally, we show the prediction in a clear language and we photograph the date for prediction. verify Full codes here.

๐Ÿšจ [Recommended Read] VIPE (Video Engine): A powerful and multi -dimensional 3D video explanation tool

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 Create_sample_Data () assistant function that creates artificial chain data with a clear and sectarian trend and random noise. This allows us to simulate realistic monthly data from 2020 to 2023 to test and show the progress of the agent. verify 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 manages the AI โ€‹โ€‹Agencial pipeline. We download artificial chains data, let Timeseriesagement realize patterns, the reason for identifying the best model, acting by training and prediction, explaining the results, and finally visualizing them. This complements the independent vision from one side to the end, logic, and the work cycle.

In conclusion, we see how the independent agent can analyze the time chains data, the reason for choosing the model, create predictions, and explain its predictions in the natural language. By combining arrows with Hugingface, we create a compressed framework but not only produce accurate predictions but also convey ideas clearly. We complete the course with the perception, and increase how Agenceic AI makes prediction more intuitive and interactive.


verify Full codes here. Do not hesitate to check our GitHub page for lessons, symbols and notebooks. Also, do not hesitate to follow us twitter And do not forget to join 100K+ ML Subreddit And subscribe to Our newsletter. I am waiting! Are you on a telegram? Now you can join us on Telegram as well.


Asif Razzaq is the CEO of Marktechpost Media Inc .. As a pioneer and vision engineer, ASIF is committed to harnessing the potential of artificial intelligence for social goodness. His last endeavor is to launch the artificial intelligence platform, Marktechpost, which highlights its in -depth coverage of machine learning and deep learning news, which is technically intact and can be easily understood by a wide audience. The platform is proud of more than 2 million monthly views, which shows its popularity among the masses.

๐Ÿ™Œ Follow Marktechpost: We added as a favorite source on Google.

Donโ€™t miss more hot News like this! Click here to discover the latest in AI news!

2025-10-04 03:33:00

Related Articles

Back to top button