Time series forecasting is one of the most practical skills a Nigerian data analyst can have. It answers one of the most common questions in every Nigerian business: what will happen next?

What will our sales be next month? How much stock do we need? How many transactions will we process next quarter? These are time series questions. And Python is one of the best tools in the world for answering them.

This guide takes you step by step through building your first time series forecasting model in Python. It is written for Nigerian analysts who know the basics of Python and want to apply them to a real forecasting task. No prior forecasting experience is needed.

Lagos Data School made this guide as part of our Python analytics training series. We teach time series forecasting to Nigerian analysts every week. This guide follows the same structure we use in our live sessions.

 

What Is a Time Series?

A time series is simply a set of data points collected over time, at regular intervals. Daily sales figures. Weekly transaction counts. Monthly revenue. Annual production output. All of these are time series.

What makes time series data special is that the order of the data points matters. The sales figure from last Monday affects what we expect from this Monday. The revenue from last December shapes what we expect from this December. Time series models use these time-based patterns to make predictions.

 

The Three Core Patterns to Look For

Before you build any forecasting model, you need to understand the three core patterns that time series data can contain.

Trend

A trend is a long-term direction in the data. Sales growing steadily over three years is a trend. Transaction volume falling gradually as a competitor gains market share is a trend. Not all time series have a clear trend, but when one exists, your model needs to account for it.

Seasonality

Seasonality is a repeating pattern that comes back at regular intervals. Nigerian retail sales often peak around Christmas, Eid, and school term starts. Transaction volumes often spike on Fridays. These regular, repeating patterns are seasonal patterns. They are very common in Nigerian business data.

Noise

Noise is the random variation that remains after you account for trend and seasonality. No model can predict noise. The goal is to capture the trend and seasonal patterns accurately so that the only thing left unexplained is genuinely random variation.

 

The Tools You Need

To follow this guide, you need Python installed on your computer along with a few libraries. Open your terminal and run this command to install what you need.

pip install pandas matplotlib prophet scikit-learn

If you are using a Jupyter notebook or Google Colab, which Lagos Data School recommends for beginners, you can add a ! before pip install and run it directly in a cell. Google Colab is completely free and requires no setup on your own machine, which makes it ideal for Nigerian analysts who are just getting started.

 

Step 1: Prepare Your Data

Every time series model starts with data in the right format. Your data needs two things: a column of dates and a column of values. That is it.

Your date column should have one row per time period. If you are forecasting monthly sales, you should have one row per month. If you are forecasting daily transactions, you should have one row per day. Gaps in your date column, such as missing months, need to be handled before you build any model.

Your value column should contain the numbers you want to forecast. This could be sales volume, revenue, customer count, transaction count, or any other numeric metric that changes over time.

Loading Your Data in Python

Here is how to load a CSV file with your time series data in Python using pandas.

import pandas as pd

df = pd.read_csv(‘your_data.csv’)

df[‘date’] = pd.to_datetime(df[‘date’])

df = df.sort_values(‘date’).reset_index(drop=True)

These four lines load your data, convert the date column to a date format Python understands, and sort the rows in date order. This is your starting point for every time series project.

 

Step 2: Plot Your Data

Before you build any model, plot your data. This is a rule, not a suggestion. Looking at your data visually tells you things that no formula can.

You are looking for the three patterns described earlier: trend, seasonality, and noise. You are also looking for anything unusual, such as a sudden spike, a period of missing data, or an obvious outlier that needs investigation.

Here is how to create a simple line chart of your time series in Python.

import matplotlib.pyplot as plt

plt.figure(figsize=(12, 5))

plt.plot(df[‘date’], df[‘value’])

plt.title(‘My Time Series Data’)

plt.xlabel(‘Date’)

plt.ylabel(‘Value’)

plt.show()

Look at the chart for at least two minutes before moving on. Ask: does this go up or down over time? Does it have regular peaks and troughs? Are there any unusual periods I need to investigate?

 

Step 3: Split Into Train and Test Sets

Before you fit any model, split your data into a training period and a test period. The model will be trained on the training data only. Then you will use it to forecast the test period and compare those forecasts to the real values to check accuracy.

A common split for time series data is to use the oldest 80 percent of your data for training and the most recent 20 percent as the test set. Here is how to do this in Python.

split_point = int(len(df) * 0.8)

train = df[:split_point]

test = df[split_point:]

You must never let the model see the test data during training. This is what gives you an honest measure of forecast accuracy. If you skip this step and evaluate the model on its own training data, you will get a misleadingly good accuracy score that falls apart in real use.

 

Step 4: Build the Model Using Prophet

For this guide, we are going to use Prophet to build the forecast. Prophet is a free, open-source forecasting library made by Meta. It is one of the best tools for beginners because it handles trend and seasonality automatically and requires very little code to get started.

Prophet expects your data in a specific format. It needs a column called ds for the dates and a column called y for the values. Here is how to rename your columns to match this format.

from prophet import Prophet

train_prophet = trainrename(columns={‘date’: ‘ds’, ‘value’: ‘y’})

Now fit the model on the training data.

model = Prophet()

model.fit(train_prophet)

That is it. Two lines to fit a forecasting model that handles trend and seasonality automatically. Prophet analyses the patterns in your training data and builds a model that can project those patterns into the future.

 

Step 5: Generate Forecasts

Now that the model is fitted, use it to generate forecasts for the test period.

future = model.make_future_dataframe(periods=len(test), freq=’M’)

forecast = model.predict(future)

The make_future_dataframe function creates a table of future dates for the model to forecast. The periods parameter tells it how many future periods to generate. The freq parameter tells it the frequency of your data. Use ‘D’ for daily, ‘W’ for weekly, ‘M’ for monthly.

The forecast object now contains your predicted values along with confidence intervals that show the range of likely outcomes. This is important. Do not just report the central forecast. The confidence interval tells your audience how uncertain the prediction is, which helps them make better decisions.

 

Step 6: Plot and Check the Forecast

Prophet has a built-in plotting function that shows your historical data alongside the forecast.

fig = model.plot(forecast)

plt.show()

The chart shows the actual data as black dots, the forecast as a blue line, and the confidence interval as a shaded blue band. The band widens as the forecast goes further into the future, which correctly reflects growing uncertainty.

Look at the chart and ask: does the forecast follow the trend I saw in the raw data? Do the seasonal peaks appear at the right times? Does the forecast look reasonable from a business perspective? If anything looks wrong, investigate before you share the output.

 

Step 7: Measure Forecast Accuracy

Now compare the model’s forecasts for the test period to the actual values. This is the honest test of how well the model works.

First, get the forecast values for the test period.

test_forecast = forecast.tail(len(test))[[‘ds’, ‘yhat’]]

test_actual = test .rename (columns={‘date’: ‘ds’, ‘value’: ‘actual’})

results = pd.merge(test_forecast, test_actual, on=’ds’)

Then calculate Mean Absolute Error, which tells you the average size of the forecast errors in the same units as your data.

mae = abs(results[‘yhat’] – results[‘actual’]).mean()

print(f’Mean Absolute Error: {mae:.2f}’)

A lower MAE means the model is more accurate. But what counts as a good MAE depends on the scale of your data. If your monthly sales are around 1,000,000 units and your MAE is 50,000 units, that is a 5 percent error, which is very good for most business forecasting purposes.

 

Step 8: Communicate Your Results

The final step is often the one that beginners skip or rush. But it may be the most important step of all.

Your forecast is only useful if the people who need to act on it can understand it. This means you need to present your results in plain, clear language that a non-technical business manager can follow.

Do not show them Python code. Show them a clean chart with a clear title. Give them one summary number: our forecast for next month is X, with a likely range of Y to Z. Explain in one or two sentences what the model found and why it thinks that.

Lagos Data School trains Nigerian analysts to present their findings this way from the very first project they complete. The technical work gets you to the answer. The communication work gets the answer used.

 

A Summary of the Eight Steps

 

Step What You Do
1 — Prepare data Load CSV, convert dates, sort in order, handle gaps
2 — Plot data Create a line chart and look for trend, seasonality, and noise
3 — Split data Use oldest 80% for training, newest 20% for testing
4 — Fit model Use Prophet to fit on training data in two lines of code
5 — Generate forecasts Use make_future_dataframe and predict to get forecast values
6 — Plot forecast Use model.plot to visualise the forecast against historical data
7 — Measure accuracy Calculate MAE on the test period for an honest accuracy score
8 — Communicate results Present findings in plain language with a clear chart

 

 

What to Do When the Model Is Not Accurate Enough

A first model is rarely perfect. Here is what to do if your forecast accuracy is lower than you need.

  • Check for data quality issues. Missing values, duplicate dates, or incorrect numbers all pull accuracy down.
  • Check for patterns the model is missing. If your data has a strong weekly pattern, make sure your model is accounting for weekly seasonality.
  • Try adding external predictors. If you know that fuel price hikes affect your sales, you can add that variable to the model as a regressor.
  • Try a longer training period. More historical data usually means better pattern recognition, especially for seasonal patterns.

Lagos Data School teaches Nigerian analysts to diagnose and fix these accuracy problems as a core part of our Python forecasting module. Building the first model is step one. Knowing how to improve it is what makes you genuinely useful on a real team.

 

In Plain Terms

Let us say the same thing without any technical language at all.

You have data with dates and numbers. You load it. You look at it. You split it in two. You train a model on the first part. You check how well it predicts the second part. You present the result clearly.

That is the whole process. Eight steps. Each one is simple. Together they give you a real forecast that a real business can use.

You do not need to understand every line of Prophet’s code. You need to understand what each step of the process is doing and why. Lagos Data School builds this understanding carefully, step by step, in every analyst we train.

Start with this guide. Build the model. See the result. Then build it again with your own data.

That is how the skill becomes real.

 

Recommended External Resource

For Prophet’s full documentation and worked examples, visit the official Prophet website: https://facebook.github.io/prophet/

 

Your First Model Checklist

Use this checklist every time you build a time series forecasting model.

  • Data has one row per time period with no gaps in the date column
  • Date column has been converted to a date type in Python
  • Data has been sorted in date order from oldest to newest
  • A line chart has been plotted and reviewed before any model was built
  • Data has been split into a training set and a test set
  • Model has been fitted on training data only
  • Forecast accuracy has been measured on the test set
  • Results have been presented clearly with a chart and a plain summary

If all eight boxes are ticked, your first model is done. Good work. The next step is to take what you have learned here and apply it to a real Nigerian business dataset that matters to you.

 

About Lagos Data School

Lagos Data School is Nigeria’s top school for cybersecurity, data science, cloud, and analytics. Every idea in this guide is part of our hands-on course.

Our teachers are real security pros, not just classroom staff. So you learn from people who guard live networks every day.

We run classes on weekdays, weekends, and online. So no matter your time, we have a slot for you. Beyond skills, we also give you a real certificate and links to job partners.

Visit Lagos Data School today to view our courses and join the next class.

Build real forecasting skills. Train with Lagos Data School.

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

Hi, How Can We Help You?
Welcome To
Lagos Data School

Artificial Intelligence (AI), Machine Learning and Robotics Programmes Are Now Available!!!

Enroll Now!

Thank You
100% secure website.