Kenya Maize Price Forecasting

Weekly wholesale maize price prediction for 5 Kenya counties, 2 weeks ahead. The pipeline combines two data sources (agriBORA weekly prices and KAMIS daily market prices), rich temporal feature engineering, and an ensemble of ML and classical time series models — with walk-forward cross-validation for honest evaluation.

Zindi · agriBORA × KAMIS 5 Counties 2-week rolling horizon LightGBM · XGBoost · Prophet · ARIMA · ETS Metric: 0.5×MAE + 0.5×RMSE

TL;DR: In sparse-data environments, data alignment and calibration produce more forecast improvement than model sophistication. The infrastructure gap must be filled by engineering before modeling can begin.

The Problem

Agricultural price forecasting in East Africa comes with a unique challenge: the data infrastructure is sparse. Markets report inconsistently, volumes fluctuate wildly between seasons, and the two available data sources — agriBORA weekly prices and KAMIS daily market data — measure slightly different things at different granularities. The task was to predict weekly wholesale maize prices for 5 Kenya counties (Kiambu, Kirinyaga, Mombasa, Nairobi, Uasin-Gishu) two weeks ahead.

The fundamental difficulty wasn't modeling — it was data alignment. KAMIS reports daily prices from individual markets within each county, while agriBORA provides weekly county-level prices. These don't perfectly match. Some weeks have missing data from one source. Some markets within a county trade vastly different volumes, meaning a simple average of their prices would be misleading. Before I could build any model, I needed a reliable way to fuse these two data sources into a single coherent price signal.

Beyond the data issues, maize prices in Kenya follow strong seasonal cycles tied to harvest periods and lean seasons — but the cycles aren't perfectly regular. Rainfall timing shifts year to year, and external shocks (import restrictions, regional supply changes) create sudden level shifts that no purely seasonal model can anticipate. The model needed to capture both the regular rhythm and the irregular disruptions.

My Approach

I started with the data alignment problem. For KAMIS daily prices, I aggregated to weekly using volume-weighted means rather than simple averages — ensuring that high-volume market days carry more weight than thin-trading days. Then I built a calibration layer between KAMIS and agriBORA prices, so the model could leverage the richer daily data while predicting against the agriBORA target. For gaps in the data, I used last-observation-carried-forward (LOCF) rather than interpolation, because in commodity markets a missing price usually means "no change" rather than "somewhere between the neighbors."

The feature engineering encoded both seasonal patterns and momentum signals. I created cyclical encodings for week-of-year (sine and cosine transforms), harvest and lean season indicators per county, rolling statistics (4-week and 8-week moving averages), lag features at 1, 2, 4, and 52 weeks, and year-over-year price changes. The cyclical encoding was important — treating week 52 and week 1 as adjacent rather than 51 units apart lets the model learn smooth seasonal transitions.

For modeling, I built an ensemble that combines ML models (LightGBM, XGBoost) with classical time series (ARIMA, ETS, Prophet). The ML models excel at capturing non-linear interactions between features but can produce unreasonable extrapolations. The classical models provide stable seasonal baselines. The ensemble blends their strengths while using walk-forward cross-validation for honest evaluation — each fold trains only on past data and predicts the next unseen window, exactly mimicking the real forecasting task.

Key Decisions

Volume-Weighted Aggregation from KAMIS

Not all market days carry equal information. High-volume trading days reveal true market prices while thin-trading days introduce noise. Volume-weighted weekly aggregation ensures the signal reflects actual market activity rather than averaging noise equally with signal.

KAMIS-to-agriBORA Calibration Layer

The two data sources measure slightly different things. Rather than choosing one, I calibrated KAMIS data to match agriBORA's scale and used both. This doubled the available signal while maintaining consistency with the prediction target.

Cyclical Seasonal Encoding

Week-of-year encoded as sine and cosine transforms ensures that week 52 and week 1 are recognized as adjacent. This lets the model learn smooth seasonal transitions at year boundaries rather than treating them as discontinuous jumps.

Walk-Forward Cross-Validation

Standard k-fold CV violates temporal ordering in time series. Walk-forward validation trains only on past data and predicts the next window, exactly mimicking the real forecasting task. This gave honest error estimates and prevented data leakage from future information.

Key Takeaway

The biggest lesson from this project: in sparse-data forecasting environments, data engineering produces more lift than model sophistication. The time I spent on volume-weighted aggregation, source calibration, and gap-filling — before any model was trained — determined the ceiling of the entire system. A sophisticated model on poorly aligned data will always lose to a simple model on well-prepared data. When the infrastructure is sparse, the engineer's job is to build the data quality that the infrastructure doesn't provide.

Design insight: In sparse-data environments, data alignment and calibration produce more forecast improvement than model sophistication. The infrastructure gap must be filled by engineering before modeling can begin.

FAQ

What is the key takeaway from "Kenya Maize Price Forecasting with MLForecast"?

In sparse-data environments, data alignment and calibration produce more forecast improvement than model sophistication. The infrastructure gap must be filled by engineering before modeling can begin.

Who wrote this and what is it about?

This was written by Mahmoud Trigui, Senior Data Scientist. MLForecast Weekly wholesale maize price forecasting for 5 Kenya counties (Kiambu, Kirinyaga, Mombasa, Nairobi, Uasin-Gishu) 2 weeks ahead. LightGBM, XGBoost, Prophet, ARIMA, ETS ensemble. Volume-weighted KAMIS aggregation, KAMIS-to-agriBORA calibration, rich temporal feature engineering, walk-forward cross-validation. Zindi competition case study.

Comments

Machine Learning Feature Engineering MLForecast Time Series Decomposition Forecasting LightGBM XGBoost Catboost Clustering Segmentation NLP LLMs Web App R Markdown SQL Oracle DB SAS-Guide SAS E-Miner Dataiku BigQuery GCP Python R CRISP-DM Hypothesis Testing ANOVA Data Analytics Dimensionality Reduction Recommendation System Network Analysis Geospace Analysis Spatial Data Embedding Sampling Techniques Decision Rules Data Storytelling CVM Churn Fraud Detection Sentiment Analysis Topic Modeling IBM Watson PowerBI Looker Studio VBA Statistical Learning Ensemble Modeling Stacking Cross-Validation Profiling ABT Construction Plumber Tidyverse Shiny Prophet Deep Learning Scikit-Learn JSON SAS Programming Git VS Code CSS Styling Automated Reporting Outlier Detection Temporal Clustering Startup Survival Pre-Valuation Modeling K-Means Decision Trees Data Science Predictive Modeling SVM LDA Text Classification Weight Prediction Pattern Recognition Real-Time Detection Community Detection Pipeline Automation Data Quality Checks Data Reliability Specification Mapping Business Strategy Marketing Campaigns Try & Buy Frameworks KPI Dashboards Network Quality Sales Analytics Mentoring Statistics Lecturer Remote Work Hybrid Work Consulting Contract Full-Time Freelance Sofrecom Orange Group Tunisia Telecom Kiota Intelligence VC Analytics Series A Prediction Pre-Valuation Modeling Production ML Applied AI Prompt Engineering Business Forecasting Decision Systems Graph Analytics Household Detection Multi-SIM Detection FTTH Forecasting Audit Extraction Infrastructure Classification Pydantic GPT-4 OpenAI API Base64 Classification Zindi Codementor LAAS-CNRS ESSAI MIT xPRO Tunisia ML Competition Cell Tower Analysis Uber Logistics Uber Cape Town Necessary Condition Analysis Behavioral Signals Spike Smoothing Observation Unit Design Dendrogram Ward Clustering VIF Target Encoding Machine Learning Feature Engineering MLForecast Time Series Decomposition Forecasting LightGBM XGBoost Catboost Clustering Segmentation NLP LLMs Web App R Markdown SQL Oracle DB SAS-Guide SAS E-Miner Dataiku BigQuery GCP Python R CRISP-DM Hypothesis Testing ANOVA Data Analytics Dimensionality Reduction Recommendation System Network Analysis Geospace Analysis Spatial Data Embedding Sampling Techniques Decision Rules Data Storytelling CVM Churn Fraud Detection Sentiment Analysis Topic Modeling IBM Watson PowerBI Looker Studio VBA Statistical Learning Ensemble Modeling Stacking Cross-Validation Profiling ABT Construction Plumber Tidyverse Shiny Prophet Deep Learning Scikit-Learn JSON SAS Programming Git VS Code CSS Styling Automated Reporting Outlier Detection Temporal Clustering Startup Survival Pre-Valuation Modeling K-Means Decision Trees Data Science Predictive Modeling SVM LDA Text Classification Weight Prediction Pattern Recognition Real-Time Detection Community Detection Pipeline Automation Data Quality Checks Data Reliability Specification Mapping Business Strategy Marketing Campaigns Try & Buy Frameworks KPI Dashboards Network Quality Sales Analytics Mentoring Statistics Lecturer Remote Work Hybrid Work Consulting Contract Full-Time Freelance Sofrecom Orange Group Tunisia Telecom Kiota Intelligence VC Analytics Series A Prediction Pre-Valuation Modeling Production ML Applied AI Prompt Engineering Business Forecasting Decision Systems Graph Analytics Household Detection Multi-SIM Detection FTTH Forecasting Audit Extraction Infrastructure Classification Pydantic GPT-4 OpenAI API Base64 Classification Zindi Codementor LAAS-CNRS ESSAI MIT xPRO Tunisia ML Competition Cell Tower Analysis Uber Logistics Uber Cape Town Necessary Condition Analysis Behavioral Signals Spike Smoothing Observation Unit Design Dendrogram Ward Clustering VIF Target Encoding