This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.2 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.3 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggthemes)
library(ggrepel)
library(pwrss)
##
## Attaching package: 'pwrss'
##
## The following object is masked from 'package:stats':
##
## power.t.test
library(pwr)
library(glm2)
library(ggplot2)
library(tsibble)
##
## Attaching package: 'tsibble'
##
## The following object is masked from 'package:lubridate':
##
## interval
##
## The following objects are masked from 'package:base':
##
## intersect, setdiff, union
library(xts)
## Loading required package: zoo
##
## Attaching package: 'zoo'
##
## The following object is masked from 'package:tsibble':
##
## index
##
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
##
##
## ######################### Warning from 'xts' package ##########################
## # #
## # The dplyr lag() function breaks how base R's lag() function is supposed to #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or #
## # source() into this session won't work correctly. #
## # #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop #
## # dplyr from breaking base R's lag() function. #
## # #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning. #
## # #
## ###############################################################################
##
## Attaching package: 'xts'
##
## The following objects are masked from 'package:dplyr':
##
## first, last
library(forecast)
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
credit_data = read.csv(("/Users/tbs/Downloads/Data Sets 'R'/credit_data.csv"))
##Creating a time-based column ‘Transaction Date’ :-
# Define the start and end dates
start_date <- as.Date("2000-01-01")
end_date <- as.Date("2023-12-31")
# Create a sequence of dates with a daily interval
credit_data$Transaction_Date <- seq(from = start_date, by = "day", length.out = nrow(credit_data))
##Filtering only pertinent time series data, and removing duplicates taking Transaction Date as date column and Loan Amount as Responsible Variable :-
credit_ <- credit_data |>
select(Transaction_Date,Loan.Amount) |>
distinct()
The response variable should be precisely defined and computed uniquely for each unit of time. Consequently, each row must be distinct, without any duplicates. Above we considered ‘Transaction_Date’ column as an index, and define our response variable to be “Loan Amount”.
##Creating a tsibble object of just the date column and response variable, then plotting data over time :-
# create a tsibble of daily earthquake counts
credit_ts <- as_tsibble(credit_, index=Transaction_Date) |>
index_by(date = date(Transaction_Date)) |>
fill_gaps()
##Creating a separate “xts” time series data frame for statistical modeling:-
# an "xts" object separate from the original
credit_xts <- xts(x = credit_ts$Loan.Amount,
order.by = credit_ts$Transaction_Date)
credit_xts <- setNames(credit_xts, "credits")
##Plot for the overall period,to predict the trends:-
credit_xts %>%
rollapply(width = 30, \(x) mean(x, na.rm = TRUE), fill = FALSE) %>%
ggplot(mapping = aes(x = Index, y = credits)) +
geom_line() +
geom_smooth(method = 'lm', color = 'blue', se = FALSE) +
labs(title = "Loan Amount Trends") +
theme_hc()
## `geom_smooth()` using formula = 'y ~ x'
The resulting chart visually depicts the overall trend of loan amounts
over time, potentially revealing seasonal patterns or long-term trends.
The smooth line helps in identifying the overall direction of the loan
amounts, while the raw line data provides a more detailed view of the
fluctuations.
##Analyzing the seasonality of loan amounts in 2022 using smoothing.
credit_ts |>
filter_index("2022" ~ "2023") |>
drop_na() |>
ggplot(mapping = aes(x = Transaction_Date , y = Loan.Amount)) +
geom_point(size=1, shape='O') +
geom_smooth(span=0.2, color = 'blue', se=FALSE) +
labs(title = "Loan Amount Trends for 2022 and 2023") +
theme_hc()
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
The resulting chart visually depicts the overall trend of loan amounts
over time for 2022 and 2023. The individual points provide a detailed
view of the daily transactions, while the smooth line helps in
identifying the overall direction of the loan amounts.
##Analyze the trends of loan amounts in 2021 using a line plot and linear regression
credit_ts |>
filter_index("2021-01" ~ "2021-06") |>
ggplot(mapping = aes(x = Transaction_Date, y = Loan.Amount)) +
geom_line() +
geom_smooth(method = 'lm', color = 'blue', se=FALSE) +
labs(title = "Loan Amount Trends") +
theme_hc()
## `geom_smooth()` using formula = 'y ~ x'
This involves focusing on the loan amount data for 2021 and creating a
line plot to visualize the trend over time. Linear regression is applied
to the data to fit a linear model that captures the overall trend of
loan amounts. The line plot combined with linear regression provides a
clear understanding of the general direction of loan amounts in
2021.
The loan amount trend exhibits an overall upward trajectory, with a slight seasonal pattern favoring the second half of the year. The underlying demand for loans appears to be relatively stable, contributing to the smooth trend line.
credit_ts |>
index_by(year = floor_date(Transaction_Date, 'halfyear')) |>
summarise(avg_credits = mean(Loan.Amount, na.rm = TRUE)) |>
ggplot(mapping = aes(x = year, y = avg_credits)) +
geom_line() +
geom_smooth(span = 0.3, color = 'blue', se=FALSE, ) +
labs(title = "Average credits Over Time",
subtitle = "(by half year)") +
scale_x_date(breaks = "1 year", labels = \(x) year(x)) +
theme_hc()
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
smooth line superimposed to visualize the average loan amounts over
time, grouped by half-year. The smooth line helps identify the overall
trend, while the data points provide a detailed view of the average loan
amounts for each half-year.
# Plot ACF and PACF to illustrate seasonality
credit_ts <- na.omit(credit_ts)
your_acf <- acf(credit_ts$Loan.Amount, lag.max = 30)
your_pacf <- pacf(credit_ts$Loan.Amount, lag.max = 30)
# Plot ACF
autoplot(your_acf) +
labs(title = "Autocorrelation Function (ACF)",
x = "Lag",
y = "ACF")
# Plot PACF
autoplot(your_pacf) +
labs(title = "Partial Autocorrelation Function (PACF)",
x = "Lag",
y = "PACF")
##ACF Plot (Autocorrelation Function):
The ACF plot illustrates the autocorrelation at different lags. The x-axis represents the lag (time interval between observations), and the y-axis represents the autocorrelation coefficient. Points outside the shaded blue region are considered statistically significant correlations.
The significant correlations at lags 12 and 24 are highlighted in the plot by the spikes in the ACF values at those lags. The ACF values at other lags are close to zero, indicating that there is little correlation between the loan amounts at those lags.
The ACF plot shows a significant correlation at lags 12 and 24, indicating that there is a seasonal pattern in the loan amounts. This means that the loan amounts tend to repeat the same pattern every 12 months.
##PACF Plot (Partial Autocorrelation Function):
The PACF plot shows the partial autocorrelation at different lags, accounting for the influence of intermediate lags. Similar to the ACF plot, the x-axis represents the lag, and the y-axis represents the partial autocorrelation coefficient. Points outside the shaded blue region are considered statistically significant partial autocorrelations.
The PACF plot also shows significant correlations at lags 12 and 24, confirming the presence of seasonal patterns. The PACF plot measures the correlation between a time series and its lagged versions after removing the effect of any intervening lags. The fact that the PACF values at lags 12 and 24 are significant after removing the effect of intervening lags indicates that the seasonal pattern in the loan amounts is not due to any other factors.