Certainly! Below is a Python code that fetches the historical USDBRL (USD to Brazilian Real) exchange rates from the web and fits an exponential model to the data. The code uses the yfinance library to retrieve the exchange rate data and scipy for fitting the exponential model.
python
# Import necessary libraries
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Step 1: Fetch historical USDBRL exchange rate data
symbol = 'BRL=X' # Yahoo Finance ticker symbol for USD/BRL exchange rate
data = yf.download(symbol, period='1y') # Download data for the past 1 year
# Check if data is fetched successfully
if data.empty:
raise ValueError("No data fetched. Please check the ticker symbol or your internet connection.")
# Step 2: Prepare the data for fitting
dates = data.index
times = np.arange(len(dates)) # Numeric time variable for fitting
rates = data['Close'].values # Closing exchange rates
# Step 3: Define the exponential model function
def exponential_model(x, a, b, c):
return a * np.exp(b * x) + c
# Initial guess for the parameters [a, b, c]
initial_guess = [rates[0], 0, 0]
# Step 4: Fit the exponential model to the data
try:
popt, pcov = curve_fit(exponential_model, times, rates, p0=initial_guess)
except RuntimeError:
raise RuntimeError("Optimal parameters not found: Number of calls to function has reached maxfev.")
# Extract the optimal parameters
a_opt, b_opt, c_opt = popt
print(f"Optimal parameters:\na = {a_opt}\nb = {b_opt}\nc = {c_opt}")
# Step 5: Plot the original data and the fitted model
plt.figure(figsize=(12, 6))
plt.plot(dates, rates, 'b.', label='Actual Exchange Rate')
plt.plot(dates, exponential_model(times, *popt), 'r-', label='Fitted Exponential Model')
plt.xlabel('Date')
plt.ylabel('Exchange Rate (BRL per USD)')
plt.title('USDBRL Exchange Rate and Exponential Fit')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
Explanation:
Imports:
yfinance is used to download financial data from Yahoo Finance.
numpy for numerical operations.
matplotlib.pyplot for plotting the data.
scipy.optimize.curve_fit for fitting the exponential model to the data.
Fetching Data:
The symbol 'BRL=X' corresponds to the USD to BRL exchange rate on Yahoo Finance.
The download function fetches the historical data for the specified period ('1y' for one year).
Preparing Data:
dates holds the date indices of the fetched data.
times is a numeric array corresponding to each time point (required for fitting).
rates contains the closing exchange rates.
Defining the Model:
The exponential_model function represents the exponential equation ( y = a \cdot e^{b x} + c ).
curve_fit will estimate the parameters a, b, and c to fit the model to the data.
Fitting the Model:
An initial guess is provided to help the fitting algorithm converge.
curve_fit returns the optimal parameters (popt) and the covariance of the parameters (pcov).
Plotting:
The actual exchange rates are plotted as blue dots.
The fitted exponential model is plotted as a red line.
The plot includes labels, a title, a legend, and a grid for better readability.
Notes:
Ensure that you have the required libraries installed. If not, you can install them using:
bash
pip install yfinance numpy matplotlib scipy
The exponential model may not be the best fit for exchange rate data, as currency exchange rates are influenced by numerous factors and may not follow an exponential trend. However, this code demonstrates how to fit such a model to the data.
The curve_fit function may raise a RuntimeError if it fails to converge; in such cases, you may need to adjust the initial guesses or investigate the data for anomalies.
Always verify the fitted model against the data to ensure it makes sense analytically and contextually.
Disclaimer:
The exchange rate data fetched is for demonstration purposes.
Exercise caution when using financial data for investment decisions.