Julia interface for public electoral data from Brazil's TSE (Tribunal Superior
Eleitoral), inspired by the R package
electionsBR, but following
Julia ecosystem conventions (DataFrames.jl, CSV.jl, Scratch.jl).
The package uses only the open data files published at
https://cdn.tse.jus.br/estatistica/sead/odsele/ — no private API or
authorisation is required.
- Automatic download of TSE ZIPs, with retry logic and atomic writes;
- Portable local cache (Windows/Linux/macOS) via Scratch.jl, configurable through
the
BRElections_CACHEenvironment variable orset_cache_dir!; - Cache revalidation: files the TSE republishes are downloaded again, and only then;
- TSE ↔ IBGE municipality code crosswalk (
municipalities); - Live vote counting on election night, straight from the TSE's results system
(
live_results), with a projection of the count (projection,live_projection), what is already mathematically decided (clinched) and a terminal dashboard (live_dashboard); - Discovery of published files by year (
available_files); - ZIP decompression with on-the-fly ISO-8859-1 → UTF-8 transcoding;
- Efficient import of large CSVs (CSV.jl, multithreaded, chunk-based reading);
- Automatic type conversion:
dd/mm/yyyydates →Date, sentinels#NULO#/#NE#→missing, identifier columns (NR_CPF_*,NR_TITULO_*) preserved asString(leading zeros intact); - Column name normalisation (lowercase, optional);
- Column and row filters applied during import to minimise memory usage;
- Provenance on every table (
sources) and ready references for the data and the package (cite, in ABNT, APA or BibTeX); - Automated test suite (offline by default; optional network tests).
pkg> add BRElectionsRequires Julia 1.10 or later. Start Julia with threads (julia -t auto): large
files are read in parallel, which for the biggest TSE files cuts the time by
a factor of 3 or more.
using BRElections
# Available datasets
available_datasets()
# What has the TSE already published for 2022?
available_files(2022)
# Candidates in 2022 (whole country)
cand = candidates(2022)
# Nominal votes in PE, 1st round, only the columns of interest.
# The filter is applied during reading (chunks) — only matching rows
# are kept in memory.
pe = candidate_votes(2022; uf = "PE",
columns = ["nr_turno", "nm_municipio", "nm_urna_candidato",
"sg_partido", "qt_votos_nominais"],
filter = row -> row.nr_turno == 1)
# Votes by electoral section (the TSE publishes one ZIP per state)
sec = section_votes(2022; uf = "PE")
# Generic interface equivalent to the above
df = elections(2020; type = :assets, uf = "PE")type |
TSE repository | Description | Since |
|---|---|---|---|
:candidates |
consulta_cand |
Registered candidates | 1998 |
:candidates_complementary |
consulta_cand_complementar |
Nationality, birthplace, re-election, spending cap… | 2014‡ |
:candidate_social_media |
rede_social_candidato |
Candidates' social media links | 2014‡ |
:cassation_reasons |
motivo_cassacao |
Reasons for revoked candidacies | 2012 |
:candidate_votes |
votacao_candidato_munzona |
Nominal votes by candidate/municipality/zone | 1998 |
:party_votes |
votacao_partido_munzona |
Votes by party/municipality/zone | 1998 |
:vote_details |
detalhe_votacao_munzona |
Vote count details by municipality/zone | 1998 |
:section_votes† |
votacao_secao |
Votes by electoral section | 1998 |
:section_vote_details |
detalhe_votacao_secao |
Vote count details by section | 1998 |
:assets |
bem_candidato |
Candidate asset declarations | 1998 |
:coalitions |
consulta_coligacao |
Coalitions and party legends | 1998 |
:vacancies |
consulta_vagas |
Number of seats in dispute | 1998 |
:voter_profile |
perfil_eleitorado |
Electorate profile | 1998 |
:voter_profile_section† |
perfil_eleitor_secao |
Electorate profile by electoral section | 2008 |
:polling_places |
eleitorado_locais_votacao |
Polling places: address, coordinates, voters per section | 2010 |
† Partitioned by state on the TSE CDN — the uf argument is mandatory. For
:section_votes, the presidential votes are in a separate national file,
uf = "BR".
‡ Not published for 2016.
Each dataset has a shortcut with the same name (candidates(2022),
cassation_reasons(2022)…). available_datasets() lists them all, with the
first year of each.
Office codes (cd_cargo) are available as OFFICES, so filters don't need
magic numbers:
dep = candidate_votes(2022; uf = "PE", filter = row -> row.cd_cargo == OFFICES.federal_deputy)polling_places lists every polling place, one row per section and round, with
address, CEP, latitude/longitude and number of voters. Coordinates come as
Float64 (the TSE writes them with a decimal point in some years and a comma in
others) and are missing where the TSE has none (it writes -1). Joined with
section_votes, it gives results by polling place, ready to map:
keys = [:nr_turno, :cd_municipio, :nr_zona, :nr_secao]
locs = polling_places(2022; uf = "PE",
columns = [keys; :nr_local_votacao; :nm_local_votacao; :nr_latitude; :nr_longitude])
sec = section_votes(2022; uf = "PE", columns = [keys; :ds_cargo; :nm_votavel; :qt_votos])
by_place = combine(groupby(innerjoin(sec, locs; on = keys),
[:nm_local_votacao, :nr_latitude, :nr_longitude, :nm_votavel]),
:qt_votos => sum => :votos)uf also takes several states, or :all:
ne = candidates(2022; uf = ["PE", "PB", "RN"]) # only those files are extracted
sec = section_votes(2022; uf = ["PE", "PB"]) # one ZIP per state, stackedFor the datasets partitioned by state, :all asks the TSE which ZIPs exist
for that year (the set changes: there is no DF in municipal elections, for
instance) and downloads all of them, which can be several GB, so combine it
with columns and filter.
Presidential votes by section are not in the state ZIPs. The TSE publishes
them in a national file, uf = "BR" (general elections only), which :all
includes:
pres_pe = section_votes(2022; uf = "BR", filter = row -> row.sg_uf == "PE")Pass a range or vector of years to stack them, with an ano column in front:
cand = candidates(2014:4:2022; uf = "PE", columns = [:ds_cargo, :sg_partido])
combine(groupby(cand, [:ano, :sg_partido]), nrow => :candidacies)Every year is validated before anything is downloaded. Columns that exist only
in some years (the TSE adds and drops fields over time) are missing in the
others; a column whose type differs between years (number in one, text in
another) becomes text; columns the TSE renamed are unified under the current
name (NM_EMAIL → DS_EMAIL).
Revenue and expenses declared by candidates and party bodies, from 2018 on (the files only have a standard layout since then):
rev = campaign_finance(2022; uf = "PE") # candidates' revenue
paid = campaign_finance(2022; table = :expenses_paid, uf = "PE")
prt = campaign_finance(2022; filer = :parties, table = :expenses_contracted, uf = "PE")table is :revenue, :revenue_original_donor, :expenses_contracted or
:expenses_paid; filer is :candidates or :parties. Pass uf: the national
files are huge (the 2024 candidates ZIP alone is 1.3 GB). The four tables of a
filer come from the same ZIP, downloaded once. They are also available through
elections as :candidate_revenue, :party_expenses_paid and so on.
Money columns (vr_*) are returned as Float64, whether the TSE file uses a
decimal comma or a decimal point.
TSE files identify municipalities by the court's own code (cd_municipio), not
the IBGE one, so they can't be joined with Census, municipal GDP and other IBGE
data directly. municipalities() returns the crosswalk, taken from the TSE's
results system for the latest general election: every municipality, including
Brasília and Fernando de Noronha, plus the cities abroad where Brazilians vote
(sg_uf = "ZZ", no IBGE code).
mun = municipalities() # sg_uf, cd_municipio, cd_municipio_ibge,
# nm_municipio, capital, zonas
votes = candidate_votes(2022; uf = "PE")
votes = leftjoin(votes, select(mun, :cd_municipio, :cd_municipio_ibge);
on = :cd_municipio)The open-data files above are only published days after an election. On
election night, live_results reads the TSE's results system
(resultados.tse.jus.br, the source of its website and "Resultados" app), which
is updated every few minutes while votes are counted. Nothing goes to the disk
cache; the last version is kept in memory and revalidated (ETag) on every call,
so polling is cheap. After the count, it keeps working for recent elections, by
municipality too.
pres = live_results(:president) # Brazil
metadata(pres, "pc_secoes_totalizadas") # % of polling stations counted
live_results(:governor; uf = "PE")
live_results(:president; uf = "SP", municipality = "São Paulo")
live_results(:mayor; uf = "PE", municipality = 2611606) # IBGE code works tooOffices: :president, :governor, :senator, :federal_deputy,
:state_deputy, :district_deputy, :mayor, :councillor. The election is
picked automatically (the latest one already held that has the office and
covers the place, so the runoff is used once it happens); pass election to
choose one. The result has one row per candidate, sorted by votes; the count
summary (polling stations counted, turnout, valid/blank/null votes, update
time) is in metadata(df). examples/live_results.jl shows it as a table
that refreshes itself:
julia --project=. examples/live_results.jl presidente --watch 60clinched(df) says, for each candidate, what the arithmetic already
guarantees in the worst case (every voter still uncounted turns out and votes
against them): :elected, :runoff (at least goes to the runoff) or :open.
live_projection (or projection on data you already have) simulates the
votes still to be counted and returns, per candidate, the projected share, an
80% range, the chance of winning (outright, when a runoff is possible) and of
reaching the runoff:
live_projection() # president
live_projection(:governor; uf = "PE")The count does not advance evenly: states finish at different times (the
Northeast usually later), and the uncounted electorate does not vote like the
counted one. For the presidential race the projection is done by state:
each state's remaining votes follow that state's profile, weighted by how many
voters are still uncounted there. In a runoff, a state that has counted
little starts from its own first-round result, shifted by the swing already
seen in the states that counted more (the transfer of the eliminated
candidates' votes). The parameters (BRElections.PROJECTION_PARAMS) were
calibrated on counts rebuilt from the real 2022 results by electoral zone
(dev/calibrate_projection.jl): real zones counted in different orders
(capitals first, last, at random; the Northeast late or not). There, the 80%
range holds the final result 81–96% of the time at every stage; in the runoff,
using each state's first round, the projected share is off by 0.9 points with
under 30% counted and 0.1 above 80%, and the actual winner is favoured from
the start — extrapolating the national total is off by 4 points early on and
favours the loser until 80% is counted. It is a simple, transparent model
with no polls: it shows where the count points, not what will happen.
For an office contested across a state (governor, senator, or president within
a state), the projection is done by municipality in the same way: the 60
largest municipalities (BRElections.MAX_MUNICIPAL_STRATA) each start from
their own first round, and the rest of the state is one more block. In the 12
state runoffs of 2022 (dev/calibrate_governor.jl) this cut the error from 4.6
to 2.8 points with up to 25% counted (2.7 to 1.6 overall) and picked the winner
85% of the time early on instead of 77%; it still struggles where the vote
transfer was very uneven (MS and SE in 2022, where the first-round leader lost
the runoff). The first call for a state downloads each municipality's first
round once (a few seconds; final files).
live_dashboard (needs Tachikoma.jl,
loaded with using Tachikoma) puts all of this in a terminal dashboard with two
screens, switched with Tab: the count (candidates with votes, bars,
projection, range, win and runoff chances, clinched marks, turnout, regions
with how much of the remaining electorate is there, the lead over time) and the
analysis (chance bars, the distribution of simulated outcomes against the
deciding cut — 50% or the last seat —, the share of the remaining votes each
candidate needs to overtake or win outright, the leader's chance over time, and
the states ranked by the weight of what is left to count).
The TSE does not publish votes one by one — each voting machine sends the whole section at once, and the aggregate is republished as reports arrive, with up to about a minute of CDN caching. The dashboard polls every few seconds (a 304 costs nothing), and when a new version arrives the counters roll to the new numbers like an odometer, never past the last published figure. The header shows the pace of the count (votes and sections per minute) and the estimated finish time.
using BRElections, Tachikoma
live_dashboard() # president, Brazil
live_dashboard(:mayor; uf = "PE", municipality = "Recife")
live_dashboard(demo = true) # simulated count, ~3 minutesdemo = true replays the latest presidential count from the real final
results by state, compressed into about three minutes (the Northeast starting
later, early returns skewed), to see the dashboard outside election day; the
intermediate numbers are simulated and the title says so. The example script
sets up Tachikoma in a temporary environment if you don't have it:
julia -t auto examples/live_dashboard.jl --demo
julia -t auto examples/live_dashboard.jl governador spcache_dir() # where ZIPs and CSVs are stored
set_cache_dir!(dir) # change cache directory at runtime
cache_info() # what is cached: one row per ZIP, with sizes and last check
clear_cache!() # wipe all cached data
clear_cache!(:candidate_votes; year = 2018) # one dataset (and year)
clear_cache!(:section_votes; extracted_only = true) # keep the ZIPs, drop the CSVsThe extracted CSVs usually take several times the size of their ZIP and are
rebuilt from it without a new download, so extracted_only = true is a cheap
way to free space.
The BRElections_CACHE environment variable sets the directory at package load
time.
The TSE regenerates its files often — including those of past elections —
without changing their URLs. So, when a ZIP is already cached, each call makes
a HEAD request and downloads it again only if the published file changed
(by ETag, Last-Modified and Content-Length). Without network access, the
cached copy is used. The check runs at most once an hour per file (set
BRElections_REVALIDATE_HOURS to change it; 0 checks on every call). Pass
check_updates = false to skip the check and keep working with the version you
already have:
df = candidates(2022; check_updates = false)pkg> test BRElections # offline suite (synthetic fixtures)BRElections_TEST_NETWORK=true julia --project -e 'using Pkg; Pkg.test()' # includes smoke tests against the TSE CDN- Covers elections from 1998 onward, in the current CDN format (files with headers). Very old years may have divergent schemas.
- Campaign finance covers 2018 onward. Earlier years exist on the TSE CDN, but each election has its own file names, folders and columns.
- Official variable dictionaries come with each ZIP (
leiame.pdf) and remain in the cache for reference.
If BRElections.jl was part of your analysis pipeline, cite two things separately: the software and the data. They are distinct objects with distinct responsibilities — the package answers for downloading, decoding and typing, the TSE answers for the content.
The repository ships a CITATION.cff, which GitHub reads
natively: the "Cite this repository" button in the sidebar generates ready
APA and BibTeX. A CITATION.bib is also provided:
@software{bertuzzi_brelections_2026,
author = {Bertuzzi, Dante},
title = {{BRElections.jl}: a {Julia} interface to {Brazilian} electoral
open data ({TSE})},
year = {2026},
version = {0.4.1},
doi = {10.5281/zenodo.22182707},
url = {https://github.com/dantebertuzzi/BRElections.jl},
note = {Julia package}
}Cite the version you used, not "the latest". The import layer is part of
the result: which columns are kept as String, which sentinels become
missing and how a schema change on the TSE side is absorbed can differ
between releases. Run pkg> status BRElections and use the number it prints.
The TSE is the primary source and must be cited as such, with the download date — the open-data files are regenerated as results are totalled and candidacies are judged, so the same query run on different dates can return different numbers:
BRASIL. Tribunal Superior Eleitoral. Repositório de dados eleitorais: dados abertos. Brasília: TSE, 2026. Available at: https://cdn.tse.jus.br/estatistica/sead/odsele/. Accessed: 31 Aug. 2026.
You don't need to assemble this by hand: every table returned by the package
carries its provenance (sources), and cite writes the references — one per
TSE file, with the published version and access date, plus one for the package
version that imported it:
cand = candidates(2022; uf = "PE")
sources(cand) # URL, TSE version (Last-Modified/ETag), download date, filters
print(cite(cand)) # ABNT; also style = :apa or :bibtexState the year and the dataset you used (candidates, candidate_votes,
section_votes, …), since each is a separate published file with its own
layout. Variable meanings come from the leiame.pdf shipped inside each ZIP,
which stays in the cache for reference.
So that someone else reaches your number, record in the paper or supplementary
material: the BRElections.jl and Julia versions; the Project.toml and
Manifest.toml of the environment (the Manifest.toml pins the whole
dependency tree and is what makes the environment reconstructible with
Pkg.instantiate()); the download date of the TSE files (and whether you
worked from an older cache — cache_dir shows where it lives); and the year,
dataset and any filter/columns you applied during import, since rows and
columns dropped at read time never reach the table you analysed.
| Standard | What it establishes |
|---|---|
| FORCE11 — Software Citation Principles | Software is a citable research product. Six principles: importance, credit, unique identification, persistence, accessibility and specificity (cite the exact version). |
| Citation File Format (CFF) 1.2.0 | Machine-readable citation metadata. What GitHub and Zenodo consume. |
| ABNT NBR 6023:2018 | References in Brazilian publications; requires Disponível em + Acesso em for electronic documents. |
| Zenodo + GitHub | Mints a persistent DOI per release, plus a concept DOI always pointing at the newest version. |
The DOIs of this project: the repository is connected to Zenodo, so every release is archived and gets a persistent identifier — the citation no longer depends on the GitHub URL surviving a rename or a transfer. Two DOIs coexist, and they are not interchangeable:
| DOI | What it identifies |
|---|---|
| 10.5281/zenodo.22182707 | Concept DOI — the project as a whole. Always resolves to the newest version; it is what the badge at the top of this README points at. |
| one per release | Each archived version gets its own — 0.1.1 is 10.5281/zenodo.22182708. All of them are listed on the Zenodo page. |
The BibTeX above carries the concept DOI, so it keeps working across releases. In a paper, swap it for the DOI of the version you used: the concept DOI says which project you used, the version DOI says which code actually ran.
MIT. The data belongs to the TSE and is publicly available.
