Cash forecasting with AI: how TreasuryOS reduced idle cash by 40%
Our ML models predict cash flows 7, 30, and 90 days ahead with 94% accuracy. How we train on historical patterns, account for seasonality, automate multi-bank sweeps, and turned R$ 47M in idle cash into yield-generating positions — all via API.

The idle cash problem
Corporate treasuries often hold excess cash across multiple banks as a safety buffer. This idle cash earns nothing — or earns below-market rates in basic checking accounts — while the company pays 15-20% annual interest on credit lines.
Here's a typical scenario: A payment processor handles R$ 500 million in monthly volume across 4 banks. Each bank holds a buffer of R$ 10-15 million "just in case." That's R$ 40-60 million sitting idle across the banking network. At CDI rate (currently ~13.65%), that idle cash could be generating R$ 5-8 million per year in yield. Instead, it earns nothing.
The treasurer knows this. But they can't reduce the buffers because they don't know — with confidence — how much cash they'll need tomorrow, next week, or next month. Without reliable forecasts, the rational response is to over-buffer. Better to waste yield than to miss a payment obligation.
This is the problem TreasuryOS solves: predict cash needs with enough accuracy to minimize idle buffers without increasing liquidity risk.
Why spreadsheet forecasting fails
The typical treasury workflow
Most corporate treasuries forecast cash flow using Excel:
1. Download bank statements from each bank portal (manually, daily)
2. Categorize transactions into inflows and outflows
3. Apply historical averages and manual adjustments
4. Add known future obligations (payroll, tax payments, supplier terms)
5. Produce a forecast that's outdated by the time it's finished
This process takes 2-4 hours daily for a team of 2-3 analysts. The forecast is typically updated once per day, covers 7-14 days ahead, and has an accuracy of 60-70%.
Why it breaks down
Stale data. By the time the analyst finishes downloading statements and categorizing transactions, new payments have arrived. The forecast is based on yesterday's data, not today's reality.
No intraday visibility. A daily forecast can't capture intraday cash movements. A company might start the day with R$ 10M in Bank A, receive R$ 5M in PIX payments at 10am, make a R$ 8M supplier payment at 2pm, and receive another R$ 3M at 5pm. The daily snapshot misses all of this volatility.
No pattern recognition. Humans are bad at detecting subtle patterns in large datasets. A treasury analyst can notice "Fridays are busy," but can't detect that "the third Thursday of months following a holiday Monday has 23% higher outflows due to delayed supplier payments." ML models can.
No probabilistic thinking. Spreadsheets produce point estimates: "We'll need R$ 12M tomorrow." But the real answer is: "We'll need between R$ 10M and R$ 14M tomorrow, with 90% confidence." Point estimates don't capture uncertainty, which means buffers are either too large (wasted yield) or too small (liquidity risk).
Manual multi-bank coordination. When cash needs to move between banks, someone has to log into each bank portal, initiate transfers, and track confirmations. This is slow, error-prone, and doesn't scale.
How TreasuryOS forecasting works
TreasuryOS is our AI-powered treasury management engine. It consumes real-time transaction data from all connected banks, runs ML models to predict future cash flows, and automates cash positioning across the banking network.
Data ingestion: real-time, multi-bank
TreasuryOS connects to every bank in the client's network via:
- API integrations (for banks with modern APIs)
- CNAB 240 / camt.053 file parsing (for banks with file-based interfaces)
- Screen scraping via regulated connectors (for banks with no API or file interface)
All transactions are ingested in real-time (or near-real-time for file-based banks). Each transaction is automatically categorized using our transaction classification engine:
- Inflow categories: Customer payments (PIX, boleto, TED, card), loan disbursements, investment redemptions, intercompany transfers
- Outflow categories: Payroll, supplier payments, tax obligations, loan repayments, investment applications, intercompany transfers
- Recurring vs. one-time: The engine identifies recurring patterns (monthly payroll, quarterly taxes) vs. one-time events
The ML pipeline
TreasuryOS runs three forecasting models simultaneously, each optimized for a different time horizon:
Short-term model (1-7 days):
- Architecture: LSTM (Long Short-Term Memory) neural network
- Input features: Last 90 days of daily cash flows, day of week, day of month, holiday calendar, known future obligations, intraday patterns
- Output: Daily cash flow prediction with confidence intervals
- Accuracy: 94% within 10% error margin (7-day horizon)
Medium-term model (7-30 days):
- Architecture: Gradient-boosted ensemble (XGBoost)
- Input features: Last 12 months of weekly aggregated flows, seasonal patterns, macroeconomic indicators (Selic rate, IPCA, employment data), client-specific variables (sales pipeline, contract renewals)
- Output: Weekly cash flow prediction with confidence intervals
- Accuracy: 87% within 15% error margin (30-day horizon)
Long-term model (30-90 days):
- Architecture: Prophet (Facebook's time series model) + custom adjustments
- Input features: Last 24 months of monthly flows, annual seasonality, known large events (13th salary in December, tax deadlines), industry trends
- Output: Monthly cash flow prediction with wide confidence intervals
- Accuracy: 78% within 20% error margin (90-day horizon)
Feature engineering: what the models see
The models consume 83 features. The most predictive ones:
Temporal features (12):
- Day of week, day of month, week of year
- Business day vs. holiday
- Days until next major payment date (payroll, taxes)
- Quarter-end proximity
Historical flow features (24):
- Rolling averages (7, 14, 30, 60, 90 days)
- Same-day-last-week, same-day-last-month comparisons
- Trend coefficients (linear and exponential)
- Volatility measures (standard deviation, coefficient of variation)
Seasonal features (15):
- Monthly seasonality indices
- Annual patterns (January cash crunch, December 13th salary)
- Holiday impact coefficients
- Industry-specific seasonal patterns
Known obligations (18):
- Scheduled payroll amounts and dates
- Tax payment calendar (IRPJ, CSLL, PIS, COFINS, ISS, ICMS)
- Supplier payment terms and amounts
- Loan amortization schedules
- Contract-based inflows (recurring revenue, SaaS billing cycles)
External signals (14):
- Selic rate (affects investment returns and credit costs)
- IPCA trajectory (affects indexed contracts)
- Industry PMI (leading indicator of business activity)
- Client-specific KPIs (sales volume, active customers, churn rate)
Model retraining and drift detection
Models are retrained weekly using the latest data. Each retraining cycle:
1. New data is added to the training set
2. Model is retrained with cross-validation
3. New model is evaluated against the current production model
4. If the new model performs better (lower MAPE), it replaces the current model
5. If performance degrades (concept drift), an alert is triggered for review
We monitor for concept drift continuously. If the model's prediction error increases by more than 2 standard deviations for 3 consecutive days, the system flags a potential regime change (e.g., a major client lost, a new revenue stream, a macroeconomic shift).
Automated cash positioning: sweep and invest
Forecasting alone doesn't save money. The value comes from acting on the forecast — moving cash from idle positions to yield-generating positions, automatically.
The sweep engine
Every morning at 8:00am (before markets open), TreasuryOS runs the sweep optimization:
1. Current state: Query balances across all banks
2. Forecast: Predict cash needs for the next 7 days per bank
3. Buffer calculation: Determine minimum buffer per bank (forecast + safety margin based on confidence interval)
4. Excess identification: Cash above the buffer is "excess" and can be invested
5. Sweep execution: Transfer excess cash to the highest-yield destination
Sweep destinations (in order of preference):
- Automatic CDI application (same bank): Zero transfer cost, immediate liquidity
- CDB/LCI/LCA (same bank): Higher yield than CDI, but with lock-up period
- Interbank transfer + application (different bank): Higher yield justifies transfer cost
The sweep engine respects constraints:
- Minimum balance requirements per bank (contractual)
- Maximum concentration per bank (risk management)
- Transfer cutoff times (TED before 4:30pm, PIX anytime)
- Settlement delays (TED D+0, DOC D+1)
Intraday rebalancing
For high-volume operations (payment processors, marketplaces), daily sweeps aren't enough. Cash positions change dramatically throughout the day.
TreasuryOS runs intraday rebalancing at configurable intervals (default: every 2 hours):
1. Check current balances vs. intraday forecast
2. If any bank is below the intraday buffer, trigger a top-up transfer
3. If any bank has unexpected excess, trigger an investment application
4. All transfers via PIX (instant, 24/7, zero cost between own accounts)
Automated investment ladder
For medium and long-term excess cash, TreasuryOS builds an investment ladder:
- 0-7 day excess: Automatic CDI (daily liquidity)
- 7-30 day excess: CDB with 30-day term (CDI + 0.5%)
- 30-90 day excess: LCI/LCA with 90-day term (CDI + 1.0%, tax-exempt for individuals)
- 90+ day excess: Longer-term instruments based on treasury policy
The ladder is dynamically adjusted based on forecasts. If the 30-day model predicts a large outflow in 3 weeks, the system avoids locking cash in 30-day CDBs and keeps it in daily-liquidity CDI instead.
Multi-bank visibility: the single pane of glass
Consolidated dashboard
TreasuryOS provides a single dashboard showing:
- Real-time balances across all banks (updated every 5 minutes)
- Intraday cash flow (cumulative inflows and outflows throughout the day)
- Forecast overlay (predicted vs. actual, with confidence bands)
- Investment positions (type, amount, maturity, yield)
- Sweep history (all automated movements with amounts and reasons)
Bank performance analytics
The dashboard also tracks bank-level metrics:
- Average idle balance per bank (lower is better)
- Yield on invested cash per bank
- Transfer costs per bank
- Settlement reliability (do transfers arrive on time?)
- API availability (uptime of bank connections)
This data helps treasurers negotiate better terms with banks and optimize their banking network.
Working capital optimization
Beyond forecasting, TreasuryOS provides working capital insights:
Days Sales Outstanding (DSO) tracking
Real-time DSO per customer segment, payment method, and vintage. The system detects DSO deterioration early — before it impacts cash flow.
Supplier payment optimization
TreasuryOS analyzes supplier payment terms and identifies opportunities:
- Which suppliers offer early-payment discounts?
- Is the discount (e.g., 2% for paying 20 days early) better than the CDI return on that cash?
- Which suppliers can be moved to longer payment terms without damaging the relationship?
Cash conversion cycle
The system tracks the complete cash conversion cycle: inventory days + receivable days - payable days. Trends are surfaced as actionable recommendations: "Extending supplier terms by 5 days would free R$ 3.2M in working capital."
The numbers from production
After 18 months of TreasuryOS in production across 23 clients:
- 94% forecast accuracy (7-day horizon, within 10% error margin)
- 87% forecast accuracy (30-day horizon, within 15% error margin)
- 40% reduction in idle cash — from R$ 47M average to R$ 28M average across the client base
- R$ 8.2M in additional yield generated in 12 months from invested excess cash
- 83 features consumed by the ML models
- < 30 seconds from data ingestion to updated forecast
- 4 banks average per client, all consolidated in a single dashboard
- 2.3 hours/day saved per treasury team (eliminated manual statement downloads and spreadsheet reconciliation)
- Zero liquidity incidents — no client has missed a payment obligation due to insufficient buffer
Why this matters
Every real sitting idle in a bank account is a real not earning yield. For a company with R$ 50M in average idle cash, the opportunity cost at CDI rate is R$ 6.8M per year. That's not a rounding error — it's a material P&L impact.
The reason companies hold excess cash isn't irrationality. It's uncertainty. They don't know how much they'll need, so they buffer conservatively. TreasuryOS replaces uncertainty with probabilistic forecasts, and replaces manual cash management with automated sweep-and-invest.
The result: less idle cash, more yield, zero additional liquidity risk, and a treasury team that spends time on strategy instead of downloading bank statements.
We built TreasuryOS because we believe treasury management is a solved problem in theory — but most companies still run it on spreadsheets and intuition. ML models that update in real-time, connected to automated sweep engines, change the economics fundamentally. And the numbers prove it.