Exchange rate shock after 45 years of martial law: Graphing the USD exchange rate with R visualization

On December 3, 2024, at 10:27 p.m., South Korea declared martial law, which threw financial markets into turmoil. Martial law is a measure used by governments to maintain order through military control in times of national emergency, and can have a severe impact on the economy.

In this post, we'll share the process of analyzing the impact of martial law on exchange rates using R visualization methods and generating a graph of the exchange rate of the Korean Won. This will help you quantitatively understand the economic impact of martial law and how to respond in the future.

R로 시각화한 계엄령 발표후 원달러 환율 그래프
(A graph of the USD exchange rate visualized in R)

1. Install and load the required packages

First, we install and load the R packages we need to import and visualize the data. If you don't have these packages installed before loading them, the console will tell you that you need to install them when you run the code. Most likely, you don't have alphavantager installed, so you can use the install.packages command in the source code below to install the missing packages.

# Install and load the required packages
# install.packages("alphavantager") # install.packages When installing packages, you will see " Required!
library(alphavantager)
library(dplyr)
library(ggplot2)
library(lubridate)
  • Alpha VantageThe Free APIs for stock, forex, and cryptocurrency datafor users. Users can utilize the data by registering with an email and receiving a free API key. The API provides data in JSON and CSV formats and includes time series data on stocks, basic information on companies, technical indicators, and more. The free API allows up to 500 requests per day and up to 5 requests per minute, and real-time data is limited to forex and cryptocurrencies.

2. Set up Alpha Vantage API and download data

Use the Alpha Vantage API to download minute-by-minute exchange rate data. To use this API Requires an issued API keyin the file.

# Alpha Vantage API Key Setup
av_api_key("YOUR_ALPHA_VANTAGE_API_KEY") # Enter your issued API key

# Download minute-by-minute data
symbol <- "USDKRW" # Korean won-dollar exchange rate symbol
data <- av_get(
  symbol = symbol,
  av_fun = "TIME_SERIES_INTRADAY", # Settings to get Intraday data
  interval = "1min", # Interval in 1 minute increments
  outputsize = "full" # Request full data
)

3. data preprocessing

Preprocess the downloaded data and convert it into a form suitable for analysis. This includes time zone conversion and selecting the columns you need.

Preprocessing # data (including UTC → KST conversion)
data_filtered %
  select(timestamp, open, high, low, close) %>% # Select the columns you need
  mutate(timestamp = with_tz(timestamp, tzone = "Asia/Seoul")) %>% # Convert UTC to KST
  filter(
    timestamp >= as.POSIXct("2024-12-03 00:00:00", tz = "Asia/Seoul") & # December 3, 2024 after 0:00 KST
      timestamp %
  arrange(timestamp) # sort by timestamp

Handle if # data is empty
if (nrow(data_filtered) == 0) {
  stop("No data available for the selected time range. Please check the API or time range.")
}

4. calculate the average, best, and worst exchange rates

Calculate the average, best, and worst exchange rates based on the preprocessed data.

Calculate # average, high, low exchange rate
avg_rate <- mean(data_filtered$close, na.rm = TRUE) # to calculate the average rate
max_rate <- max(data_filtered$high, na.rm = TRUE) # to calculate the highest exchange rate
min_rate <- min(data_filtered$low, na.rm = TRUE) # to calculate the lowest rate

5. Visualize a graph of the USD exchange rate

ggplot2 to visualize exchange rate fluctuations.

Visualize #
ggplot(data_filtered, aes(x = timestamp, y = close)) +
  geom_line(color = "steelblue", size = 1.2) + # Rate Change Line Graph
  geom_hline(yintercept = avg_rate, color = "darkgreen", linetype = "dashed", size = 1) + # Average exchange rate horizontal line
  geom_hline(yintercept = max_rate, color = "red", linetype = "dotted", size = 1) + # maximum rate horizontal line
  geom_hline(yintercept = min_rate, color = "blue", linetype = "dotted", size = 1) + # lowest exchange rate horizontal line
  annotate("text", x = max(data_filtered$timestamp), y = avg_rate,
           label = paste0("Average: ", round(avg_rate, 2)), vjust = -1, color = "darkgreen") +
  annotate("text", x = max(data_filtered$timestamp), y = max_rate,
           label = paste0("Max: ", round(max_rate, 2)), vjust = -1, color = "red") +
  annotate("text", x = max(data_filtered$timestamp), y = min_rate,
           label = paste0("Min: ", round(min_rate, 2)), vjust = 2, color = "blue") +
  labs(
    title = "KRW/USD Exchange Rate from Midnight, Dec 3, 2024 (KST)",
    subtitle = "1-Minute Interval Data via Alpha Vantage API",
    x = "Time (KST)",
    y = "Exchange Rate (KRW per USD)"
  ) + Β
  theme_minimal() +
  theme(
    plot.title = element_text(size = 18, face="bold"),
    plot.subtitle= element_text(size=14),
    axis.title= element_text(size=12),
    axis.text= element_text(size=10),
    axis.text.x= element_text(angle=45,hjust=1)         

6. Martial Law and Financial Markets: What the Data Means

The declaration of martial law had a huge psychological and practical impact on financial markets. R can be used to quantitatively analyze this data and help inform investment decisions.

The code in this post to generate a graph of the dollar exchange rate shows how to take exchange rate data directly and analyze and visualize changes. These methods are very useful for getting a comprehensive understanding of economic conditions beyond just the numbers.

# Full Code & Detailed Code Explanation

# Install and load the required packages
# install.packages("alphavantager")
library(alphavantager)
library(dplyr)
library(ggplot2)
library(lubridate)

Set the # Alpha Vantage API key
av_api_key("YOUR_ALPHA_VANTAGE_API_KEY") # Enter your issued API key

# Download minute-by-minute data
symbol <- "USDKRW" # Korean won-dollar exchange rate symbol
data <- av_get(
  symbol = symbol,
  av_fun = "TIME_SERIES_INTRADAY", # Settings to get Intraday data
  interval = "1min", # Interval in 1 minute increments
  outputsize = "full" # Request full data
)

Preprocess # data (including UTC → KST conversion)
data_filtered %
  select(timestamp, open, high, low, close) %>% # Select the required columns
  mutate(timestamp = with_tz(timestamp, tzone = "Asia/Seoul")) %>% # Convert UTC to KST
  filter(
    timestamp >= as.POSIXct("2024-12-03 00:00:00", tz = "Asia/Seoul") & # December 3, 2024 after 0:00 KST
      timestamp %
  arrange(timestamp) # sort by timestamp

Handle if # data is empty
if (nrow(data_filtered) == 0) {
  stop("No data available for the selected time range. Please check the API or time range.")
}

Calculate the average, highest, and lowest exchange rate for #
avg_rate <- mean(data_filtered$close, na.rm = TRUE) Calculate the average rate for #
max_rate <- max(data_filtered$high, na.rm = TRUE) # to calculate the highest exchange rate
min_rate <- min(data_filtered$low, na.rm = TRUE) # to calculate the lowest rate

Visualize #
ggplot(data_filtered, aes(x = timestamp, y = close)) +
  geom_line(color = "steelblue", size = 1.2) + # Exchange Rate Change Line Graph
  geom_hline(yintercept = avg_rate, color = "darkgreen", linetype = "dashed", size = 1) +
  geom_hline(yintercept = max_rate, color = "red", linetype = "dotted", size = 1) +
  geom_hline(yintercept = min_rate, color = "blue", linetype = "dotted", size = 1) +
  annotate("text", x = max(data_filtered$timestamp), y = avg_rate,
           label = paste0("Average: ", round(avg_rate, 2)), vjust = -1, color = "darkgreen") +
  annotate("text", x = max(data_filtered$timestamp), y = max_rate,
           label = paste0("Max: ", round(max_rate, 2)), vjust = -1, color = "red") +
  annotate("text", x = max(data_filtered$timestamp), y = min_rate,
           label = paste0("Min: ", round(min_rate, 2)), vjust = 2, color = "blue") +
  labs(
    title = "KRW/USD Exchange Rate from Midnight, Dec 3, 2024 (KST)",
    subtitle = "1-Minute Interval Data via Alpha Vantage API",
    x = "Time (KST)",
    y = "Exchange Rate (KRW per USD)"
  ) + Β
  theme_minimal() +
  theme(
    plot.title=element_text(size=18, face="bold"),
    plot.subtitle=element_text(size=14),
    axis.title=element_text(size=12),
    axis.text=element_text(size=10),
    axis.text.x=element_text(angle=45,hjust=1)
)

Interpreting code

1. Installing and loading packages

   library(alphavantager)
   library(dplyr)
   library(ggplot2)
   library(lubridate)
  • alphavantagerUsed to get financial data through the Alpha Vantage API.
  • dplyr: Packages for preprocessing and manipulating data.
  • ggplot2: A package for data visualization.
  • lubridate: Package for date and time manipulation.

2. Set up your Alpha Vantage API key

   av_api_key("YOUR_ALPHA_VANTAGE_API_KEY")
  • Set up a private API key to use the Alpha Vantage API.

3. Downloading data

   symbol <- "USDKRW"
   data <- av_get(
     symbol=symbol,
     av_fun="TIME_SERIES_INTRADAY",
     interval="1min",
     outputsize="full"
   )
  • symbolSets the symbol for the won-dollar exchange rate.
  • av_get: Get the won-dollar exchange rate data from Alpha Vantage on a minute-by-minute basis.

4. Data preprocessing

   data_filtered %
     select(timestamp, open, high, low, close) %>%
     mutate(timestamp=with_tz(timestamp, tzone="Asia/Seoul")) %>%
     filter(
       timestamp >= as.POSIXct("2024-12-03 00:00:00", tz="Asia/Seoul") &
       timestamp %
     arrange(timestamp)
  • select: Select only the columns you need.
  • mutate: Converts UTC time to Korean Standard Time (KST).
  • filter: Filters data within a specified date range.
  • arrange: Sort the data in chronological order.

5. Handling when data is empty

   if (nrow(data_filtered) == 0) {
     stop("No data available for the selected time range. Please check the API or time range.")
   }
  • If the filtered data is empty, output an error message and abort execution.

6. Calculate average, best, and worst exchange rates

   avg_rate <- mean(data_filtered$close, na.rm=TRUE)
   max_rate <- max(data_filtered$high, na.rm=TRUE)
   min_rate <- min(data_filtered$low, na.rm=TRUE)
  • Average (avg_rate), highest (max_rate), lowest (min_rate) Calculate the exchange rate for each.

7. graph of the USD exchange rate Visualization 下載

   ggplot(data_filtered, aes(x=timestamp, y=close)) +
     geom_line(color="steelblue", size=1.2) +
     geom_hline(yintercept=avg_rate,color="darkgreen",linetype="dashed",size=1)+
     geom_hline(yintercept=max_rate,color="red",linetype="dotted",size=1)+
     geom_hline(yintercept=min_rate,color="blue",linetype="dotted",size=1)+
     annotate("text",x=max(data_filtered$timestamp),y=avg_rate,
              label=paste0("Average: ",round(avg_rate,2)),vjust=-1,color="darkgreen")+
     annotate("text",x=max(data_filtered$timestamp),y=max_rate,
              label=paste0("Max: ",round(max_rate,2)),vjust=-1,color="red")+
     annotate("text",x=max(data_filtered$timestamp),y=min_rate,
              label=paste0("Min: ",round(min_rate,2)),vjust=2,color="blue")+
     labs(
       title="KRW/USD Exchange Rate from Midnight, Dec3,2024(KST)",
       subtitle="1-Minute Interval Data via Alpha Vantage API",
       x="Time (KST)",
       y="Exchange Rate (KRW per USD)"
     ) + Β
     theme_minimal() +
     theme(
       plot.title=element_text(size=18, face="bold"),
       plot.subtitle=element_text(size=14),
       axis.title=element_text(size=12),
       axis.text=element_text(size=10),
       axis.text.x=element_text(angle=45,hjust=1)
     )
  • geom_line: Shows the change in the exchange rate as a line graph.
  • geom_hlineDisplays the average (green dotted line), highest (red dotted line), and lowest (blue dotted line) exchange rates as horizontal lines.
  • annotate: Adds a text annotation of each figure to the graph.
  • labs: Set the graph title and axis labels.
  • theme_minimal and theme: Sets the style and text size of the graph.

This code demonstrates the process of using R visualization methods to get data from the Alpha Vantage API, analyze it, and generate a graph of the Korean Won exchange rate. (The generated graph is a bit off in terms of dates, but this is likely due to the timezone, so I'll do a little more research and change it to match your local time).

Similar Posts