DEV Community

qing
qing

Posted on

Build a Time Series Forecasting App with Python

Build a Time Series Forecasting App with Python

Build a Time Series Forecasting App with Python

Imagine you’re staring at a spreadsheet of daily sales numbers, wondering if next month will be a boom or a bust. You could guess, but why not let Python predict the future with data-driven precision? Time series forecasting isn’t just for finance experts or data scientists in hoodies—it’s a practical tool you can build today to anticipate trends, optimize inventory, or even plan your next marketing push. And with Python, you don’t need a PhD to make it happen.

In this guide, you’ll build a working time series forecasting app from scratch using Python. We’ll use Facebook Prophet, a library that’s beginner-friendly but powerful enough for real-world use. By the end, you’ll have code you can drop into your own project and start forecasting tomorrow’s numbers.

Why Time Series Forecasting Matters

Time series data is any data collected over time—stock prices, website traffic, temperature readings, or daily sales. The goal of forecasting is to use past patterns to predict future values. This is crucial for:

  • Business planning: Predict demand to avoid overstocking or understocking.
  • Resource allocation: Forecast server usage to scale infrastructure efficiently.
  • Risk management: Anticipate market shifts or equipment failures.

Unlike standard regression, time series models account for trends, seasonality, and autocorrelation (where past values influence future ones). That’s why you can’t just throw your data into a random forest and call it a day.

The 5-Step Forecasting Workflow

Before diving into code, here’s the universal workflow for time series forecasting [1]:

  1. Gather, preprocess, and visualize your data.
  2. Split into training, validation, and testing sets.
  3. Build and fit a model (we’ll use Prophet).
  4. Generate and plot predictions.
  5. Evaluate performance with metrics like MAE or RMSE [1][5].

Let’s implement this step-by-step.

Step 1: Set Up Your Environment

First, install the necessary libraries. You’ll need pandas for data handling, matplotlib for plotting, and prophet for forecasting:

pip install pandas matplotlib prophet
Enter fullscreen mode Exit fullscreen mode

Note: fbprophet is the old name; the current package is prophet.

Step 2: Load and Visualize Your Data

We’ll use a sample dataset of daily sales. In practice, you’d load your own CSV:

import pandas as pd
import matplotlib.pyplot as plt
from prophet import Prophet

# Load data
data = pd.read_csv('sales_data.csv', parse_dates=['date'], index_col='date')

# Rename columns for Prophet
data = data.rename(columns={'sales': 'y', 'date': 'ds'})

# Visualize
data.plot(figsize=(10, 5))
plt.title("Daily Sales Over Time")
plt.xlabel("Date")
plt.ylabel("Sales")
plt.show()
Enter fullscreen mode Exit fullscreen mode

This gives you a quick look at trends and seasonality. If you see repeating peaks (e.g., every December), that’s seasonality. If sales are steadily rising, that’s a trend.

Step 3: Build and Fit the Prophet Model

Prophet automatically handles trends and seasonality. Here’s how to initialize and fit it:

# Initialize model
model = Prophet()

# Fit the model
model.fit(data)

# Create future dataframe (forecast 30 days)
future = model.make_future_dataframe(periods=30)
forecast = model.predict(future)
Enter fullscreen mode Exit fullscreen mode

The make_future_dataframe method creates dates for the next 30 days. model.predict() adds forecasted values (yhat) and confidence intervals (yhat_lower, yhat_upper).

Step 4: Plot Your Forecast

Now, let’s visualize the results:

# Plot forecast
fig = model.plot(forecast)
plt.title("Sales Forecast for Next 30 Days")
plt.xlabel("Date")
plt.ylabel("Sales")
plt.show()

# Plot components (trend, weekly, yearly seasonality)
fig2 = model.plot_components(forecast)
plt.show()
Enter fullscreen mode Exit fullscreen mode

The component plot reveals whether weekly patterns (e.g., higher sales on weekends) or yearly trends (e.g., holiday spikes) are driving your forecast.

Step 5: Evaluate Model Performance

To trust your forecast, you need to measure accuracy. Split your data into training and test sets, then compare predictions to actual values:

from sklearn.metrics import mean_absolute_error, mean_squared_error

# Split data
train = data.iloc[:-30]
test = data.iloc[-30:]

# Fit on training
model.fit(train)

# Forecast on test period
future_test = model.make_future_dataframe(periods=30)
forecast_test = model.predict(future_test)

# Evaluate
mae = mean_absolute_error(test['y'], forecast_test['yhat'])
rmse = mean_squared_error(test['y'], forecast_test['yhat'], squared=False)

print(f"MAE: {mae:.2f}")
print(f"RMSE: {rmse:.2f}")
Enter fullscreen mode Exit fullscreen mode

Lower MAE and RMSE mean better accuracy. If your metrics are high, try adding custom seasonality or adjusting the trend growth parameter.

Making It Actionable: Your Forecasting App Template

You can now wrap this into a reusable script or web app. Here’s a minimal template you can copy-paste and run today:

def forecast_sales(csv_path, forecast_days=30):
    import pandas as pd
    from prophet import Prophet
    from sklearn.metrics import mean_absolute_error

    # Load and prep data
    data = pd.read_csv(csv_path, parse_dates=['date'], index_col='date')
    data = data.rename(columns={'sales': 'y', 'date': 'ds'})

    # Split
    train = data.iloc[:-forecast_days]
    test = data.iloc[-forecast_days:]

    # Fit
    model = Prophet()
    model.fit(train)

    # Forecast
    future = model.make_future_dataframe(periods=forecast_days)
    forecast = model.predict(future)

    # Evaluate
    mae = mean_absolute_error(test['y'], forecast['yhat'])

    return forecast, mae

# Usage
forecast, mae = forecast_sales('sales_data.csv')
print(f"Forecast MAE: {mae:.2f}")
Enter fullscreen mode Exit fullscreen mode

Save this as forecast_app.py, drop in your CSV, and run:

python forecast_app.py
Enter fullscreen mode Exit fullscreen mode

Boom—you’ve got a forecasting app.

Bonus: Add Custom Seasonality

If your data has unique patterns (e.g., monthly promotions), Prophet lets you add them:

model.add_seasonality(name='monthly_promo', period=30, fourier_order=5)
Enter fullscreen mode Exit fullscreen mode

This tells Prophet to look for a 30-day repeating pattern.

What’s Next?

You’ve built a forecasting app that can predict sales, traffic, or any time-based metric. But don’t stop here:

  • Try other models: ARIMA, LSTM, or AutoTS for more complex patterns [4][7].
  • Deploy it: Wrap your script in a Flask app or export forecasts to a dashboard.
  • Automate: Run forecasts daily with a cron job or GitHub Actions.

Time series forecasting is a superpower in data-driven decision-making. With Python and Prophet, you’ve just unlocked it.

Your challenge: Take your own dataset, run this code, and share your forecast on Dev.to. Tag me in the comments—I’d love to see what you predict!


If you found this helpful, consider buying me a coffee ☕ — it keeps these articles coming!

Also check out my AI tools collection: AI 次元世界 — free AI tools for developers.

Top comments (0)