Coding guides for building autonomous AI for time series to predict darts and hug faces
In this tutorial, we build an advanced proxy AI system that automatically processes time series to predict usage Dart The library is combined with a lightweight hug-face model for inference. We designed the agent to run in the perceptual-curation-action cycle, in which it first analyzes the patterns in the data, then selects the appropriate prediction model, generates predictions, and finally interprets and visualizes the results. By browsing this pipeline, we experience how proxy AI aggregates statistical modeling and natural language reasoning to make predictions accurate and interpretable. Check The complete code is 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 first install and import the required libraries, including darts for time series prediction, transformers for reasoning, and packages that support Pandas, Numpy, and Matplotlib. With these tools, we have established the foundation for establishing and running autonomous forecasting agents. Check The complete code is 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 timeline for thinking with a lightweight hug-face model and work with a combination of small dart models. We perceive the patterns (trend, volatility, seasonality), select the best model, and then train, predict and validate the reasons. Finally, we interpret predictions in simple language and visualize history and predictions. Check The complete code is here.
๐จ [Recommended Read] Vipe (Video Pose Engine): A powerful and universal 3D video annotation tool for space 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 clear trends, sine seasonality and random noise. This allows us to simulate realistic monthly data from 2020 to 2023 to test and demonstrate the agencyโs forecast workflow. Check The complete code is 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 proxy AI pipeline. We load comprehensive time series data, let the timetable perceive patterns, select the best models, interpret the results and ultimately visualize them by training and predicting actions. This completes an end-to-end autonomous perception, reasoning and action cycle.
In short, we see how autonomous agents analyze time series data, regarding the reasons for model selection, generate predictions and interpret their predictions in natural language. By combining the dart with the hug face, we create a compact and powerful framework that not only produces accurate predictions but also clearly conveys insights. We complete the loop through visualization and strengthen how proxy AI makes predictions more intuitive and interactive.
Check The complete code is here. Check out ours anytime Tutorials, codes and notebooks for github pages. Also, please stay tuned for us twitter And don’t forget to join us 100K+ ml reddit And subscribe Our newsletter. wait! Are you on the telegram? Now, you can also join us on Telegram.
Asif Razzaq is CEO of Marktechpost Media Inc. As a visionary entrepreneur and engineer, ASIF is committed to harnessing the potential of artificial intelligence to achieve social benefits. His recent effort is to launch Marktechpost, an artificial intelligence media platform that has an in-depth coverage of machine learning and deep learning news that can sound both technically, both through technical voices and be understood by a wide audience. The platform has over 2 million views per month, demonstrating its popularity among its audience.
๐Follow Marktechpost: Add us as the preferred source on Google.