0% found this document useful (0 votes)
13 views2 pages

SARIMA Model For Forecasting Currency Exchange Ra 2

This document discusses using a SARIMA model to forecast currency exchange rates between the Indian rupee and US dollar. It covers collecting historical exchange rate data, examining it for trends and seasonality, building a SARIMA model to identify patterns in the data, making predictions of future exchange rates using the model, and evaluating the model's performance.

Uploaded by

9hgxjfsctp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

SARIMA Model For Forecasting Currency Exchange Ra 2

This document discusses using a SARIMA model to forecast currency exchange rates between the Indian rupee and US dollar. It covers collecting historical exchange rate data, examining it for trends and seasonality, building a SARIMA model to identify patterns in the data, making predictions of future exchange rates using the model, and evaluating the model's performance.

Uploaded by

9hgxjfsctp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

SARIMA Model for Forecasting

Currency Exchange Rates V

GenAI Projects for 2024: Train LLMs


like GPT-3.5, Create Your ChatGPT,
Build Text-to-Image Models.

Learn More

Home Beginner

SARIMA Model for Forecasting Currency

Exchange Rates

Ata Amrullah
A 20 Jun, 2023 • 7 min read

Introduction

Forecasting currency exchange rates is

the practice of anticipating future

changes in the value of one currency

about another. Currency forecasting may

assist people, corporations, and financial

organizations make educated financial

decisions. One of the forecasting

techniques that can be used is SARIMA.

SARIMA is an excellent time series

forecasting technique for estimating time

series data with seasonal patterns.

It works by modeling the link between

past and current values of a time series

and recognizing patterns in the data.

SARIMA utilizes a variety of auto-

regression (AR) and moving average

(MA) models, as well as differencing, to

capture trends and seasonality in data.

“seasonality” refers to data variations

that occur regularly and predictably

throughout a specified period, such as

daily, weekly, or annual cycles. We can

be better informed about changes in

currency values by anticipating exchange

rates. Now, let’s make the forecasting

through the steps in the article.

Learning Objectives

!" To help individuals, businesses, and

financial institutions anticipate

market trends by identifying patterns

and trends in historical data.

$" To reduce risk by identifying potential

risks associated with currency

fluctuations.

%" To optimize currency conversions by

identifying the best time to convert

currencies.

&" Improve decision-making by

providing businesses and individuals

with information about the future

direction of currency exchange rates.

Based on these objectives, we will use

SARIMA to develop a model to estimate

currency exchange rates by aggregating

seasonal data patterns to make more

accurate predictions of future values.

This article was published as a part of

the Data Science Blogathon.

Table of contents

Step 1: Import Library

!pip install pmdarima


from pmdarima.arima import auto_arima
from statsmodels.tsa.statespace.sarimax im
from statsmodels.tsa.seasonal import seaso
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objs as go
import plotly.io as pio

We must install the ‘pmdarima’ library to

use the auto_arima function. This

function fits an ARIMA model with time

series data and automatically

determines the appropriate model

parameters based on the data provided.

Step 2: Read the Data

We need historical data about exchange

rates between two currencies to forecast

exchange rates. Thus, we can download

historical data containing weekly

exchange rates between INR and USD at

yahoo finance web. And we can utilize a

period of December 1, 2003, to June 15,

2023. Fortunately, I’ve made it public on

GitHub.

alamat = 'https://raw.githubusercontent.co
data = pd.read_csv(alamat)
print(data.sample(11))

Data Overview

Let’s check whether the dataset includes

any missing values before proceeding

further. It is essential to verify.

print(data.isna().sum())

Missing Value

Several missing values in the dataset

have been identified. As a result, we

must eliminate them.

data = data.dropna()

Examine descriptive statistics to acquire

a better understanding of the data set

and the factors that underpin it. We may

get essential insights into data set

characteristics, spot potential outliers,

grasp data distribution elements, and

establish the framework for future

exploratory data analysis and modeling

efforts. Let’s look at the descriptive

statistics for this data collection.

print(data.describe())

Data Descriptive Statistics

The dataset contains the value of INR for

1 USD for a given time. Below are all the

features in the data:

!" The date represents the specific day

of the exchange rate data.

$" Open refers to the exchange rate at

the start of a specific trading period,

such as the opening price for the day

or the week.

%" High represents the highest

exchange rate observed during a

specific trading period.

&" Low represents the lowest exchange

rate observed during a specific

trading period.

'" Close shows the currency rate at the

end of a certain trading period.

(" Adjusted Closing considers any

business activities that may impact

the Closing Price, such as stock splits

or dividends.

)" Volume refers to the number of USD-

INR currency pairs traded during a

specific period.

Step 3: Conversion Rate


Analysis

Let’s analyze the conversion rates

between the two currencies over the

years. By examining historical trends, we

can gain valuable insights into exchange

rate dynamics and potentially uncover

important patterns or events that affect

these exchange rates. To visualize this

analysis, we will use a line chart to

illustrate the trend of the USD-INR

conversion rate over time.

figure = px.line(data, x="Date",


y="Close",
title='Conversion Rate ov
figure.show()

Annual Conversion Rate

Let’s add year and month fields to the

data so we can enable deeper temporal

analysis.

data["Date"] = pd.to_datetime(data["Date"]
data['Year'] = data['Date'].dt.year
data["Month"] = data["Date"].dt.month
print(data.head())

Date Open High Low closeAdjcloseVolume


02003-12-0145.70900045.72800145.44900145.48000045.480000 0.0
12003-12-0845.47499845.50799945.35200145.45100045.451000 0.0

22003-12-1545.45000145.50000045.33200145.45500245.455002
32003-12-2245.41700045.54900045.29600145.50799945.507999 0.0

42003-12-2945.439999 45.64500045.42100145.56000145.560001 0.0

Year Month
2003 12
2003 12
2003 12
2003 12
2003 12

Adding New Column

Let’s examine the compounded yearly

increase of the INR-USD exchange rate

to discover times of economic strength

or weakness, important events impacting

currency rates, or long-term patterns in

INR-USD conversion rates.

growth = data.groupby('Year').agg({'Close'

fig = go.Figure()
fig.add_trace(go.Bar(x=growth.index,
y=growth['Close'],
name='Yearly Growth')

fig.update_layout(title="Yearly Growth of
xaxis_title="Year",
yaxis_title="Growth (%)"
width=900,
height=600)

pio.show(fig)

Conversion Rate Annual Growth

Now let’s break it down again by looking

at the combined monthly conversion rate

growth between INR and USD.

import warnings
warnings.simplefilter(action='ignore', cat
# Calculate monthly growth
data['Growth'] = data.groupby(['Year', 'Mo
transform(lambda x: (x.iloc[-1] - x.iloc[0

# Group data by Month and calculate averag


grouped_data = data.groupby('Month').mean(

fig = go.Figure()

fig.add_trace(go.Bar(
x=grouped_data['Month'],
y=grouped_data['Growth'],
marker_color=grouped_data['Growth'],
hovertemplate='Month: %{x}<br>Average
))

fig.update_layout(
title="Aggregated Monthly Growth of Co
xaxis_title="Month",
yaxis_title="Average Growth (%)",
width=900,
height=600
)

pio.show(fig)

Monthly Growth of the Conversion Rate

The graph illustrates that the USD value

has consistently decreased in January

and March. This observation shows that

the INR tends to strengthen against the

USD during these months, reducing the

conversion rate. Meanwhile, in the

second quarter, the USD boosted against

the INR every year. The USD value

against INR peaked in August but fell in

September, rose annually in the fourth

quarter, and fell again in December.

Step 4: Build a SARIMA Model


and Make a Forecasting

We must perform a seasonal

decomposition of the USD – INR

exchange rate data. This method

separates the different data

components: trends, seasonality, and

residual or random fluctuations.

result = seasonal_decompose(data["Close"],
fig = plt.figure()
fig = result.plot()
fig.set_size_inches(8, 6)
fig.show()

Seasonal Decomposition

We can see that there is a seasonal

pattern to this data. So, we use SARIMA

as the most appropriate algorithm for

this data. Before using SARIMA, we need

to find the p, d, and q values first. We

can use the ‘pmdarima’ library to find

those values automatically.

model = auto_arima(data['Close'], seasonal


print(model.order)

p,d,q value

The parameter seasonal=True

determines that the time series shows a

seasonal pattern. Meanwhile, the

parameter m=52 shows the seasonal

periodicity of weekly data. And 2, 1, 0 is

the p, d, q value.

We are ready to train our model using

SARIMA to estimate currency exchange

rates.

from statsmodels.tools.sm_exceptions impor


warnings.simplefilter('ignore', ValueWarni

p, d, q = 2, 1, 0
model = SARIMAX(data["Close"], order=(p, d
seasonal_order=(p, d, q, 5
fitted = model.fit()
print(fitted.summary())

SARIMAX model summary

We now predict future currency

exchange rates from the fitted ARIMA

model.

predictions = fitted.predict(len(data), le
print(predictions)

Prediction Values

We display the prediction value on the

graph to make it more engaging.

fig = go.Figure()

# Add training data line plot


fig.add_trace(go.Scatter(
x=data.index,
y=data['Close'],
mode='lines',
name='Training Data',
line=dict(color='blue')
))

# Add predictions line plot


fig.add_trace(go.Scatter(
x=predictions.index,
y=predictions,
mode='lines',
name='Predictions',
line=dict(color='red')
))

fig.update_layout(
title="Training Data VS Predictions",
xaxis_title="Date",
yaxis_title="Close",
legend_title="Data",
width=1000,
height=600
)

pio.show(fig)

Graphic Prediction Result

Conclusion

This article starts by checking if there

are missing values in the dataset and

analyzing the data with descriptive

statistics. Then explore the conversion

rate between the two currencies

aggregated annually and monthly before

forecasting the currency exchange rate

using the SARIMA. We have discussed

the following:

The SARIMA model is a statistical

model that captures seasonal trends

in the past values of the data to

predict future discounts.

The SARIMA model can forecast

currency exchange rates for various

currencies.

The SARIMA model helps make

informed decisions related to

currency trading, financial planning,

or international business operations.

The accuracy of the model depends

on several factors, including the data

quality and the currency market’s

stability.

This article provides a comprehensive

guide to currency exchange rate


forecasting with SARIMA using Python.

The media shown in this article is not

owned by Analytics Vidhya and is used

at the Author’s discretion.

blogathon Conversion Rate

dataset forecasting Seasonality

time Time Series trends

Ata Amrullah
A 20 Jun 2023

Beginner Statistics Time Series

Time Series Forecasting

Frequently Asked
Questions

Q1. What is the forecasting currency


exchange rate?

A. Forecasting currency exchange rates is


predicting changes in the value of one
currency compared to another at a
particular time. Generally influenced by
various factors, including economic
figures, political events, market mood,
and technical analysis.

Q2. What is SARIMA Technique?

Q3. What’s the distinction between


ARIMA and SARIMA?

Q4. What are the SARIMA model’s


benefits?

Q5. What are the risks associated with


using the SARIMA model?

Write, Shine, Succeed

Write, captivate, and earn accolades and


rewards for your work

Reach a Global Audience

Get Expert Feedback

Build Your Brand & Audience

Cash In on Your Knowledge

Join a Thriving Community

Level Up Your Data Science Game

Arnab Mondal Prateek Majumder

15 68

Company Discover

About Us Blogs

Contact Us Expert session

Careers Podcasts

Comprehensive
Guides

Learn Engage

Free courses Community

Learning path Hackathons

BlackBelt program Events

Gen AI Daily challenges

Contribute Enterprise

Contribute & win Our offerings

Become a speaker Case studies

Become a mentor Industry report

Become an instructor quexto.ai

Download
App

Terms & conditions Refund Policy


Privacy Policy Cookies Policy ©
Analytics Vidhya 2023.All rights reserved.

You might also like