---
title: "Getting Started with Turkish Banking Data"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting Started with Turkish Banking Data}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---


```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  fig.alt = "Default descriptive text",
  comment = "#>"
)
```

# Introduction to the rbrsa package

The `rbrsa` package facilitates programmatic access to Turkish banking sector data from the Turkish Banking Regulation  and Supervision Agency (BRSA, known as BDDK in Turkish). The package provides  R users with a clean interface to fetch monthly and quarterly banking statistics,  financial reports, and sectoral indicators directly from BRSA's official APIs. This vignette demonstrates a complete workflow: from discovering available data to fetching it and performing a basic analysis.

Some key features are
- Direct API access to BRSA monthly bulletins (17 financial tables)
- Quarterly Finturk data with city-level granularity (7 tables, 82 cities including 'HEPSI' for all cities)
- Consistent parameter interface for both data sources
- Built-in metadata for tables, banking groups, and cities
- Multiple export formats: RDS, CSV, Excel via `save_data()`
- Returns base R data frames ready for analysis

## Installation and Setup

```{r, eval=FALSE}
# Install from CRAN
install.packages("rbrsa")

# Or install the development version from GitHub
# install.packages("pak")
pak.::pkg_install("obakis/rbrsa")
```

```{r}
# Load the package
library(rbrsa)
```

## Part 1: Discovering Available Data

Before requesting data, it's useful to explore what tables and banking groups are available from BDDK's two main portals.  
Both portals are official sources, but they organize the data differently:
The [Monthly Bulletin Portal](https://www.bddk.org.tr/bultenaylik) provides 
high-level, summary reports designed for general consumption and quick 
overviews of monthly trends without any geographic coverage.
The [Finturk Data System](https://www.bddk.org.tr/BultenFinturk/) provides 
granular, detailed data, including statistics broken down by province, whereas the standard Monthly Bulletin offers national-level aggregates.

**Important note**: Currently, only a single `grup_kod` can be specified per request.  The underlying BDDK API supports multiple `grup_kod` codes, and this functionality will be added in a future version.

### Monthly Bulletin Tables

Monthly Bulletin provides high-level, national aggregate statistics.

```{r}
# List available tables in the Monthly Bulletin
bulletin_tables <- list_tables("bddk", lang="en")
head(bulletin_tables)

# List available banking groups for the Monthly Bulletin
bulletin_groups <- list_groups("bddk", lang="en")
head(bulletin_groups)
```

### Finturk Tables

Finturk system provides more granular data, including provincial breakdowns.

```{r}
# List available tables in Finturk
finturk_tables <- list_tables("finturk", lang="en")
finturk_tables

# List available banking groups for Finturk
finturk_groups <- list_groups("finturk", lang="en")
finturk_groups

# List of cities for Finturk
cities <- list_cities()
head(cities)

```

## Part 2: Fetching Monthly Bulletin Data

Let's fetch "Table 4: Consumer Loans" for public banks (`grup_kod = 10006`) between January 2020 and December 2020.

```{r}
my_dat <- fetch_bddk(
  start_year = 2020,
  start_month = 1,
  end_year = 2020,
  end_month = 12,
  table_no = 4,
  grup_kod = 10001,
  verbose=TRUE
)
# Examine the structure of the returned data
cat("Dimensions:", dim(my_dat), "\n")
colnames(my_dat)
head(my_dat)
## To save the results:
# temp_file <- tempfile() # filename should be without extension
# save_data(my_dat, temp_file, format = "csv")
```

Let's compare "Consumer Loans - Housing" and "Consumer Loans - Personal Finance" over time.

```{r, message=FALSE, warning=FALSE}
library(dplyr)
library(ggplot2)
colnames(my_dat)
cols = c("Consumer Loans - Housing","Consumer Loans - Personal Finance")
p = my_dat |>
  select(Ad,TRY,period) |>
  filter(Ad %in% cols) |>
  mutate(date=as.Date(paste0(period, "-01"))) |>
  ggplot(aes(x=date, y=TRY, color=Ad, group=Ad, shape=Ad)) +
  geom_line(linewidth = 1) +
  geom_point(size = 2.4, alpha = 0.7) +
  scale_x_date(
    date_breaks = "2 months",      # Show tick every 3 months
    date_labels = "%b %Y",         # Format as "Jan 2020"
    expand = c(0.01, 0)           # Reduce padding
  ) +
  scale_y_continuous(
    labels = scales::comma       # Format numbers with commas
  ) +
  labs(
    title = "Consumer Loans Trends, Jan 2020-Dec 2020 (TRY)",
    subtitle = "Monthly data for Housing vs Personal Finance loans",
    x = "",
    y = ""
  ) +
  theme_minimal() +
theme(
    legend.position = "bottom",  # This moves the legend to the bottom
    axis.text.x = element_text(angle = 45, hjust = 1),
    plot.title = element_text(face = "bold", size = 14),
  )
p
```

## Part 3: Fetching Granular Finturk Data

Now let's explore the more detailed Finturk data. We'll fetch "Table 2: Deposits" for all banks (`grup_kod = 10001`), all provinces over 2023 and 2024.

```{r}
my_dat2 <- fetch_finturk(
  start_year = 2023,
  start_month = 3,
  end_year = 2024,
  end_month = 12,
  table_no = 2,
  grup_kod = 10001,
  il=0,
  verbose=FALSE
)
# Examine the structure of the returned data
cat("Dimensions:", dim(my_dat2), "\n")
colnames(my_dat2)
head(my_dat2)
## To save the results:
# temp_file <- tempfile() # filename should be without extension
# save_data(my_dat, temp_file, format = "csv")

```


Finturk data includes a province column (`il`). Let's examine the share of selected provinces in total deposits ove 2020-2024 period.

```{r}
sel_cities =c("ADANA","MALATYA","MUGLA","KAYSERI")
cols = c("il_adi", "period","Toplam Mevduat")
lookup <- c(city="il_adi", deposit="Toplam Mevduat")
p2 = my_dat2[,cols] |>
  rename(all_of(lookup)) |>
  mutate(date=as.Date(paste0(period, "-01"))) |>
  mutate(.by=period, sh = 100*deposit/sum(deposit, na.rm=TRUE)) |>
  filter( city %in% sel_cities) |>
    ggplot(aes(x=date, y=sh, color=city, group=city, shape=city)) +
  geom_line(linewidth = 1) +
  geom_point(size = 2.4, alpha = 0.7) +
  scale_x_date(
    date_breaks = "3 months",      # Show tick every 3 months
    date_labels = "%b %Y",         # Format as "Jan 2020"
    expand = c(0.01, 0)           # Reduce padding
  ) +
  labs(
    title = "Share of Selected Provinces in Deposits, 2020-2023 (TRY)",
    x = "",
    y = ""
  ) +
  theme_minimal() +
theme(
    legend.position = "bottom",  # This moves the legend to the bottom
    axis.text.x = element_text(angle = 45, hjust = 1),
    plot.title = element_text(face = "bold", size = 14),
  )
p2
```

## Part 4: Saving Your Results

The `save_data()` function allows you to export results in various formats for use in other tools.

```{r, eval=FALSE}
# Save to different formats. file name must be without extension
save_data(my_dat, "filename_you_prefer", format = "csv")
save_data(my_dat, "filename_you_prefer", format = "rds")
save_data(my_dat, "filename_you_prefer", format = "xlsx")

# Using tempfile() for examples (as in README)
temp_file <- tempfile()
save_data(my_dat, temp_file, format = "csv")
cat("Data saved to:", temp_file, "\n")
```


## Next Steps

This vignette demonstrated the basic workflow of the `rbrs` package. To learn more:

1.  Explore all functions in the package reference: https://obakis.github.io/rbrsa/reference/
2.  Try different tables and banking groups using `list_tables()` and `list_groups()`.
3.  Check out the `pybrsa` package (https://github.com/obakis/pybrsa) for similar functionality in Python. (UNDER CONSTRUCTION)



```{r, include=FALSE}
# Optional: Ensure all packages needed for building are available
# This chunk won't appear in the final vignette
knitr::opts_chunk$set(
  echo = TRUE,
  message = FALSE,
  warning = FALSE,
  fig.width = 7,
  fig.height = 5,
  fig.align = "center"
)
```

---

*For more detailed function references and advanced usage, visit the complete package documentation at <https://obakis.github.io/rbrsa/>*