Bddkr

9 minute read

Published:

bddkR Tutorial: Working with Turkish Banking Data

Introduction

The bddkR package provides seamless access to Turkish banking sector data published by the Banking Regulation and Supervision Agency (BDDK). This tutorial will guide you through the installation process and demonstrate various use cases for analyzing Turkish banking data.

Installation

Prerequisites

First, ensure you have the required dependencies installed:

install.packages(c("httr", "jsonlite", "dplyr", "writexl", "lubridate"))

Installing bddkR

Install the package directly from GitHub:

# Install devtools if not already installed
if (!require(devtools)) install.packages("devtools")

# Install bddkR from GitHub
devtools::install_github("ozancanozdemir/bddkR")

Loading the Package

library(bddkR)

Basic Usage

Understanding the Parameters

The main function fetch_data() requires several parameters:

  • start_year: Starting year (e.g., 2023)
  • start_month: Starting month (1-12)
  • end_year: Ending year (e.g., 2024)
  • end_month: Ending month (1-12)
  • table_no: Table number (1-17)
  • currency: Currency type (“TL” or “USD”)
  • group: Bank group code (10001-30003)
  • lang: Language (“tr” for Turkish, “en” for English)
  • save_excel: Save to Excel (TRUE/FALSE)

Your First Data Pull

Let’s start with a simple example - fetching balance sheet data for deposit banks:

# Fetch balance sheet data for January 2024
balance_data <- fetch_data(
  start_year = 2024,
  start_month = 1,
  end_year = 2024,
  end_month = 1,
  table_no = 1,        # Balance Sheet
  currency = "TL",
  group = 10001,       # Deposit Banks
  lang = "en",
  save_excel = FALSE
)

# View the structure of the data
str(balance_data)
head(balance_data)

Available Tables and Groups

Financial Tables (table_no)

  1. Balance Sheet - Assets, liabilities, and equity information
  2. Income Statement - Revenue, expenses, and profit data
  3. Loan Portfolio - Loan details and classifications
  4. Consumer Loans - Individual lending data
  5. Sectoral Credit Distribution - Loans by economic sectors
  6. SME Financing - Small and medium enterprise loans
  7. Syndication and Securitization - Complex financing instruments
  8. Securities Portfolio - Investment holdings
  9. Deposit Structure - Deposit types and currencies
  10. Maturity-Based Deposits - Deposits by maturity periods
  11. Liquidity Indicators - Cash and liquid asset metrics
  12. Capital Adequacy - Capital ratios and requirements
  13. Foreign Exchange Position - Currency exposure data
  14. Off-Balance Sheet Items - Contingent assets and liabilities
  15. Financial Ratios - Key performance indicators
  16. Operational Information - Branch, ATM, personnel data
  17. International Branch Data - Overseas operations

Bank Groups (group)

  • 10001: Deposit Banks
  • 10002: Development and Investment Banks
  • 10003: Participation Banks
  • 10004: All Banks
  • 20001: State Banks
  • 20002: Private Banks
  • 20003: Foreign Banks
  • 30001: Large Scale Banks
  • 30002: Medium Scale Banks
  • 30003: Small Scale Banks

Practical Examples

Example 1: Quarterly Balance Sheet Analysis

# Fetch quarterly balance sheet data for 2023
quarterly_balance <- fetch_data(
  start_year = 2023,
  start_month = 3,      # March (Q1)
  end_year = 2023,
  end_month = 12,       # December (Q4)
  table_no = 1,
  currency = "TL",
  group = 10004,        # All Banks
  lang = "en"
)

# View the data structure
print(quarterly_balance)

# Check available periods
unique(quarterly_balance$Period)

Example 2: Comparing Bank Types

# Function to fetch data for different bank groups
fetch_bank_comparison <- function(table_num, year, month) {
  bank_types <- list(
    "State Banks" = 20001,
    "Private Banks" = 20002,
    "Foreign Banks" = 20003
  )
  
  results <- list()
  
  for (bank_name in names(bank_types)) {
    results[[bank_name]] <- fetch_data(
      start_year = year,
      start_month = month,
      end_year = year,
      end_month = month,
      table_no = table_num,
      currency = "TL",
      group = bank_types[[bank_name]],
      lang = "en"
    )
  }
  
  return(results)
}

# Compare income statements across bank types for 2024
income_comparison <- fetch_bank_comparison(2, 2024, 6)  # June 2024

# View results for each bank type
lapply(income_comparison, head)

Example 3: Multi-Currency Analysis

# Fetch the same data in both TL and USD for comparison
fetch_multi_currency <- function(table_num, year, month, group_code) {
  
  # TL data
  tl_data <- fetch_data(
    start_year = year,
    start_month = month,
    end_year = year,
    end_month = month,
    table_no = table_num,
    currency = "TL",
    group = group_code,
    lang = "en"
  )
  
  # USD data
  usd_data <- fetch_data(
    start_year = year,
    start_month = month,
    end_year = year,
    end_month = month,
    table_no = table_num,
    currency = "USD",
    group = group_code,
    lang = "en"
  )
  
  return(list("TL" = tl_data, "USD" = usd_data))
}

# Get balance sheet data in both currencies
multi_currency_data <- fetch_multi_currency(1, 2024, 3, 10001)

# Compare the datasets
str(multi_currency_data$TL)
str(multi_currency_data$USD)

Example 4: Time Series Analysis

# Fetch monthly data for a full year
monthly_loans <- fetch_data(
  start_year = 2023,
  start_month = 1,
  end_year = 2023,
  end_month = 12,
  table_no = 3,         # Loan Portfolio
  currency = "TL",
  group = 10001,        # Deposit Banks
  lang = "en"
)

# Basic time series exploration
library(dplyr)

# Group by period and calculate summary statistics
monthly_summary <- monthly_loans %>%
  group_by(Period) %>%
  summarise(
    total_rows = n(),
    periods_available = n_distinct(Period),
    .groups = 'drop'
  )

print(monthly_summary)

# Plot time series (if you have ggplot2 installed)
if (require(ggplot2)) {
  # This is a basic example - you'll need to adapt based on actual column names
  # monthly_loans %>%
  #   ggplot(aes(x = as.Date(Period), y = some_numeric_column)) +
  #   geom_line() +
  #   labs(title = "Banking Data Over Time")
}

Example 5: Exporting Data to Excel

# Fetch data and save directly to Excel
comprehensive_data <- fetch_data(
  start_year = 2024,
  start_month = 1,
  end_year = 2024,
  end_month = 6,
  table_no = 15,        # Financial Ratios
  currency = "TL",
  group = 10004,        # All Banks
  lang = "en",
  save_excel = TRUE     # This will save the file automatically
)

# The file will be saved as "bddk_2024_01_2024_06.xlsx" in your working directory

Example 6: Batch Data Collection

# Function to collect multiple tables for the same period
collect_comprehensive_data <- function(year, month, group_code, currency_type = "TL") {
  
  # Define tables of interest
  key_tables <- list(
    "Balance_Sheet" = 1,
    "Income_Statement" = 2,
    "Loans" = 3,
    "Deposits" = 9,
    "Ratios" = 15
  )
  
  results <- list()
  
  for (table_name in names(key_tables)) {
    cat("Fetching", table_name, "data...\n")
    
    results[[table_name]] <- fetch_data(
      start_year = year,
      start_month = month,
      end_year = year,
      end_month = month,
      table_no = key_tables[[table_name]],
      currency = currency_type,
      group = group_code,
      lang = "en"
    )
    
    # Add a small delay to be respectful to the API
    Sys.sleep(1)
  }
  
  return(results)
}

# Collect comprehensive data for June 2024
comprehensive_june_2024 <- collect_comprehensive_data(2024, 6, 10001)

# Check what we collected
names(comprehensive_june_2024)
lapply(comprehensive_june_2024, function(x) if(!is.null(x)) dim(x) else "No data")

Data Structure and Column Names

The package automatically handles column naming based on the API response. Here’s what to expect:

Common Columns in All Tables

  • Period: Date in YYYY-MM-DD format
  • Table: Name of the financial table
  • Order: Row sequence number
  • Sector: Description of the data row

Table-Specific Columns

Each table will have specific columns based on its content:

  • Balance Sheet: TP (Turkish Lira), YP (Foreign Currency), Toplam (Total)
  • Income Statement: Various income and expense categories
  • Loan data: Different loan types and classifications

Error Handling and Troubleshooting

Common Issues and Solutions

  1. No data returned: Check if the requested period has published data
    # Always check if data is not NULL
    if (is.null(data)) {
      cat("No data available for the specified parameters\n")
    }
    
  2. API connection issues: The package handles SSL automatically, but network issues may occur
    # Retry mechanism example
    fetch_with_retry <- function(..., max_attempts = 3) {
      for (i in 1:max_attempts) {
     result <- fetch_data(...)
     if (!is.null(result)) return(result)
     cat("Attempt", i, "failed, retrying...\n")
     Sys.sleep(2)
      }
      return(NULL)
    }
    
  3. Parameter validation: The package validates inputs, but double-check your parameters
    # Valid parameter ranges:
    # table_no: 1-17
    # group: 10001, 10002, 10003, 10004, 20001, 20002, 20003, 30001, 30002, 30003
    # currency: "TL" or "USD"
    # lang: "tr" or "en"
    # months: 1-12
    

Performance Tips

  1. Use appropriate date ranges: Avoid unnecessarily large date ranges
  2. Add delays between requests: Be respectful to the BDDK API
  3. Cache results: Store frequently used data locally
  4. Use specific bank groups: Filter data at the API level rather than in R

Advanced Usage

Creating Custom Analysis Functions

# Function to calculate year-over-year growth
calculate_yoy_growth <- function(table_num, month, group_code) {
  
  current_year <- as.numeric(format(Sys.Date(), "%Y"))
  
  # Current year data
  current_data <- fetch_data(
    start_year = current_year,
    start_month = month,
    end_year = current_year,
    end_month = month,
    table_no = table_num,
    currency = "TL",
    group = group_code,
    lang = "en"
  )
  
  # Previous year data
  previous_data <- fetch_data(
    start_year = current_year - 1,
    start_month = month,
    end_year = current_year - 1,
    end_month = month,
    table_no = table_num,
    currency = "TL",
    group = group_code,
    lang = "en"
  )
  
  return(list(
    "current" = current_data,
    "previous" = previous_data
  ))
}

Best Practices

  1. Always check for NULL returns before processing data
  2. Use meaningful variable names that indicate the data period and type
  3. Document your analysis with comments explaining parameter choices
  4. Respect the API by adding delays between requests
  5. Version control your scripts to track analysis changes
  6. Validate data quality by checking for expected patterns

Getting Help

  • Check the package documentation: ?fetch_data
  • Visit the GitHub repository: https://github.com/ozancanozdemir/bddkR
  • Review BDDK’s official documentation for data definitions
  • Open issues on GitHub for bugs or feature requests

Conclusion

The bddkR package provides a powerful and convenient way to access Turkish banking data programmatically. With the examples in this tutorial, you should be able to start analyzing banking trends, comparing institutions, and conducting financial research using official BDDK data.

Remember to always verify your results and understand the context of the data you’re analyzing. The Turkish banking sector is dynamic, and regulatory changes may affect data availability and structure over time.