Inventory Management Software

Kardex Tauro

Kardex Tauro® Inventory Software is designed to efficiently manage your warehouse or storage facility, and it is quick and easy to learn.

Kardex Tauro is free for non-commercial use.
It does not require an internet connection; it runs on Windows.

Python code: demand forecast with a small network (compared with the moving average)

Python code: demand forecast with a small network (compared with the moving average)

Anyone who runs a warehouse faces the same question at the end of every month: how much will I sell next month? Buy too much and the money sits still on the shelf while the back room fills with goods nobody asks for; buy too little and you run out of stock exactly the day a customer needs it. The program behind this article answers that question with numbers instead of hunches: it reads twenty-four months of sales from a plain text file, works out two forecasts — the three-month moving average, the classic method everybody knows, and a tiny neural network — and compares them so it can tell you, with data, which one was wrong by less. It is written for business owners, accountants and warehouse staff who want to understand what sits behind a forecast figure without becoming programmers.

⬇ Download the code (ZIP)
File in the ZIPWhat it is for
pronostico_demanda.pyThe complete program, commented in English line by line. It is the only file you run.
datos/ventas_mensuales.csvTwenty-four months of sample sales, with the month and the units sold. Excel opens it and you can swap in your own figures.
salida_ejemplo.txtThe real output of the program, exactly as it appears on screen, so you can compare it with yours.
README.mdThe instructions for the package: how to run it, what each column means and the usual questions.

What the program does

The program does not guess and it holds no opinions about your business: it learns from the past of the series itself and then measures itself against a plain method, so that you can judge whether the effort is worth it. Step by step, this is what happens:

  1. It reads the file datos/ventas_mensuales.csv and keeps the list of months with the number of units sold in each one: twenty-four rows in all.
  2. It rescales the whole series to a range between zero and one. That sounds technical, but it is plain common sense: the network is comfortable with small numbers, and if you hand it raw units the arithmetic blows up.
  3. It builds the training samples: every month becomes one example where the inputs are the three months before it and the correct answer is the current month. That way the program does not memorize: it learns the link between what happened and what came next.
  4. It creates a network with three inputs, four neurons in the hidden layer and one output. The starting weights are random numbers, but under a fixed seed: that is what makes the program give the same result today and a year from now.
  5. It trains the network two thousand times over those same samples, nudging the weights a little on every pass, always in the direction that lowers the error.
  6. At the same time it works out the three-month moving average forecast: the plain average of the three previous months. That is the method everybody builds in Excel, and it serves as the yardstick.
  7. It compares the two methods over exactly the same months: twenty-one months have enough history to be evaluated; the first three do not, because the months before them are missing.
  8. It prints how far off each method was, states which one wins, and saves the full table to a file that opens in Excel.

How to run it

You need one thing installed: Python 3.11 or later, which you download free from the official Python site and install by clicking next, next, next. After that, the steps are these:

  1. Unzip the package into any folder; the desktop is fine, it does not matter where it lands.
  2. Open the terminal: on Windows, Start menu, type cmd and press Enter; on a Mac, open the Terminal app.
  3. Type cd followed by the path of the folder where you unzipped the package, and press Enter.
  4. Type python pronostico_demanda.py and press Enter.

There is nothing else to install: the program only uses what ships with Python, so there are no libraries to download and no dependencies that break. If the system tells you python does not exist, try py on Windows or python3 on a Mac. When it finishes, besides the summary on screen, you will find a new file inside the salida folder.

The code, explained

The program fits on one screen and it is commented from the first line to the last. These are the parts worth understanding, without wading into deep mathematics.

# ==========================================================================
#  DEMAND FORECAST WITH A SMALL NETWORK
#  Didactic Python code for inventory · Kardex Tauro · kardex-tauro.muisca.co
#  What it does: reads 24 months of sales from datos/ventas_mensuales.csv, trains by hand
#  a network with 3 inputs, 4 hidden neurons and 1 output, and compares it with the
#  3-month moving average; leaves the table and the forecast in salida/pronostico.csv
# ==========================================================================

import csv                                      # csv: reads and writes comma-separated files (Excel opens them directly)
import math                                     # math: the exponential function the sigmoid curve needs
import random                                   # random: randomness with a fixed seed, so the result always repeats

That header says in plain words what the file is for and where it takes its data from, and it brings in the libraries: everything imported ships with Python, so there is nothing exotic to install. Getting into the habit of explaining a file in its first line is something your future self will thank you for.

Then come the numbers that drive the experiment, all in one place with their explanation alongside. They sit at the top, and not buried in the middle of the code, because they are the ones you will want to touch: change the seed and you will get another result; cut the epochs and you will watch the forecast lose sharpness.

# The numbers that drive the network: seed, rate, epochs, report and shape
SEMILLA = 7          # Fixed seed: with the same data the result is always the same
TASA = 0.1           # Learning rate: how much each weight is corrected on every sample
EPOCAS = 2000        # Epochs: how many full passes over the 21 samples
INFORME = 250        # Every how many epochs the average error of the network is printed
REZAGO = 3           # Inputs of the network: the 3 previous months
OCULTAS = 4          # Hidden neurons: not so few that it learns nothing, not so many that it memorizes
VENTANA = 3          # Months averaged by the moving average, so both methods are compared fairly

Next come two three-line functions that hold up everything else. The first brings the series to a comfortable scale — the range from zero to one — and the second is the curve of the neuron, the one that squeezes any number into that same range. Without those two functions the arithmetic runs off to infinity and the program learns nothing.

def escalar(valores: list[float]) -> tuple:
    """Scales the series to the 0..1 range (min-max): that way the network works with small numbers."""
    minimo, maximo = min(valores), max(valores)
    rango = maximo - minimo
    # If the whole series held one value the range would be zero: 0 avoids dividing by zero
    return [(valor - minimo) / rango for valor in valores], minimo, maximo


def sigmoide(suma: float) -> float:
    """Sigmoid: squeezes any number into the 0..1 range (the curve of the neuron)."""
    return 1.0 / (1.0 + math.exp(-suma))

Here is the heart of the matter: every time the network sees one sample month, it compares its answer with the real figure, measures the gap and moves every weight a little against the error. That is all. Repeated two thousand times, that movement is what we call learning.

            # Gradient descent: every weight moves a little against the error
            for j in range(OCULTAS):
                red["w_salida"][j] += TASA * delta_salida * ocultas[j]
            red["b_salida"] += TASA * delta_salida

And finally the yardstick everything is measured against: the three-month moving average, which is the sum anyone would do by hand, and the average absolute error of each method over exactly the same months. That detail is the key to an honest comparison: if each method were measured over different months, the comparison would be worth nothing.

def promedio_movil(unidades: list[float], indice: int) -> float:
    """Moving-average forecast: the average of the months before that one."""
    return sum(unidades[indice - VENTANA:indice]) / VENTANA
    evaluados = [fila for fila in filas if fila["promedio"] is not None]
    error_pm = sum(abs(fila["unidades"] - fila["promedio"]) for fila in evaluados) / len(evaluados)
    error_rd = sum(abs(fila["unidades"] - fila["red"]) for fila in evaluados) / len(evaluados)

What you will see on screen

The first thing the program prints is what it read and the shape the network will work with:

Months read: 24
Neural network: 3 -> 4 -> 1 (sigmoid)
Moving-average window: 3 months
Range of the series: 150.00 to 310.00 units

Then it shows the training progress every two hundred and fifty rounds. That detail is more useful than it looks: the error falls fast at the start and then flattens out, and watching it explains why two thousand epochs are used and not twenty thousand.

TRAINING: 2000 epochs, rate 0.10, seed 7
  Epoch 500/2000 · average error (0-1 scale) 0.093869
  Epoch 1000/2000 · average error (0-1 scale) 0.086684
  Epoch 2000/2000 · average error (0-1 scale) 0.078619

And it closes with the verdict, which is what you came for:

SUMMARY: WHO MISSES BY LESS
  Months evaluated (those with 3 months of history): 21
  Average absolute error of the 3-month moving average: 17.32 units
  Average absolute error of the 3-4-1 neural network: 12.58 units
  Forecast for 2028-01 - 3-month moving average: 300.33 units
  Forecast for 2028-01 - 3-4-1 neural network: 289.71 units

The program also saves the full table to salida/pronostico.csv, with one row per month and four columns: the month, the actual units, the moving-average forecast and the network forecast. Excel opens that file, and you can chart it to see with your own eyes where the two lines separate.

The result, told without exaggeration

With the sample data the verdict is clear but modest: over the twenty-one months evaluated, the moving average missed by 17.32 units per month on average and the network by 12.58. The network did win, but it won by a little: less than five units a month on a series that moves between 150 and 310 units. For the following month the two methods also land close: the moving average points to 300.33 units and the network to 289.71. That is what there is, no more and no less: with twenty-four months of history the network beat the average by a small margin, and that result is enough to keep testing it on your own numbers, not to believe it reads the future.

It is worth being clear about what that network is before you trust a purchase decision to it. It is not a program that knows about sales and it is not an oracle: it is a rule that adjusts itself. Picture a rule written with about twenty numbers; every time the rule is wrong, those numbers shift a little towards wherever the error falls, until they settle in the position where they are wrong the least. That is all there is to it. That is why the program compares itself against the moving average: a rule that adjusts itself is only worth it if it beats the fixed rule you were already using.

Common mistakes and advice

  • Changing the data and never looking at the error again. The program always prints the error of both methods. If the network ends up worse than the average on your sales, nothing is broken: your data simply does not give itself to a network this small. Keep the average and carry on.
  • Treating the forecast as a promise. A forecast is an estimate with an error attached, and the program names that error for you. Use the figure to plan purchases and to talk to suppliers, not to sign a delivery commitment.
  • Too little history. With twelve months the network hardly has anything to learn from and the moving average cannot be measured well either. This program is meant for two years or more.
  • Hiding seasonality. If your business sells three times as much in December, three months of history are not enough for the network to see the peak coming. Load two or three full years and run the comparison again.
  • Moving the seed to improve the result. If you keep changing the seed until the network wins, you are no longer measuring, you are cheating. Leave the seed fixed and accept the verdict, whoever wins.
  • Not checking the data file before running it. The CSV headings and the decimal separator have to be consistent; if Excel saved the months in another order or another format, the program will read something else.

When this is not enough

This program is a good starting point and a fine way to understand a forecast without depending on anybody, but it falls short as the business grows. Here there is only one series, one product and a folder of files: no users, no warehouses, no record of who moved what.

When the inventory no longer fits in a spreadsheet — hundreds of items, several warehouses and movements every day — and when you want the forecast, the reorder point and the day movement in the same place, that is where Kardex Tauro does what a script does not. The underlying idea does not change: the network is still the same rule that adjusts itself, it simply runs on tidy data with a backup behind it. Start with the free program to understand the method and to bring your stock records into order; the full software is for when spreadsheets and scripts are no longer enough.

⬇ Download the code (ZIP)

Download the ZIP, swap the data file for your own sales of the last two years and look at the summary. If the network beats the average by a little, good news: you now have a forecasting method measured with your own numbers, and you know how far off it tends to be.

Share
Link copied
Microsoft Store from Microsoft StoreDownload free
Chatea por WhatsApp