babilonia.accounting#

Brazil-specific accounting classes and tax reference constants.

Provides data classes for parsing and analyzing bank statements from Banco do Brasil and Nubank, computing cash flow summaries, managing budget records, and loading NFSe XML invoices. Module-level constants hold the 2025 INSS and IRRF progressive tax tables.

Classes

BBCDB([name, alias])

Parses Banco do Brasil CDB investment statement text files.

Budget([name, alias])

A record table for managing budget items.

CashFlow([name, alias])

A primitive class for handling Cash flow analysis

CashFlowBBCC([name, alias])

A class for handling CSV data from Banco do Brasil Conta Corrente.

CashFlowBBCCPJ([name, alias])

Class for handling BB-CC for PJ accoung CSV data.

CashFlowBBPP([name, alias])

Class for handling BB-PP CSV data.

CashFlowNUCredit([name, alias, invert_sign])

A class for handling CSV data exported from Nubank Cartão de Crédito (Nubank credit card) invoices.

NFSe([name, alias])

Class for handling NFSe XML data.

NFSeColl([base_object, name, alias])

A collection of NFSe objects.

class babilonia.accounting.Budget(name='MyBudget', alias='Bud')[source]#

Bases: RecordTable

A record table for managing budget items.

Extends RecordTable to track revenues and expenses with support for contract grouping, payment status, due dates, and file attachments. Signed totals and per-status or per-contract summaries are recomputed automatically on update.

update()[source]#

Refresh all mutable attributes based on data (including paths).

set_data(input_df)[source]#

Set RecordTable data from incoming dataframe. Expected to be incremented downstream.

Parameters:

input_df (dataframe) – incoming dataframe

Returns:

None

Return type:

None

get_summary_by_type()[source]#
get_summary_by_status(filter_df=True)[source]#
get_summary_by_contract(filter_df=True)[source]#
get_summary_by_tags(filter_df=True)[source]#
static parse_annual_budget(year, budget_df, freq_field='Freq')[source]#
class babilonia.accounting.CashFlow(name='CashFlow', alias='CF')[source]#

Bases: DataSet

A primitive class for handling Cash flow analysis

Cashflow Analysis Example
from babilonia.accounting import CashFlow

# create an empty class
cf = CashFlow()

# set the file for CSV
file_csv = "path/to/file.csv" # [change this]

# load data
cf.load_data(file_csv)

# call method
dc = cf.cashflow_analysis(df=cf.data, category="Custeio")

# print data
print(dc["monthly"])
print(dc["yearly"])
Balance vs Levels Example

Check the running balance against the levels in an optional levels.json placed in the account folder (its schema is documented in load_levels()), and plot it.

from babilonia.accounting import CashFlow

# account folder: holds the data and, optionally, levels.json
folder = "path/to/account"  # [change this]

# load data
cf = CashFlow()
cf.load_data(file_data=f"{folder}/file.csv")  # [change this]

# load the level rules (None if there is no levels.json)
levels = CashFlow.load_levels(folder=folder)

# monthly balance + one Level_<name> column per level + Status
panel = CashFlow.get_balance_panel(
    df=cf.data,
    initial_cash=30000,  # [change this] balance before the data
    levels=levels,
)
print(panel[["Mes", "Saldo", "Status"]])

# plot, with the same style overrides as the other plots
config = CashFlow.load_plot_config(folder=folder)
CashFlow.plot_balance(
    panel=panel,
    file_out=f"{folder}/balance.jpg",
    levels=levels,
    config=config,
)

Levels can also be passed inline instead of from a file – the rules dict or just its list:

levels = [
    {"name": "target", "value": 30000, "kind": "reference"},
    {"name": "minimum", "value": 15000, "kind": "critical"},
]
load_data(file_data)[source]#

Load data from file.

Parameters:

file_data (str) – file path to data.

static get_cashflow_analysis(df, category=None)[source]#

Perform cash flow analysis with monthly and yearly aggregation.

This method classifies cash flows into inputs and outputs, aggregates values on a monthly and yearly basis, and computes cumulative balances. The analysis is fully independent from class state and inheritance behavior.

Parameters:
  • df (pandas.DataFrame) – Input cash flow data containing at least the columns Data, Categoria and Valor.

  • category (str or None) – Optional category filter. If None, all categories are grouped under "Geral".

Returns:

Dictionary with monthly and yearly cash flow summaries.

Return type:

dict

static compute_oir(df, input_field='Entradas', output_field='Saidas')[source]#
static enrich_time_index(df)[source]#

Add year and year-month time indices to the cash flow data.

This method extracts the calendar year and a YYYY-MM monthly identifier from the Data column.

Parameters:

df (pandas.DataFrame) – Input cash flow data.

Returns:

Copy of the input data with additional Ano and Mes columns.

Return type:

pandas.DataFrame

static classify_flows(df)[source]#

Classify cash flows as inputs or outputs.

Positive or zero values are classified as "In" and negative values as "Out".

Parameters:

df (pandas.DataFrame) – Cash flow data containing a Valor column.

Returns:

Copy of the input data with an additional Flow column.

Return type:

pandas.DataFrame

static filter_category(df, category)[source]#

Filter cash flow data by category.

If no category is provided, all records are grouped under the default category "Geral".

Parameters:
  • df (pandas.DataFrame) – Cash flow data.

  • category (str or None) – Category name used to filter the data.

Returns:

Tuple containing the filtered data and the resolved category name.

Return type:

tuple

static get_monthly_summary(df, category)[source]#

Compute monthly cash flow summaries for each year.

This method aggregates cash flow inputs and outputs on a monthly basis, ensures that all calendar months are present, and computes annual cumulative balances.

Parameters:
  • df (pandas.DataFrame) – Cash flow data enriched with time indices and flow classification.

  • category (str) – Category name associated with the analysis.

Returns:

Monthly cash flow summary table.

Return type:

pandas.DataFrame

static get_yearly_summary(df_monthly, category)[source]#

Compute yearly cash flow summaries.

This method aggregates monthly cash flow data into yearly totals and computes cumulative balances across years.

Parameters:
  • df_monthly (pandas.DataFrame) – Monthly cash flow summary table.

  • category (str) – Category name associated with the analysis.

Returns:

Yearly cash flow summary table.

Return type:

pandas.DataFrame

static get_daily_summary(df, year)[source]#

Compute daily Entradas/Saidas totals for every calendar day in year.

Unlike get_monthly_summary(), no category breakdown is kept – this is meant for plotting a full-year daily timeseries, where every day must be present (as a zero bar) even without transactions.

Parameters:
  • df (pandas.DataFrame) – Cash flow data containing at least Data and Valor.

  • year (int or str) – Calendar year to cover, start to end.

Returns:

One row per day of year, with Data, Entradas, Saidas and Fluxo columns.

Return type:

pandas.DataFrame

static get_cashflow_report(df, year=None, initial_cash=None)[source]#

Build a yearly cash flow panel and summary by category.

Parameters:
  • df (pandas.DataFrame) – Cash flow DataFrame containing transactional data with date, category, and value information compatible with the enrich_time_index, classify_flows, and cashflow_analysis methods.

  • year (int, optional) – Year to be analyzed. If None, the current calendar year (local time) is used.

  • initial_cash (float, optional) – Initial account balance at the beginning of the selected year. If None, defaults to 0.0.

Returns:

Dictionary containing: "Pannel": monthly cash flow panel with totals, per-category flows, and running balance. "Summary": yearly summary by category with total, mean, and percentage contribution to total inflows.

Return type:

dict

static format_currency(x: float)[source]#
static format_currency_columns(df: pandas.DataFrame, columns: list[str]) → pandas.DataFrame[source]#

Return a copy of df with selected numeric columns formatted as strings.

static format_compact(x, decimals=1)[source]#

Format a value as a compact string, rounding to K (thousand) or M (million) once the magnitude is too big to annotate as-is.

Parameters:
  • x (float) – Value to format.

  • decimals (int) – Decimal places kept on the K/M value.

Returns:

Compact string, e.g. "1.2K", "-3.4M", "850".

Return type:

str

static load_plot_config(folder)[source]#

Load tool config overrides from cashflow.json in folder.

Every key is optional, and so is the file itself: anything missing falls back to PLOT_CONFIG_DEFAULTS. Figure size, bar colors, bar width, background color, histogram panel size/bins/ color and font sizes are the tunable surface for plot_cashflow_bars(); language controls the printed table headers in cashflow.py (see its COLUMN_LABELS) – currently "en" (default) or "pt-br".

{
    "figsize_mm": [150, 80],
    "dpi": 300,
    "color_inflows": "tab:blue",
    "color_outflows": "tab:red",
    "background_color": "#F7F7FB",
    "language": "en",
    "fontsize_title": 10,
    "fontsize_annotation": 5,
    "fontsize_ticks": 8,
    "bar_width_pct": 60,
    "hist_width_pct": 33,
    "hist_bin_size": null,
    "color_hist": null
}

color_hist is null by default, meaning the histogram panel keeps the main panel’s inflow/outflow color split; set it to a single color (e.g. "tab:gray") to use that for both sides of the histogram instead. hist_bin_size is also null by default, meaning the bin width is computed from the data itself via compute_optimal_bin_size() (Scott’s rule) rather than fixed; set it to a number to use a fixed currency-wide bin instead.

Parameters:

folder (str or pathlib.Path) – Bank/account folder where cashflow.json is expected (the same folder the plots are written to).

Returns:

PLOT_CONFIG_DEFAULTS overridden by any keys present in the file, or an unmodified copy if the file is absent.

Return type:

dict

static compute_optimal_bin_size(values)[source]#

Compute a histogram bin width via Scott’s rule, rounded to a clean 1/2/5 x 10^k step for a readable currency axis.

Scott’s rule (3.49 * std * n ** -1/3) assumes a roughly normal distribution and adapts to sample size – a longer series (more months) gets proportionally finer bins on its own, with no manual scaling needed. Used as the default for hist_bin_size (None in PLOT_CONFIG_DEFAULTS) whenever it is not set explicitly.

Parameters:

values (array-like) – Sample to size bins for (e.g. Entradas and Saidas.abs() concatenated).

Returns:

Bin width, always > 0.

Return type:

float

static plot_cashflow_bars(df, x_col, file_out, title=None, scale=None, annotate=False, date_axis=False, year_ticks=False, ylim_default=100000, config=None)[source]#

Plot Entradas/Saidas as a diverging bar chart and save it as a JPEG.

Entradas (always >= 0) are drawn above the zero line and Saidas (always <= 0) below it, both anchored at the same baseline for every value of x_col. No legend is drawn – the color convention is stated once via scale in the title instead of repeating a color key on every plot. Month ticks are single letters ("J", "F", …), the y-axis is compacted to whole K/M (no decimals) via format_compact(), and the y-limits are symmetric around zero so 0 always sits at the vertical center of the plot: fixed at ylim_default unless some bar would be clipped by it, in which case 1.1 * max(|Entradas|, |Saidas|) is used instead – this keeps the scale stable (and years comparable) for ordinary months, only growing for an outlier year.

A second panel to the right (hist_width_pct of the total width, default a third) shares the main panel’s y-axis and shows it as a horizontal histogram instead – a sideways projection of the monthly series’ distribution. Entradas values are binned into hist_bin_size currency-wide bins (or, if unset, bins sized by compute_optimal_bin_size()) from 0 upward and drawn as bars extending right from x=0 in the positive region; Saidas are binned the same way (by magnitude) and mirrored into the negative region, so bin position lines up directly with the main panel’s y-scale. The histogram’s x-limit is fixed at twice its tallest bar (not autoscaled), so no single bin is ever stretched edge-to-edge. Both sides use color_inflows/color_outflows (the same split as the main bars) unless color_hist is set, in which case it covers both sides with a single color instead. A solid horizontal line marks each series’ mean (Entradas.mean(), Saidas.mean()) across the histogram panel, in that series’ own color regardless of color_hist, annotated (in the default annotation text color, like the bar annotations) with the rounded value at the line’s upper-right.

Every visual aspect – figure size, bar colors, background color, bar width, histogram panel width and bin size, font sizes – comes from config (see load_plot_config()), falling back to PLOT_CONFIG_DEFAULTS for anything missing.

Parameters:
  • df (pandas.DataFrame) – Data with x_col, Entradas and Saidas columns.

  • x_col (str) – Column used for the x-axis (e.g. "Data" or "Mes").

  • file_out (str or pathlib.Path) – Destination path for the .jpg file.

  • title (str, optional) – Optional chart title.

  • scale (str, optional) – Granularity label (e.g. "Daily", "Monthly"), appended to title.

  • annotate (bool) – If True, print each bar’s value at its outer edge, compacted via format_compact(). Meant for charts with few bars (e.g. monthly); too dense for a daily timeseries.

  • date_axis (bool) – If True, x_col is treated as a datetime axis and tick marks are placed once per month.

  • year_ticks (bool) – If True (meant for a multi-year x_col like "YYYY-MM", e.g. the full-history monthly series), only January of each year gets a tick, labeled with that year’s number – no per-month letters, so a many-year series stays readable. Ignored when date_axis is True.

  • ylim_default (float) – Fixed symmetric y-limit used as long as it does not clip any bar.

  • config (dict, optional) – Style overrides, as returned by load_plot_config(). Missing keys fall back to PLOT_CONFIG_DEFAULTS.

Returns:

The file_out path, for logging by the caller.

Return type:

str or pathlib.Path

static load_levels(folder)[source]#

Load balance level rules from levels.json in folder.

A level is a horizontal line the account’s running balance is checked against, month by month – a target to aim at, a threshold that should not be crossed, a floor that must never be broken. levels.json lists them. It sits in the account folder, next to cashflow.json, but the two files have different jobs: cashflow.json only changes how plots look; levels.json defines what the balance means.

The file is optional. Without it, get_balance_panel() marks every month "ok" and plot_balance() draws the plain balance.

File structure

The file is one JSON object with two keys:

Key

Type

Required

Meaning

title

string

no

Plot title. A title passed to plot_balance() overrides it.

levels

list of objects

yes

The levels, one object each, in any order and any number (one is fine). A file without this key raises ValueError.

Each object in levels takes these keys:

Key

Type

Required

Default

Meaning

name

string

yes

–

Suffix of the panel column Level_<name>. Must be unique.

kind

string

yes

–

What crossing it means. One of "reference", "warning", "critical" (see below). Any other value raises ValueError.

value

number

yes, unless follow is set

–

The level, in currency units (e.g. 30000).

growth_yearly

number

no

0

Compound yearly growth applied to value from the first month with data, as a fraction: 0.045 raises the level 4.5% a year (e.g. to keep it indexed to inflation).

follow

string

no

–

"peak": ignore value and use the balance’s own running peak instead – a level that only ever moves up, for a balance that must never shrink. Any other value raises ValueError.

fraction

number

no

1.0

Only with follow. Multiplies the peak: 0.95 tolerates a 5% drawdown from the peak.

Level kinds

kind

Balance below it

Drawn as

"reference"

Nothing happens – the line is informative only (e.g. a target).

Dashed gray line.

"warning"

The month’s status becomes "warning".

Dashed amber line; the month gets an amber band.

"critical"

The month’s status becomes "critical".

Dashed red line; the month gets a red band.

When several levels are crossed in the same month, the worst kind wins: critical over warning over ok.

Example – a reserve with a target and two thresholds

Aim at 30K, warn below 27K, treat anything under 15K as critical:

{
    "title": "Reserve",
    "levels": [
        {"name": "target", "value": 30000, "kind": "reference"},
        {"name": "alert", "value": 27000, "kind": "warning"},
        {"name": "minimum", "value": 15000, "kind": "critical"}
    ]
}
Example – a single floor, indexed to inflation

One critical line starting at 10K and growing 4.5% a year:

{
    "levels": [
        {
            "name": "floor",
            "value": 10000,
            "kind": "critical",
            "growth_yearly": 0.045
        }
    ]
}
Example – a balance that must never shrink

No fixed value: the level is the balance’s own running peak, so any month below a previous high is critical. Add "fraction": 0.95 to tolerate a 5% drawdown instead.

{
    "title": "Long-term portfolio",
    "levels": [
        {"name": "peak", "follow": "peak", "kind": "critical"}
    ]
}
Parameters:

folder (str or pathlib.Path) – Account folder where levels.json is expected.

Returns:

The parsed rules, or None if the file is absent.

Return type:

dict or None

static get_balance_panel(df, initial_cash=0.0, levels=None, saldos=None)[source]#

Build a monthly balance panel, checked against optional levels.

The balance comes from one of two sources:

  • Flows only (saldos=None): initial_cash plus the cumulative sum of Valor. Right when the flows are complete and the opening balance is known.

  • Observed balances (saldos given): balances read from the bank (e.g. the SALDOS_*.csv files) anchor the series, and flows only fill the gaps between them. Each month’s balance is the nearest observation at or before its last day, plus the flows after that observation; months before the first observation are walked back from it. A balance observed on Data is taken as the balance at the end of that day, after its flows. initial_cash is ignored. Use this when the flows miss something the bank adds on its own – interest, fees, IR withheld – or when the opening balance is not known.

Parameters:
  • df (pandas.DataFrame) – Cash flow data with typed Data and Valor.

  • initial_cash (float) – Balance before the first transaction. Only used without saldos.

  • levels (dict or list or None) – Level rules, as returned by load_levels() (the dict, or just its "levels" list). None for none.

  • saldos (pandas.DataFrame or None) – Observed balances, with typed Data and Valor (the balance on that date). Several rows per month are fine; any other columns are ignored.

Returns:

One row per calendar month, always covering whole years – January of the first year with data to December of the last, like get_monthly_summary() – with Mes, Entradas, Saidas, Fluxo, Saldo (end of month), Saldo_Fonte ("observado" if a balance was observed in that month, else "calculado"), one column per level holding its value that month (Level_<name>) and Status ("ok", "warning" or "critical", the worst kind among the levels the balance is below). Months before the first data point or after the last one (e.g. the rest of the current year) are padding: zero flows, Saldo NaN, empty Saldo_Fonte and Status. Fixed levels still have a value there (a target holds for the months ahead); a peak-following level is empty before the data and holds its last value after it. With saldos, “data” also includes every observation date.

Return type:

pandas.DataFrame

static plot_balance(panel, file_out, levels=None, title=None, year_ticks=None, config=None)[source]#

Plot a monthly balance against its levels and save it as a JPEG.

Top panel: the end-of-month balance (Saldo) as a black step line. Each level is a dashed step line (so a growing or peak-following level reads month by month) – gray for reference, amber for warning, red for critical – with its value at the line’s right end written inside the plot (December, on a padded year). Level names are not drawn; the values and colors carry them, and the names live in levels.json.

Trouble is shown by period, not by point: every month in warning status gets a vertical amber band, every month in critical a vertical red band, across both panels – so a stretch of trouble reads as one block of time, lined up with the flows that caused it. Above the frame, a small key on the right names the two colors and a badge on the left states the current status in words, so status never relies on color alone – and neither ever covers the data.

Bottom panel: the monthly Entradas/Saidas as diverging bars, in the same colors as plot_cashflow_bars(), on their own y-axis – flows and the balance they produce never share a scale.

The y-range runs down to zero (how far the balance is from empty), except when a level follows the peak: then it zooms onto the data, since a drawdown is small next to the total.

The x-axis adapts to the length of the series. Up to BALANCE_YEAR_TICKS_AFTER months (3 years), every month gets a letter ("J", "F", …) with the year under each January. Beyond that, the letters would run together: only January is labeled, with its year, and the other months keep an unlabeled tick mark.

Parameters:
  • panel (pandas.DataFrame) – Output of get_balance_panel().

  • file_out (str or pathlib.Path) – Destination path for the .jpg file.

  • levels (dict or list or None) – The same level rules passed to get_balance_panel(). None plots the plain balance.

  • title (str, optional) – Chart title; defaults to the rules’ "title".

  • year_ticks (bool or None) – True labels only Januaries (with the year), False labels every month; None (default) picks by length, as described above.

  • config (dict, optional) – Style overrides, as returned by load_plot_config().

Returns:

The file_out path, for logging by the caller.

Return type:

str or pathlib.Path

class babilonia.accounting.CashFlowBBCC(name='CashFlowBBCC', alias='CFBBCC')[source]#

Bases: CashFlow

A class for handling CSV data from Banco do Brasil Conta Corrente.

Script example
from babilonia.accounting import CashFlowBBCC

# create an empty class
cf = CashFlowBBCC()

# set the file for CSV
file_csv = "path/to/file.csv" # [change this]

# load data
cf.load_data(file_csv)

# standardize data
cf.standardize()

# print data
print(cf.data.head(10))

# save data
file_out = "path/to/output.csv" # [change this]
cf.data.to_csv(file_out, sep=";", index=False)
load_data(file_data)[source]#

Load raw data from bank CSV statement

Parameters:

file_data (str or Path) – Bank statement CSV file path

Returns:

None

Return type:

None

standardize(force=False)[source]#

Standardize data into canonical format.

Parameters:

force – Rebuild parsed data even if it exists

parse_data(df=None)[source]#

Parse data to canonical format

Parameters:

df (pandas.DataFrame) – Optional input data

Returns:

Formated data

Return type:

pandas.DataFrame

parse_date(series)[source]#

Parse BB date field from DD/MM/YYYY to datetime.

Parameters:

series (pandas.Series) – String series

Returns:

Datetime series

Return type:

pandas.Series

parse_valor(series)[source]#

Convert Valor field to float.

Examples

Input

Output

5.000,00

5000.00

-403,00

-403.00

Parameters:

series (pandas.Series) – String series

Returns:

Value series

Return type:

pandas.Series

apply_drops(df)[source]#

Filter dataframe for parsing

Parameters:

df (pandas.DataFrame) – Input data

Returns:

Output data

Return type:

pandas.DataFrame

normalize_columns(df)[source]#

Normalize legacy / alternative column names to the current schema.

Parameters:

df (pandas.DataFrame) – Input data

Returns:

Output data

Return type:

pandas.DataFrame

class babilonia.accounting.CashFlowBBCCPJ(name='CashFlowBBCCPJ', alias='CFBBCCPJ')[source]#

Bases: CashFlowBBCC

Class for handling BB-CC for PJ accoung CSV data.

parse_valor(series)[source]#

Convert Valor field to float.

Two T0 export variants are supported, so a file from either (or a single file spanning the transition) parses correctly:

  • Legacy, marker-suffixed: sign comes from a trailing C/D marker, discarding whatever sign the string itself carries (e.g. "5.000,00 C" -> credit/inflow, "403,00 D" and "-403,00 D" both -> debit/outflow).

  • Newer, plain signed value with no marker (a separate Tipo Lançamento column states “Entrada”/”Saída” redundantly): handled by the base CashFlowBBCC.parse_valor(), sign taken directly from the string (e.g. "-3.000,00" -> outflow, "3.423,00" -> inflow).

Examples

Input

Output

5.000,00 C

5000.00

-403,00 D

-403.00

-3.000,00

-3000.00

3.423,00

3423.00

Parameters:

series (pandas.Series) – String series

Returns:

Value series

Return type:

pandas.Series

apply_drops(df)[source]#

Filter dataframe for parsing

Parameters:

df (pandas.DataFrame) – Input data

Returns:

Output data

Return type:

pandas.DataFrame

class babilonia.accounting.CashFlowBBPP(name='CashFlowBBPP', alias='CFBBPP')[source]#

Bases: CashFlowBBCC

Class for handling BB-PP CSV data.

parse_data(df=None)[source]#

Parse data to canonical format

Parameters:

df (pandas.DataFrame) – Optional input data

Returns:

Formated data

Return type:

pandas.DataFrame

parse_valor(series: pandas.Series) → pandas.Series[source]#

Convert Valor field to float.

Examples

Input

Output

5.000,00 C

5000.00

-403,00 D

-403.00

Parameters:

series (pandas.Series) – String series

Returns:

Value series

Return type:

pandas.Series

apply_drops(df)[source]#

Filter dataframe for parsing

Parameters:

df (pandas.DataFrame) – Input data

Returns:

Output data

Return type:

pandas.DataFrame

class babilonia.accounting.CashFlowNUCredit(name='CashFlowNuCC', alias='CFNUCC', invert_sign=True)[source]#

Bases: CashFlow

A class for handling CSV data exported from Nubank Cartão de Crédito (Nubank credit card) invoices.

Nubank appears to export at least two CSV variants for the same date,title,amount schema:

  • Quoted, Brazilian-formatted values, e.g. "1.234,56" or "- 41,97" (comma decimal separator, dot thousands separator, sometimes a space between the minus sign and the digits).

  • Unquoted, international-formatted values, e.g. 1234.56 or -6722.00 (dot decimal separator, no thousands separator).

parse_valor auto-detects and normalizes both variants.

Note on sign convention: Nubank reports purchases as positive amount and payments/refunds (“Pagamento recebido”) as negative. By default this class inverts that sign when building the canonical Valor field, so purchases become outflows (negative Valor, classified as "Out") and payments/refunds become inflows (positive Valor, classified as "In") — consistent with how CashFlow.classify_flows() is used for the BB accounts. Pass invert_sign=False at construction time to keep Nubank’s raw sign convention instead.

Script example
from babilonia.accounting import CashFlowNuCC

# create an empty class
cf = CashFlowNuCC()

# set the file for CSV
file_csv = "path/to/file.csv"  # [change this]

# load data
cf.load_data(file_csv)

# standardize data
cf.standardize()

# print data
print(cf.data.head(10))

# save data
file_out = "path/to/output.csv"  # [change this]
cf.data.to_csv(file_out, sep=";", index=False)
load_data(file_data)[source]#

Load raw data from the Nubank credit-card CSV export.

Parameters:

file_data (str or Path) – Nubank credit-card CSV file path

Returns:

None

Return type:

None

standardize(force=False)[source]#

Standardize data into canonical format.

Parameters:

force – Rebuild parsed data even if it exists

parse_data(df=None)[source]#

Parse data to canonical format

Parameters:

df (pandas.DataFrame) – Optional input data

Returns:

Formated data

Return type:

pandas.DataFrame

parse_date(series)[source]#

Parse Nubank date field from YYYY-MM-DD to datetime.

Parameters:

series (pandas.Series) – String series

Returns:

Datetime series

Return type:

pandas.Series

parse_valor(series)[source]#

Convert amount field to float, auto-detecting the CSV variant.

Examples

Input

Output (before sign inversion)

"50,50"

50.50

"- 3.784,83"

-3784.83

69.99

69.99

-6722.00

-6722.00

Parameters:

series (pandas.Series) – String series

Returns:

Value series

Return type:

pandas.Series

apply_drops(df)[source]#

Filter dataframe for parsing. No rows are dropped by default; override or extend this to filter specific transactions if needed.

Parameters:

df (pandas.DataFrame) – Input data

Returns:

Output data

Return type:

pandas.DataFrame

normalize_columns(df)[source]#

Normalize alternative / legacy column names to the current schema.

Parameters:

df (pandas.DataFrame) – Input data

Returns:

Output data

Return type:

pandas.DataFrame

class babilonia.accounting.BBCDB(name='BBCDB', alias='BBCDB')[source]#

Bases: DataSet

Parses Banco do Brasil CDB investment statement text files.

Reads the plain-text report exported by BB for CDB DI and CDB Progressivo accounts and splits it into named sections (EXTRATO, SALDOS, DEPOSITOS, RENDIMENTOS), normalizing each into a pandas.DataFrame. The result is stored in self.data as a nested dictionary keyed by account then section name.

load_data(file_data)[source]#

Load data from file.

Parameters:

file_data (str) – file path to data.

static read_txt(file_txt, encoding='cp1252')[source]#
static drop_blank_lines(lines)[source]#
static drop_lines(lines, contains='-')[source]#
static replace_lines(lines, contains='\xa0', relacer=' ')[source]#
static split_accounts(lines)[source]#
static split_sections(dc_data)[source]#
static get_year(lines)[source]#
class babilonia.accounting.NFSe(name='NFSeDataSet', alias='NFSe')[source]#

Bases: DataSet

Class for handling NFSe XML data.

get_metadata()[source]#

Get a dictionary with object metadata.

Returns:

dictionary with all metadata

Return type:

dict

Warning

Metadata does not necessarily include all object attributes.

load_data(file_data)[source]#

Load and parse XML data from the provided file.

Parameters:

file_data (str) – file path to the NFSe XML data.

Returns:

None

class babilonia.accounting.NFSeColl(base_object=<class 'babilonia.accounting.NFSe'>, name='MyNFeCollection', alias='NFeCol0')[source]#

Bases: Collection

A collection of NFSe objects.

Extends Collection to load and aggregate multiple NFSe XML files into a shared catalog, either from a folder or an explicit list of file paths.

load_folder(folder)[source]#

Load NFSe files from a folder

Parameters:

folder (str) – path to folder

Returns:

None

Return type:

None

load_files(lst_files)[source]#

Load NFSe files from a list of files

Parameters:

lst_files (list) – list of paths to files

Returns:

None

Return type:

None