Certainly! Below is a Python script that will load historical USDBRL exchange rate data, fit an exponential model to it, and plot both the original data and the fitted model. This script uses the pandas, numpy, matplotlib, and scipy libraries.
Step 1: Import Necessary Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
Step 2: Load the Data
Assuming you have historical USDBRL exchange rate data in a CSV file named usd_brl.csv with two columns: Date and ExchangeRate. Here's how you can load it:
# Load the data
data = pd.read_csv('usd_brl.csv')
# Convert 'Date' column to datetime objects
data['Date'] = pd.to_datetime(data['Date'])
# Sort the data by date
data = data.sort_values('Date')
# Reset the index
data = data.reset_index(drop=True)
Note: If you don't have the data, you can download historical exchange rate data from reliable financial data sources and save it as usd_brl.csv.
Sample of usd_brl.csv file:
Date,ExchangeRate
2020-01-01,4.02
2020-02-01,4.28
2020-03-01,4.48
...
Step 3: Prepare the Data for Modeling
We need to convert the dates to a numerical format (e.g., the number of days since the first date):
# Calculate the number of days since the first date
data['Days'] = (data['Date'] - data['Date'].iloc[0]).dt.days
# Extract X and Y values for modeling
X = data['Days'].values
Y = data['ExchangeRate'].values
Step 4: Define the Exponential Model Function
We'll define an exponential function to fit. A common exponential growth/decay model is:
[ y = a \cdot e^{b \cdot x} ]
def exponential_model(x, a, b):
return a * np.exp(b * x)
Step 5: Perform the Curve Fitting
Use curve_fit from scipy.optimize to fit the model to the data:
# Initial guess for the parameters a and b
initial_guess = [Y[0], 0.0001]
# Fit the exponential model to the data
params, covariance = curve_fit(exponential_model, X, Y, p0=initial_guess)
# Extract the fitted parameters
a_fitted, b_fitted = params
print(f"Fitted parameters: a = {a_fitted}, b = {b_fitted}")
Step 6: Use the Fitted Model to Make Predictions
# Generate Y values based on the fitted model
Y_fitted = exponential_model(X, a_fitted, b_fitted)
Step 7: Plot the Original Data and the Fitted Model
plt.figure(figsize=(12, 6))
plt.scatter(data['Date'], Y, label='Original Data', color='blue')
plt.plot(data['Date'], Y_fitted, label='Exponential Fit', color='red')
plt.xlabel('Date')
plt.ylabel('USDBRL Exchange Rate')
plt.title('USDBRL Exchange Rate and Exponential Fit')
plt.legend()
plt.show()
Complete Script
Putting it all together, here's the complete script:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Load the data
data = pd.read_csv('usd_brl.csv')
data['Date'] = pd.to_datetime(data['Date'])
data = data.sort_values('Date').reset_index(drop=True)
# Calculate the number of days since the first date
data['Days'] = (data['Date'] - data['Date'].iloc[0]).dt.days
# Extract X and Y values for modeling
X = data['Days'].values
Y = data['ExchangeRate'].values
# Define the exponential model function
def exponential_model(x, a, b):
return a * np.exp(b * x)
# Initial guess for the parameters a and b
initial_guess = [Y[0], 0.0001]
# Fit the exponential model to the data
params, covariance = curve_fit(exponential_model, X, Y, p0=initial_guess)
a_fitted, b_fitted = params
print(f"Fitted parameters: a = {a_fitted}, b = {b_fitted}")
# Generate Y values based on the fitted model
Y_fitted = exponential_model(X, a_fitted, b_fitted)
# Plot the original data and the fitted model
plt.figure(figsize=(12, 6))
plt.scatter(data['Date'], Y, label='Original Data', color='blue')
plt.plot(data['Date'], Y_fitted, label='Exponential Fit', color='red')
plt.xlabel('Date')
plt.ylabel('USDBRL Exchange Rate')
plt.title('USDBRL Exchange Rate and Exponential Fit')
plt.legend()
plt.show()
Explanation:
- The
curve_fit function estimates the parameters a and b that best fit the exponential model to your data.
- The initial guess (
initial_guess) helps the optimization algorithm start at a reasonable point.
- After fitting, we print the fitted parameters and plot the original data along with the fitted exponential curve.
Considerations:
- Data Quality: Ensure your data covers a period where an exponential model is appropriate. Exchange rates are influenced by numerous factors and may not always follow an exponential trend.
- Time Units: The time variable (
Days) is calculated in days since the first date. Depending on your dataset, you might prefer to use months or years.
- Model Selection: If the exponential model does not fit well, consider other models (linear, logarithmic, etc.) or more complex time-series forecasting methods.
Example Output:
After running the script, you'll see a plot displaying the original exchange rate data as blue dots and the exponential fit as a red line:
[image: USDBRL Exponential Fit]
Dependencies:
Make sure you have the necessary Python packages installed:
pip install pandas numpy matplotlib scipy
Final Notes:
- Always visualize your data and the fitted model to assess the quality of the fit.
- Use statistical metrics (like R-squared) to quantify the goodness of fit.
- Be cautious when extrapolating the model into the future, as exchange rates can be highly unpredictable.