Pular para conteúdo

IPCA Data

indexes(start, end)

Retrieves the IPCA index values for a specified date range.

Makes an API call to the IBGE's data portal using the format: https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/YYYYMM-YYYYMM/variaveis/2266?localidades=N1[all]

Example: For the date range "01-01-2024" to "31-03-2024", the API URL will be: https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/202401-202403/variaveis/2266?localidades=N1[all]

Parameters:

Name Type Description Default
start DateScalar

The start date of the date range

required
end DateScalar

The end date of the date range

required

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns 'Period' and 'Value'

Examples:

>>> from pyield import ipca
>>> # Get the IPCA indexes for the first quarter of 2025
>>> ipca.indexes(start="01-01-2025", end="01-03-2025")
shape: (3, 2)
┌────────┬─────────┐
│ Period ┆ Value   │
│ ---    ┆ ---     │
│ i64    ┆ f64     │
╞════════╪═════════╡
│ 202501 ┆ 7111.86 │
│ 202502 ┆ 7205.03 │
│ 202503 ┆ 7245.38 │
└────────┴─────────┘
Source code in pyield/ipca/historical.py
def indexes(start: DateScalar, end: DateScalar) -> pl.DataFrame:
    """
    Retrieves the IPCA index values for a specified date range.

    Makes an API call to the IBGE's data portal using the format:
    https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/YYYYMM-YYYYMM/variaveis/2266?localidades=N1[all]

    Example: For the date range "01-01-2024" to "31-03-2024", the API URL will be:
    https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/202401-202403/variaveis/2266?localidades=N1[all]

    Args:
        start (DateScalar): The start date of the date range
        end (DateScalar): The end date of the date range

    Returns:
        pl.DataFrame: DataFrame with columns 'Period' and 'Value'

    Examples:
        >>> from pyield import ipca
        >>> # Get the IPCA indexes for the first quarter of 2025
        >>> ipca.indexes(start="01-01-2025", end="01-03-2025")
        shape: (3, 2)
        ┌────────┬─────────┐
        │ Period ┆ Value   │
        │ ---    ┆ ---     │
        │ i64    ┆ f64     │
        ╞════════╪═════════╡
        │ 202501 ┆ 7111.86 │
        │ 202502 ┆ 7205.03 │
        │ 202503 ┆ 7245.38 │
        └────────┴─────────┘
    """
    if has_null_args(start, end):
        return pl.DataFrame()
    start = convert_dates(start)
    end = convert_dates(end)

    start_date = start.strftime("%Y%m")
    end_date = end.strftime("%Y%m")
    api_url = f"{IPCA_URL}{start_date}-{end_date}/variaveis/2266?localidades=N1[all]"
    data_dict = _fetch_api_data(api_url)

    return _process_ipca_dataframe(data_dict)

last_indexes(num_months=1)

Retrieves the last IPCA index values for a specified number of months.

Makes an API call to the IBGE's data portal using the format: https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/-N/variaveis/2266?localidades=N1[all]

Example: For the last 2 months, the API URL will be: https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/-2/variaveis/2266?localidades=N1[all]

Parameters:

Name Type Description Default
num_months int

Number of months to retrieve. Defaults to 1.

1

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns 'Period' and 'Value'

Examples:

>>> from pyield import ipca
>>> # Get the last month's IPCA index
>>> df = ipca.last_indexes(1)
>>> # Get the last 3 months' IPCA indexes
>>> df = ipca.last_indexes(3)
Source code in pyield/ipca/historical.py
def last_indexes(num_months: int = 1) -> pl.DataFrame:
    """
    Retrieves the last IPCA index values for a specified number of months.

    Makes an API call to the IBGE's data portal using the format:
    https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/-N/variaveis/2266?localidades=N1[all]

    Example: For the last 2 months, the API URL will be:
    https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/-2/variaveis/2266?localidades=N1[all]

    Args:
        num_months (int, optional): Number of months to retrieve. Defaults to 1.

    Returns:
        pl.DataFrame: DataFrame with columns 'Period' and 'Value'

    Examples:
        >>> from pyield import ipca
        >>> # Get the last month's IPCA index
        >>> df = ipca.last_indexes(1)
        >>> # Get the last 3 months' IPCA indexes
        >>> df = ipca.last_indexes(3)
    """
    num_months = abs(num_months)
    if num_months == 0:
        return pl.DataFrame()

    api_url = f"{IPCA_URL}-{num_months}/variaveis/2266?localidades=N1[all]"
    data_dict = _fetch_api_data(api_url)

    return _process_ipca_dataframe(data_dict)

last_rates(num_months=1)

Retrieves the last IPCA monthly rates for a specified number of months.

Makes an API call to the IBGE's data portal using the format: https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/-N/variaveis/63?localidades=N1[all]

Example: For the last 2 months, the API URL will be: https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/-2/variaveis/63?localidades=N1[all]

Parameters:

Name Type Description Default
num_months int

Number of months to retrieve. Defaults to 1.

1

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns 'Period' and 'Value'

Raises:

Type Description
ValueError

If num_months is 0

Examples:

>>> from pyield import ipca
>>> # Get the last month's IPCA rate
>>> df = ipca.last_rates(1)
>>> # Get the last 3 months' IPCA rates
>>> df = ipca.last_rates(3)
Source code in pyield/ipca/historical.py
def last_rates(num_months: int = 1) -> pl.DataFrame:
    """
    Retrieves the last IPCA monthly rates for a specified number of months.

    Makes an API call to the IBGE's data portal using the format:
    https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/-N/variaveis/63?localidades=N1[all]

    Example: For the last 2 months, the API URL will be:
    https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/-2/variaveis/63?localidades=N1[all]

    Args:
        num_months (int, optional): Number of months to retrieve. Defaults to 1.

    Returns:
        pl.DataFrame: DataFrame with columns 'Period' and 'Value'

    Raises:
        ValueError: If num_months is 0

    Examples:
        >>> from pyield import ipca
        >>> # Get the last month's IPCA rate
        >>> df = ipca.last_rates(1)
        >>> # Get the last 3 months' IPCA rates
        >>> df = ipca.last_rates(3)
    """
    num_months = abs(num_months)
    if num_months == 0:
        raise ValueError("The number of months must be greater than 0.")

    api_url = f"{IPCA_URL}-{num_months}/variaveis/63?localidades=N1[all]"
    data_dict = _fetch_api_data(api_url)

    return _process_ipca_dataframe(data_dict, is_in_pct=True)

projected_rate()

Retrieves the current IPCA projection from the ANBIMA website.

This function makes an HTTP request to the ANBIMA website, extracts HTML tables containing economic indicators, and specifically processes the IPCA projection data.

Process
  1. Accesses the ANBIMA indicators webpage
  2. Extracts the third table that contains the IPCA projection
  3. Locates the row labeled as "IPCA1"
  4. Extracts the projection value and converts it to decimal format
  5. Extracts and formats the reference month of the projection
  6. Extracts the date and time of the last update

Returns:

Name Type Description
IndicatorProjection IndicatorProjection

An object containing: - last_updated (dt.datetime): Date and time of the last data update - reference_period (str): Reference period of the projection as a string in "MMM/YY" brazilian format (e.g., "set/25") - projected_value (float): Projected IPCA value as a decimal number

Raises:

Type Description
RequestException

If there are connection issues with the ANBIMA site

ValueError

If the expected data is not found in the page structure

Example

from pyield import ipca

Retrieve the current IPCA projection from ANBIMA

ipca.projected_rate() IndicatorProjection(last_updated=..., reference_period=..., projected_value=...)

Notes
  • The function requires internet connection to access the ANBIMA website
  • The structure of the ANBIMA page may change, which could affect the function
Source code in pyield/ipca/projected.py
def projected_rate() -> IndicatorProjection:
    """
    Retrieves the current IPCA projection from the ANBIMA website.

    This function makes an HTTP request to the ANBIMA website, extracts HTML tables
    containing economic indicators, and specifically processes the IPCA projection data.

    Process:
        1. Accesses the ANBIMA indicators webpage
        2. Extracts the third table that contains the IPCA projection
        3. Locates the row labeled as "IPCA1"
        4. Extracts the projection value and converts it to decimal format
        5. Extracts and formats the reference month of the projection
        6. Extracts the date and time of the last update

    Returns:
        IndicatorProjection: An object containing:
            - last_updated (dt.datetime): Date and time of the last data update
            - reference_period (str): Reference period of the projection as a string in
              "MMM/YY" brazilian format (e.g., "set/25")
            - projected_value (float): Projected IPCA value as a decimal number

    Raises:
        requests.RequestException: If there are connection issues with the ANBIMA site
        ValueError: If the expected data is not found in the page structure

    Example:
        >>> from pyield import ipca
        >>> # Retrieve the current IPCA projection from ANBIMA
        >>> ipca.projected_rate()
        IndicatorProjection(last_updated=..., reference_period=..., projected_value=...)

    Notes:
        - The function requires internet connection to access the ANBIMA website
        - The structure of the ANBIMA page may change, which could affect the function
    """
    page_text = _get_page_text()
    df = _read_ipca_table(page_text)

    last_update_str = df.iat[0, 0].split("Atualização:")[-1].strip()
    last_update = dt.datetime.strptime(last_update_str, "%d/%m/%Y - %H:%M h")

    ipca_row = df.loc[df[0] == "IPCA1"]
    ipca_value = ipca_row.iloc[0, 2]
    ipca_value = float(ipca_value) / 100
    ipca_value = round(ipca_value, 4)

    # Extract and format the reference month
    ipca_date = ipca_row.iloc[0, 1]
    ipca_date = str(ipca_date)
    ipca_date = ipca_date.split("(")[-1].split(")")[0]

    return IndicatorProjection(
        last_updated=last_update,
        reference_period=ipca_date,
        projected_value=ipca_value,
    )

rates(start, end)

Retrieves the IPCA monthly rates for a specified date range.

Makes an API call to the IBGE's data portal using the format: https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/YYYYMM-YYYYMM/variaveis/63?localidades=N1[all]

Example: For the date range "01-01-2024" to "31-03-2024", the API URL will be: https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/202401-202403/variaveis/63?localidades=N1[all]

Parameters:

Name Type Description Default
start DateScalar

The start date of the date range

required
end DateScalar

The end date of the date range

required

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns 'Period' and 'Rate'

Examples:

>>> from pyield import ipca
>>> # Get the IPCA rates for the first quarter of 2025
>>> ipca.rates("01-01-2025", "01-03-2025")
shape: (3, 2)
┌────────┬────────┐
│ Period ┆ Value  │
│ ---    ┆ ---    │
│ i64    ┆ f64    │
╞════════╪════════╡
│ 202501 ┆ 0.0016 │
│ 202502 ┆ 0.0131 │
│ 202503 ┆ 0.0056 │
└────────┴────────┘
Source code in pyield/ipca/historical.py
def rates(start: DateScalar, end: DateScalar) -> pl.DataFrame:
    """
    Retrieves the IPCA monthly rates for a specified date range.

    Makes an API call to the IBGE's data portal using the format:
    https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/YYYYMM-YYYYMM/variaveis/63?localidades=N1[all]

    Example: For the date range "01-01-2024" to "31-03-2024", the API URL will be:
    https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/202401-202403/variaveis/63?localidades=N1[all]

    Args:
        start (DateScalar): The start date of the date range
        end (DateScalar): The end date of the date range

    Returns:
        pl.DataFrame: DataFrame with columns 'Period' and 'Rate'

    Examples:
        >>> from pyield import ipca
        >>> # Get the IPCA rates for the first quarter of 2025
        >>> ipca.rates("01-01-2025", "01-03-2025")
        shape: (3, 2)
        ┌────────┬────────┐
        │ Period ┆ Value  │
        │ ---    ┆ ---    │
        │ i64    ┆ f64    │
        ╞════════╪════════╡
        │ 202501 ┆ 0.0016 │
        │ 202502 ┆ 0.0131 │
        │ 202503 ┆ 0.0056 │
        └────────┴────────┘
    """
    if has_null_args(start, end):
        return pl.DataFrame()
    start = convert_dates(start)
    end = convert_dates(end)

    start_date = start.strftime("%Y%m")
    end_date = end.strftime("%Y%m")
    api_url = f"{IPCA_URL}{start_date}-{end_date}/variaveis/63?localidades=N1[all]"
    data_dict = _fetch_api_data(api_url)

    return _process_ipca_dataframe(data_dict, is_in_pct=True)