Portfolio Project · Data Engineering & ML

CottonIQ

// Market Intelligence Platform

An end-to-end automated system that collects global cotton market data from four distinct sources, feeds it through XGBoost prediction models, and surfaces everything through a live Streamlit analytics dashboard.

4 Data Sources
2 ML Models
70+ Features
Daily Auto
// Full System Components
🌾
USDA FAS API
Weekly export sales · 8 commodity codes
Live
📄
Cotlook PDF Scraper
Adaptive parser · 5 PDF structure types
Live
🤖
CCF Selenium Bot
ECharts JS injection · 70+ yarn features
Live
📊
CFTC COT Reports
Legacy & disaggregated futures data
Live
🧠
XGBoost Price Model
Custom feature engineering · lagged + COT
ML
📈
XGBoost OI Model
Open interest prediction · export inputs
ML
🖥️
Streamlit Dashboard
5 live views · predictions + market data
Viz
// Data Pipeline

Four sources.
One platform.

Each pipeline component handles a completely different source type — REST API, PDF documents, a JavaScript-rendered web app, and government report files. Every component feeds the same database.

01

USDA Export Sales API

Fetches weekly cotton export data for 8 commodity codes across two marketing years. Computes marketing year, week number, and grand totals — then stages before promoting to the main table.

requestspandas psycopg2incremental load
02

Cotlook PDF Parser

Auto-detects PDF structure type (single-year, dual-year, CIF Europe, dual-index, multi-index) and routes to the correct parser. Outputs price, change, and shipment data for 20+ cotton growths per document.

pdfplumberregex numpyadaptive routing
03

CCF Selenium Web Bot

Logs into CCF Group, navigates to ECharts dashboards, and extracts 70+ yarn price series via JavaScript injection. Chrome → Firefox fallback, virtual display support, and full crash recovery.

SeleniumECharts JS headlessupsert
04

CFTC COT Ingestion

Pulls legacy and disaggregated Commitments of Traders reports. Normalises 30+ column name variants, filters for current-year data, and bulk-loads to the production reporting table.

cot_reportsSQLAlchemy column normalisation
05

Contract Metadata Engine

Computes First Notice Dates for the next 6 active cotton futures contracts, accounting for US federal holidays across all years. Inserts only net-new contracts — never duplicates.

holidaysBDay calendar logic
06

Materialized View Layer

An 8-CTE SQL view aggregates grand totals, computes Shipment % of Final against a 5-year historical average, and auto-refreshes after every pipeline run to serve the latest week's KPIs.

PostgreSQL8 CTEs REFRESH MATERIALIZED VIEW
// Machine Learning

Two XGBoost models.
Built from scratch.

Both models were trained on the data this pipeline collects. Feature engineering was done manually — drawing on domain knowledge of how cotton market signals interact across time horizons.

Model 01 · Regression

Cotton Price
Prediction

Predicts the Cotlook A Index price using a combination of lagged price signals, COT positioning, export sales momentum, and seasonal patterns.

Lagged Cotlook A Index values (t-1, t-2, t-4, t-8)
Rolling price averages (4-week, 8-week, 12-week)
CFTC net commercial / non-commercial positioning
USDA cumulative export commitments & net sales
Marketing year week number (seasonal signal)
Model 02 · Regression

Open Interest
Prediction

Predicts cotton futures open interest levels, capturing changes in market participation driven by speculative positioning and fundamental export signals.

Lagged open interest values (t-1, t-2, t-4)
Rolling OI averages and rate-of-change features
COT gross longs, gross shorts, spreading positions
Weekly export sales (USDA) as demand signal
Calendar week and marketing year position

Feature Engineering Breakdown

All features were hand-crafted — no automated feature selection libraries. Each group reflects a deliberate hypothesis about what drives cotton prices and open interest.

Time-Series Features
Price lag t-1, t-2, t-4, t-8 OI lag t-1, t-2, t-4 4-week rolling mean 8-week rolling mean 12-week rolling mean Week-over-week change
Market Positioning (COT)
Net commercial position Net non-commercial position Gross long / gross short Spreading contracts % of open interest WoW positioning change
Fundamental & Seasonal
USDA CMY net sales USDA cumulative exports Cotlook A Index level Marketing year week no. Calendar month MY start / end flag
// Analytics Dashboard

Everything in
one place.

A Streamlit dashboard connects directly to the PostgreSQL database and presents all pipeline outputs alongside model predictions in a single interface — updated automatically after every pipeline run.

— Actual - - Predicted Aug Nov Feb May
View 01 · ML Predictions

Price Prediction Chart

Actual vs. predicted Cotlook A Index plotted over time. Model confidence bands and week-ahead forecasts shown alongside raw price history.

XGBoostPlotlyCotlook data
█ Open Interest - - Forecast
View 02 · ML Predictions

Open Interest Forecast

Weekly futures open interest with XGBoost model forecast overlay. Useful for anticipating changes in market participation before they're reported.

XGBoostCOT dataPlotly
Shpt % Final 68.4% — Net Sales — Acum. Exports
View 03 · Export Sales

USDA Export Pipeline

Live weekly export sales and accumulated shipments from USDA. Includes the Shipment % of Final KPI computed by the materialized view.

USDA FASMat. View KPIweekly
█ Net Longs █ Net Shorts
View 04 · COT Report

Positioning Visualization

CFTC Commitments of Traders data shown as net long / net short bars by trader category. Highlights speculative vs commercial positioning shifts week by week.

CFTCCOT legacydisaggregated
India C32S Pak C20S China OE10S Vietnam C32S
View 05 · Yarn & Cotlook Prices

CCF Yarn Prices + Cotlook Index

Interactive multi-series chart showing 70+ global yarn price series from CCF alongside the Cotlook A Index and composition prices. Users can filter by origin country, yarn type, and date range — all sourced live from the PostgreSQL database the scraper populates.

CCF historical Cotlook compositions 70+ series Plotly Streamlit
// Database Architecture

Built in layers.
Designed to scale.

Multi-schema PostgreSQL on AWS RDS. Raw data lands in staging, gets validated, promoted to production, and then aggregated into a materialized analytics layer — all in a single automated run.

Ingest
USDA FAS REST API Cotlook PDFs CCF Web Platform CFTC COT Files
Transform
Marketing Year Calc Week Number Logic PDF Structure Detection Column Normalisation Grand Total Aggregation Holiday-aware FND XGBoost Feature Engineering Lag / Rolling / COT Features
Stage
staging.cotton_exports_incremental staging.ExportSalesGrandTotal staging.contract_codes
Prod
staging.Cotton_Exports_new prod.prices_ccf_historical prod.cftc_cot_report_legacy prod.model_predictions
Serve
Materialized View (latest week) Shipment % of Final KPI 5-Year Avg Benchmark Contract Calendar Streamlit Dashboard XGBoost Predictions
// Tech Stack

What it's built with.

A modern Python data stack from ingestion to prediction to visualisation. Everything connects — the same data that's scraped feeds the models that feed the dashboard.

Data Collection

requests · Selenium · pdfplumber

REST API calls, headless browser automation with Chrome/Firefox fallback, adaptive PDF parsing.

Transformation

pandas · numpy · regex

DataFrame pipelines, column normalisation, date arithmetic, numeric cleaning, type coercion.

Machine Learning

XGBoost · scikit-learn

Two regression models with hand-crafted feature engineering across time-series, COT, and fundamental data.

Visualisation

Streamlit · Plotly

Five-view interactive dashboard. Live DB connection. Actual vs predicted charts, COT positioning, export KPIs.

Storage

PostgreSQL · AWS RDS

Multi-schema DB on AWS eu-north-1. psycopg2 for direct control, SQLAlchemy for bulk loads.

Analytics Layer

Materialized Views · CTEs

8-CTE view auto-refreshed per run, computing Shipment % of Final against a 5-year historical benchmark.

Orchestration

Cron · Job Logging

Scheduled daily runs. Full execution logged to staging_tables.cron_jobs_logs for observability.

Infrastructure

AWS RDS · Ubuntu Linux

Production on AWS eu-north-1. Headless browser support, pyvirtualdisplay, emergency crash saves.

// Project Structure

Well organised.
Easy to navigate.

Every component lives in its own module. The ML and dashboard layers are clearly separated from the data pipeline.

cottoniq/
├── pipelines/
│ ├── usda_cotton_pipeline.py # USDA FAS API · incremental load · materialized view refresh
│ ├── cotlook_pdf_parser.py # Adaptive PDF extractor · 5 structure types
│ ├── ccf_scraper.py # Selenium bot · ECharts JS injection · 70+ yarn features
│ ├── cot_ingestion.py # CFTC COT reports · column normalisation · bulk load
│ └── contract_codes.py # Futures contract metadata · holiday-aware FND calc
├── models/
│ ├── feature_engineering.py # Lag, rolling, COT, seasonal feature construction
│ ├── price_model.py # XGBoost price prediction · training + inference
│ ├── open_interest_model.py # XGBoost OI prediction · training + inference
│ └── saved/ # Serialised model artefacts (.json)
├── dashboard/
│ ├── app.py # Streamlit entry point · 5 views
│ ├── views/
│ │ ├── price_predictions.py # Actual vs predicted price chart
│ │ ├── oi_predictions.py # Open interest forecast chart
│ │ ├── export_sales.py # USDA pipeline + Shipment % KPI
│ │ ├── cot_report.py # COT positioning visualisation
│ │ └── yarn_cotlook.py # CCF yarn + Cotlook index charts
├── sql/
│ ├── materialized_view.sql # 8-CTE analytics view DDL
│ ├── schema_staging.sql
│ └── schema_prod.sql
├── .env.example
├── requirements.txt
└── README.md