To simulate the Cox-Ingersoll-Ross (CIR) interest rate model for the SELIC rate and scrape the current SELIC rate in Python, you can follow the steps below. The CIR model is used to model the evolution of interest rates over time and is given by the stochastic differential equation:
[ dr_t = a(b - r_t)dt + \sigma \sqrt{r_t} dW_t ]
Where:
( r_t ) is the interest rate at time ( t )
( a ) is the speed of mean reversion
( b ) is the long-term mean interest rate level
( \sigma ) is the volatility parameter
( dW_t ) is the Wiener process increment
Here's the complete Python code:
python
import requests
import numpy as np
import matplotlib.pyplot as plt
def get_current_selic_rate():
# URL to get the latest SELIC rate from Banco Central do Brasil API
url = 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.432/dados/ultimos/1?formato=json'
response = requests.get(url)
data = response.json()
# Extract the SELIC rate and convert to float
selic_rate = float(data[0]['valor'].replace(',', '.'))
return selic_rate
def simulate_CIR(r0, a, b, sigma, T, N):
dt = T / N # Time step
rates = np.zeros(N+1)
times = np.linspace(0, T, N+1)
rates[0] = r0
for t in range(1, N+1):
r_t = rates[t-1]
sqrt_rt = np.sqrt(max(r_t, 0))
# Generate a random shock from normal distribution
epsilon = np.random.normal(0, 1)
dr = a * (b - max(r_t, 0)) * dt + sigma * sqrt_rt * epsilon * np.sqrt(dt)
rates[t] = r_t + dr
rates[t] = max(rates[t], 0) # Ensure the rate stays non-negative
return times, rates
def main():
# Get the current SELIC rate
current_selic_rate = get_current_selic_rate()
print(f"Current SELIC rate: {current_selic_rate}%")
# Parameters for the CIR model
r0 = current_selic_rate # Initial rate
a = 0.1 # Speed of mean reversion
b = 8.0 # Long-term mean rate (%)
sigma = 0.02 # Volatility parameter
T = 1.0 # Time horizon in years
N = 252 # Number of time steps (e.g., trading days in a year)
# Simulate the CIR model
times, rates = simulate_CIR(r0, a, b, sigma, T, N)
# Plot the simulated SELIC rates over time
plt.figure(figsize=(10, 6))
plt.plot(times, rates, label='Simulated SELIC Rate')
plt.xlabel('Time (years)')
plt.ylabel('Interest Rate (%)')
plt.title('CIR Model Simulation of SELIC Rate')
plt.legend()
plt.grid(True)
plt.show()
if __name__ == '__main__':
main()
Explanation:
Scraping the Current SELIC Rate:
We use the Banco Central do Brasil API to get the latest SELIC rate.
The API endpoint https://api.bcb.gov.br/dados/serie/bcdata.sgs.432/dados/ultimos/1?formato=json returns the most recent SELIC rate in JSON format.
The get_current_selic_rate function retrieves this data and parses the SELIC rate.
Simulating the CIR Model:
The simulate_CIR function simulates the interest rate path using the CIR model.
It initializes the rate array with the current SELIC rate.
For each time step, it calculates the change in the rate (dr) using the CIR formula.
It ensures that the rates remain non-negative by taking the maximum of the rate and zero.
The simulation uses the Euler-Maruyama method for discretization.
Plotting the Results:
After simulation, we plot the time series of the simulated SELIC rates.
The plot provides a visual representation of how the SELIC rate might evolve over the next year according to the CIR model.
Note:
The parameters a, b, and sigma are set to example values. You may adjust them based on more accurate estimates or historical data.
The volatility sigma is set to a low value to reflect typical interest rate volatilities.
The long-term mean rate b is set to 8.0% as an example. Adjust this value based on your expectations of the long-term SELIC rate.
Dependencies:
Make sure you have the required libraries installed:
code
pip install requests numpy matplotlib
Running the Code:
Save the code to a file named, for example, cir_selic_simulation.py.
Run the script using the command:
code
python cir_selic_simulation.py
This will display the current SELIC rate and show a plot of the simulated interest rate over the next year.