How to calculate the annual inflation in Brazil using javascript

Written in May 13, 2021 - 🕒 2 min. read

Today I needed to know the accumulated inflation of the last year for Brazil for a project I am working on, information that can be easily accessed on the IBGE website, however I needed this data in JSON or at least XML format.


Incredibly, just searching for ”API accumulated inflation 2021 brazil” did not return any useful results . I even tried ”how to calculate the accumulated inflation “javascript”” and nothing, which is why I’m writing this post.

The Central Bank of Brazil provides several end-points with data related to the Brazilian economy, but for a person who does not understand economics like myself, it is difficult to know which is the correct endpoint to get the correct data.

The Central Bank of Brazil has end-points in the format, in which XXX is the data reference code. First I found this end-point, which seemed to be correct, but the value of April 2021 is 0.05 and on the IBGE website the value is 0.31, that is not what I need.

After trying a few different codes that I found searching on Google, I found this end-point, in which the April 2021 value is 0.31. Yay!

It is possible to filter the results of this end-point using, which returns the values of last 12 months.

Now we can use this data to calculate the accumulated inflation for the last year:

const fetchBacenData = async () => {
    const url = '';
    const result = await fetch(url, {
        method: 'GET',
    }).then(async (response) => await response.text());

    return JSON.parse(result);

const data = await fetchBacenData();

To calculate the annual inflation we use the following formula: acummulated inflation = ((1 + previous montly inflation) * (1 + current montly inflation)) - 1 (provided by my great mathematician friend Leandro). And how do we accumulate data using javascript? By using reduce:

const inflation =
    data.reduce((acc, curr) => ((1 + parseFloat(acc)) * (1 + parseFloat(curr.valor) / 100)) - 1, 0);

This will give us 0.06759188526903293, which by rounding we get to the amount of 6,76%, just like it is in the IBGE website. Noice!

I hope the next person who Googles “API accumulated inflation 2021 brazil” find this post 😊

That’s all for today, cheers!


Post a comment


No comments yet.