Building a personal finance agent in Dataiku
Bank statements on one side, free market and macro APIs on the other, and a Dataiku agent that reasons across both. A build blueprint, including the parts that constrain the design more than the architecture does.

Most personal finance tools answer one of two questions. Budgeting apps tell you where your money went. Market apps tell you what the market did. Neither answers the question people actually ask, which sits across both:
Given what I earn, what I spend, what I owe and what the market is doing, how much can I reasonably invest right now, and what should I be wary of?
That is a join. On one side, your own transactions. On the other, rates, inflation, equities, gold, oil and currency. This is a walk-through of building that join as an agent in Dataiku, using only free data sources.
One framing point before the architecture. The hard part is not the agent. It is the accounting — and the free-tier limits, which shape the design far more than any model choice does.
What “free” actually buys you
The brief for this build was to avoid Bloomberg, Refinitiv and friends. That is achievable, but “free” varies enormously, and two of these limits are tight enough to dictate the architecture.
| Source | Key? | Free tier, as of November 2026 | Use it for |
|---|---|---|---|
| FRED | Yes | Generous; ample for daily pulls | US rates, CPI, Treasury yields |
| World Bank | No | Open, no registration | GDP, inflation by country |
| IMF | No | New SDMX 3.0 API | Global macro indicators |
| Alpha Vantage | Yes | ~25 requests/day, 5/min | Equities, ETFs, FX |
| SAHMK | Yes | 100 requests/day, no history | Tadawul quotes |
| GDELT | No | Open | Financial and geopolitical news |
| Frankfurter | No | Open, ECB reference rates | Currency conversion |
| EIA | Yes | Generous | Oil and energy prices |
| SEC EDGAR | No | Open, 10 req/sec, User-Agent required | Company filings |
Three of these deserve more than a table row.
Alpha Vantage is 25 calls a day. It was 500, then 100, and is now roughly 25 with a five-per-minute ceiling, with free keys restricted to outputsize=compact. This is the single most important constraint in the build. You cannot poll. You cannot refresh a watchlist of thirty tickers. You get a handful of calls, so every one must be deliberate and cached, and your flow must survive a day where the quota is already spent.
SAHMK’s free tier has no historical data. Free access covers current quotes, market summary, gainers and losers and sector performance, at around 100 requests a day. History, batch quotes and financials sit behind paid plans. That means your Saudi market history is something you accumulate yourself by snapshotting quotes on a schedule — which is a good argument for getting the scenario running early, because the history only starts when you do.
The IMF moved. The legacy data portal has been retired in favour of the IMF Data API on the SDMX 3.0 standard, and older IFS series codes stopped resolving without an official crosswalk. If you find a tutorial using the old JSON endpoint, it is dead. For most personal-finance purposes the World Bank covers the same ground with a simpler interface, so I would treat the IMF as optional.
All of these change. Check the current documentation before you build on any figure above — including mine.
The architecture
Seven layers, with one rule that matters more than the rest: the LLM never does arithmetic.
Every number in the final report — spend by category, savings rate, investable surplus, volatility — is computed in Python and handed to the agent as a fact. The agent’s job is to interpret, connect and caveat. The moment you let a model total a column, you have built something that is confidently wrong at unpredictable intervals, in a domain where that matters.
flowchart TD
A[Bank CSV · FRED · Alpha Vantage · SAHMK · World Bank · GDELT · Frankfurter · EIA] --> B[Ingestion: datasets + cached API recipes]
B --> C[Preparation: standardise, de-duplicate, detect transfers, categorise]
C --> D1[Personal finance metrics]
C --> D2[Market metrics]
D1 --> E[Investable surplus engine - deterministic]
D2 --> E
E --> F[Agent: Dataset Lookup, SQL Query, Knowledge Bank, Calculator]
F --> G[Dashboard + weekly briefing]
In Dataiku terms: datasets for everything persisted, Python recipes for ingestion and calculation, a knowledge bank for news and filings, agent tools over the resulting datasets, and a Scenario to run it weekly. Dataiku 14’s managed tools include Dataset Lookup, SQL Query, Knowledge Bank Search and Calculator, which maps almost exactly onto what this agent needs.
Getting statements in
Start manual. Download CSV or XLSX from online banking into a Dataiku managed folder, and treat Open Banking as a later version — in Saudi Arabia that means SAMA’s Open Banking framework and a licensed TPP, which is a different project with a different risk profile.
Every bank exports a different shape. Normalise to one schema immediately:
import pandas as pd
CANON = ["txn_date", "description", "amount", "currency", "account_id", "source_file"]
def load_statement(path: str, mapping: dict, account_id: str) -> pd.DataFrame:
"""Read one bank export and return the canonical schema.
`mapping` translates that bank's column names, e.g.
{"Transaction Date": "txn_date", "Narrative": "description",
"Debit": "debit", "Credit": "credit"}
"""
df = pd.read_csv(path) if path.endswith(".csv") else pd.read_excel(path)
df = df.rename(columns=mapping)
# Banks split debit/credit into two columns about as often as they use one.
if "amount" not in df.columns:
debit = pd.to_numeric(df.get("debit"), errors="coerce").fillna(0)
credit = pd.to_numeric(df.get("credit"), errors="coerce").fillna(0)
df["amount"] = credit - debit # income positive, spend negative
df["txn_date"] = pd.to_datetime(df["txn_date"], dayfirst=True, errors="coerce")
df["currency"] = df.get("currency", "SAR")
df["account_id"] = account_id
df["source_file"] = path
df["description"] = df["description"].astype(str).str.strip().str.upper()
return df.loc[df["txn_date"].notna(), CANON]
Note dayfirst=True. Saudi and UK statements are overwhelmingly DD/MM; a silent US-style parse turns 03/07 into March and corrupts every monthly total downstream. It is the most common quiet failure in this kind of pipeline.
The two traps that ruin the numbers
Double-counting card repayments. If you load both a current account and a credit card, the card purchases appear on the card statement and the repayment appears on the current account. Total them naively and your spending is inflated by roughly the value of everything you put on the card.
Internal transfers. Moving money to a savings account is not expenditure. Left in, your savings rate collapses and your “surplus” is understated.
Both are the same problem — a debit on one account matched by a credit on another — and both are solved by pairing:
import pandas as pd
def flag_internal_transfers(df: pd.DataFrame, tol_days: int = 3) -> pd.DataFrame:
"""Mark debit/credit pairs across your own accounts as internal.
A transfer is an outflow on one account matched by an inflow of the same
magnitude on another, within a few days. Card repayments are the same
shape, so this catches both.
"""
df = df.copy()
df["is_internal"] = False
out = df[df["amount"] < 0]
inn = df[df["amount"] > 0]
for i, debit in out.iterrows():
window = inn[
(inn["account_id"] != debit["account_id"])
& (inn["amount"].sub(-debit["amount"]).abs() < 0.01)
& (inn["txn_date"].sub(debit["txn_date"]).dt.days.abs() <= tol_days)
& (~inn.index.isin(df.index[df["is_internal"]]))
]
if not window.empty:
df.loc[[i, window.index[0]], "is_internal"] = True
return df
Everything downstream filters on ~is_internal. Keep the rows rather than dropping them — when a total looks wrong, the first question is always “what did the transfer matcher eat?”, and you want to be able to answer it.
Categorisation
Do it in two passes. Rules first, because they are free, instant and auditable:
RULES = {
"groceries": ["TAMIMI", "PANDA", "CARREFOUR", "DANUBE", "LULU"],
"fuel": ["ADNOC", "PETROMIN", "SASCO", "ALDREES"],
"utilities": ["SEC ", "NWC", "STC", "MOBILY", "ZAIN"],
"subscriptions": ["NETFLIX", "SPOTIFY", "ICLOUD", "ADOBE", "OPENAI"],
"dining": ["STARBUCKS", "ALBAIK", "HERFY", "TALABAT", "HUNGERSTATION"],
}
def rule_category(desc: str) -> str | None:
for category, needles in RULES.items():
if any(n in desc for n in needles):
return category
return None
Then send only the unmatched remainder to an LLM through the LLM Mesh, in batches, and cache the result by normalised description. Merchant strings repeat relentlessly, so after a few months almost everything is a cache hit and your model spend approaches zero. This is also the honest division of labour: rules handle the 80% you can enumerate, the model handles the long tail, and neither touches a number.
Recurring subscriptions fall out of the same data — group by normalised description and look for a stable monthly cadence:
def find_subscriptions(df: pd.DataFrame, min_occurrences: int = 3) -> pd.DataFrame:
spend = df[(~df["is_internal"]) & (df["amount"] < 0)].copy()
spend["merchant"] = spend["description"].str.replace(r"\d+", "", regex=True).str.strip()
out = []
for merchant, g in spend.groupby("merchant"):
if len(g) < min_occurrences:
continue
gaps = g.sort_values("txn_date")["txn_date"].diff().dt.days.dropna()
if gaps.empty:
continue
# Monthly-ish, and consistent: a subscription, not a coincidence.
if 26 <= gaps.median() <= 34 and gaps.std(ddof=0) < 6:
out.append({
"merchant": merchant,
"monthly_amount": round(-g["amount"].mean(), 2),
"occurrences": len(g),
"last_seen": g["txn_date"].max().date(),
})
return pd.DataFrame(out).sort_values("monthly_amount", ascending=False)
Market data on a 25-call budget
Because Alpha Vantage gives you so little, the market layer has to be built around caching rather than fetching. One generic, defensive caller handles every provider:
import os, json, time, pathlib, requests
from datetime import date
CACHE = pathlib.Path("/data/cache") # a Dataiku managed folder works too
CACHE.mkdir(parents=True, exist_ok=True)
def fetch_json(url: str, params: dict, cache_key: str,
ttl_hours: int = 24, headers: dict | None = None) -> dict | None:
"""GET with an on-disk cache. Returns None rather than raising, so one dead
provider never fails the whole scenario."""
path = CACHE / f"{cache_key}_{date.today().isoformat()}.json"
if path.exists() and (time.time() - path.stat().st_mtime) < ttl_hours * 3600:
return json.loads(path.read_text())
try:
r = requests.get(url, params=params, headers=headers or {}, timeout=30)
r.raise_for_status()
data = r.json()
except Exception as exc:
print(f"[warn] {cache_key} failed: {exc}")
stale = sorted(CACHE.glob(f"{cache_key}_*.json"))
return json.loads(stale[-1].read_text()) if stale else None
# Alpha Vantage returns HTTP 200 with a "Note"/"Information" body when
# you are rate-limited. Treat that as failure, not as data.
if isinstance(data, dict) and ({"Note", "Information"} & data.keys()):
print(f"[warn] {cache_key} rate-limited")
stale = sorted(CACHE.glob(f"{cache_key}_*.json"))
return json.loads(stale[-1].read_text()) if stale else None
path.write_text(json.dumps(data))
return data
That rate-limit detail catches people out: Alpha Vantage does not return 429. It returns 200 OK with an explanatory message where the data should be, so naive code stores a Note string as a price series and fails much later, somewhere confusing.
The providers themselves are straightforward:
FRED_KEY = os.environ["FRED_API_KEY"] # Dataiku: use a project secret
AV_KEY = os.environ["ALPHAVANTAGE_API_KEY"]
def fred_series(series_id: str, start: str = "2015-01-01"):
"""e.g. DGS10 (10y Treasury), CPIAUCSL (CPI), FEDFUNDS (policy rate)."""
return fetch_json(
"https://api.stlouisfed.org/fred/series/observations",
{"series_id": series_id, "api_key": FRED_KEY,
"file_type": "json", "observation_start": start},
cache_key=f"fred_{series_id}",
)
def av_daily(symbol: str):
"""One of your ~25 daily calls. Spend them deliberately."""
return fetch_json(
"https://www.alphavantage.co/query",
{"function": "TIME_SERIES_DAILY", "symbol": symbol,
"outputsize": "compact", "apikey": AV_KEY},
cache_key=f"av_{symbol}",
)
def worldbank_indicator(country: str, indicator: str):
"""No key. e.g. SAU / FP.CPI.TOTL.ZG for Saudi inflation."""
return fetch_json(
f"https://api.worldbank.org/v2/country/{country}/indicator/{indicator}",
{"format": "json", "per_page": 100},
cache_key=f"wb_{country}_{indicator}",
)
def fx_rate(base: str = "USD", symbols: str = "SAR,EUR,GBP"):
"""Frankfurter: no key, ECB reference rates."""
return fetch_json("https://api.frankfurter.dev/v1/latest",
{"base": base, "symbols": symbols}, cache_key=f"fx_{base}")
def gdelt_news(query: str, timespan: str = "7d", maxrecords: int = 50):
"""No key. Returns articles, not prices - treat as qualitative context."""
return fetch_json(
"https://api.gdeltproject.org/api/v2/doc/doc",
{"query": query, "mode": "artlist", "format": "json",
"timespan": timespan, "maxrecords": maxrecords},
cache_key=f"gdelt_{abs(hash(query))}",
)
For SEC EDGAR, the one non-obvious requirement is that you must identify yourself or you get blocked:
EDGAR_HEADERS = {"User-Agent": "Personal Finance Agent your.name@example.com"}
Append every successful pull to a history dataset rather than overwriting. For SAHMK in particular this is the only way you will ever have Saudi history on a free plan — the snapshot you take today is the data you will have in six months.
The surplus calculation
This is the number the whole thing exists to produce, and it is pure arithmetic. No model goes anywhere near it.
def investable_surplus(
monthly_income: float,
monthly_essential_spend: float,
monthly_discretionary_spend: float,
liquid_savings: float,
credit_card_balance: float,
committed_outflows: float = 0.0,
emergency_months: float = 6.0,
) -> dict:
"""Deterministic. Every figure traceable to a transaction or a balance."""
monthly_spend = monthly_essential_spend + monthly_discretionary_spend
monthly_net = monthly_income - monthly_spend - committed_outflows
emergency_target = monthly_essential_spend * emergency_months
buffer_gap = max(0.0, emergency_target - liquid_savings)
# Card debt is almost always dearer than expected returns: clear it first.
deployable = max(0.0, liquid_savings - emergency_target - credit_card_balance)
return {
"monthly_net_cash_flow": round(monthly_net, 2),
"savings_rate_pct": round(100 * monthly_net / monthly_income, 1) if monthly_income else 0.0,
"emergency_fund_target": round(emergency_target, 2),
"emergency_fund_gap": round(buffer_gap, 2),
"investable_now": round(deployable, 2),
"investable_monthly": round(max(0.0, monthly_net), 2),
"blocked_reason": (
"Emergency fund below target" if buffer_gap > 0
else "Credit card balance outstanding" if credit_card_balance > 0
else None
),
}
The ordering encodes a deliberate opinion: emergency fund, then card debt, then investing. The agent is not permitted to re-order it, and when investable_now is zero it must say so rather than suggesting an allocation anyway. That is the behaviour you most need to pin down, because an agent asked “where should I invest?” will cheerfully answer even when the correct response is “nowhere yet”.
The agent
Four tools, matching Dataiku’s managed set:
| Tool | Backed by | Returns |
|---|---|---|
| Dataset Lookup | personal_finance_summary | Income, spend by category, savings rate, subscriptions |
| SQL Query | market_history | Price, rate and CPI series with observation dates |
| Knowledge Bank Search | GDELT + EDGAR | News and filings, with source and date |
| Calculator | — | Arithmetic the agent must not do itself |
A system prompt that holds up in practice:
You are a personal finance analyst. You have read-only access to the user's
own financial data and to market datasets built from public sources.
RULES
1. Every figure you state must come from a tool call. Never estimate,
interpolate or recall a number from training.
2. Never perform arithmetic yourself. Use the calculator tool.
3. Cite the source and the observation date for every market figure.
Say "as of" explicitly - stale data presented as current is the failure
mode that matters most here.
4. Separate three things, visibly: what the data says; what you infer;
what is uncertain.
5. If investable_now is zero or the emergency fund is below target, say so
and stop. Do not suggest an allocation anyway.
6. Name risks, including the ones that cut against an attractive option.
7. You are decision support, not a licensed adviser. You do not predict
prices and you never execute transactions.
If a tool fails or returns nothing, say so. Do not fill the gap.
Rules 1 and 2 are the load-bearing ones. The rest is tone; those two are what keep the output trustworthy.
The weekly briefing
The output worth building towards is a single page that joins both halves. Illustrative figures only:
Week to 6 November 2026 — hypothetical
Net cash flow +SAR 7,400; savings rate 31%, up from 27% in October. Spend SAR 16,600, of which discretionary SAR 4,900. Dining is up 38% on your trailing three-month average — eleven transactions against a usual six. Two subscriptions renewed (SAR 310/month combined); one has not been used in the period covered by your statements.
Emergency fund at SAR 71,000 against a six-month target of SAR 70,200 — target met this month. Card balance nil. Investable now: SAR 43,800, plus SAR 7,400/month recurring.
Markets, as of 5 November: US 10-year 4.18% (−12bp on the week, FRED). Gold +2.1%, with 30-day realised volatility above its one-year median — moving more than usual, which cuts both ways. Brent −1.4% (EIA). USD/SAR unchanged at the peg (Frankfurter). TASI snapshot +0.6% on the week, from our own accumulated series — short history, treat as directional.
For your attention: the surplus has crossed the emergency-fund threshold for the first time, so this is a genuine allocation decision rather than a theoretical one. Against that: gold volatility is elevated, so sizing matters more than usual this week.
One report, not two. If the market section could be cut and pasted into someone else’s briefing unchanged, it is not doing its job.
Governance
This project holds a complete picture of someone’s finances, which deserves more care than a side project usually gets.
- Secrets in Dataiku project variables or a secrets backend, read via environment variables. Never in recipe code, never in notebook output.
- Access control at project level. A finance project is not a project to share widely “so someone can take a look”.
- LLM exposure is the decision that needs making consciously: categorisation sends merchant strings to a model. Under the LLM Mesh you can route that to a locally hosted or private endpoint. Either way, decide it deliberately rather than discovering it later.
- Retention: keep derived aggregates long, raw statements only as long as you need them.
- Validation: reconcile computed totals against the statement’s own closing balance every run. If they disagree, the pipeline is wrong and every downstream number is wrong with it.
- Human approval before any money moves. The agent writes briefings; it does not place orders, and it should not be wired to anything that could.
And the obvious one: this is decision support, not regulated financial advice.
Implementation checklist
- Dataiku project; managed folder for statements; secrets for FRED, Alpha Vantage, EIA, SAHMK.
- Ingestion recipe → canonical schema. Verify
dayfirstagainst a known transaction. - De-duplication and transfer matching. Reconcile against closing balances before continuing.
- Rule-based categorisation, then LLM for the remainder, cached by merchant.
- Subscription and anomaly detection.
- Market pull recipes, all through the cached fetcher. Append to history; never overwrite.
- Surplus engine as a pure function, with unit tests.
- Knowledge bank over GDELT and EDGAR.
- Agent with four tools and the prompt above.
- Scenario: refresh market data → process statements → recompute → generate briefing → email. Weekly.
- Dashboard for the series the briefing references.
Start the scenario before the agent. SAHMK gives you no history on the free tier, so the only Saudi market series you will ever have is the one you begin accumulating today — and that is worth more than getting the prompt right in week one.
Figures in the sample briefing are hypothetical. API limits were checked in November 2026 and move frequently; verify current documentation before relying on any of them.