Credit Card Fraud Analysis

Project background (Introduction)

According to a dataset published by the central bank of Malaysia [Trend of usage for credit card from BNM], there is a growing adoption of users towards credit card facilities. Even in the day and age of digital payments, the ratio of credit card usage is still substantial, covering [Insert dataset regarding the usage of credit card compared to other forms of payment] x% of all payments. The increase in adoption not only brought opportunities, it also brought threats alongside it, fraudsters. As the market is huge, it is very attractive for fraudsters to lay their hands on performing credit card fraud. The data on fraud is clear, on the past x years [Insert data on credit card fraud transactions in the past few years], leading to billions of dollars being lost annually. As a result, my team and I intend to contribute towards the cause of fraud identification and detection, via data science methods, by building a prediction model based on credit card transaction information that is provided for training purposes by [Insert authorising body for the dataset].

Project impact towards society

This project intends to explore the possibilities of creating a reliable model that detects frauds before intervention becomes too late. This could potentially bring benefits towards authorities, card scheme providers such as Visa, MasterCard, and EuroNet, and banks by building a credit card system that is more safe, reliable, and trusted. Furthermore, it also helps credit card users avoid a sticky situation where their card is being used fraudulently, leading up to deteriorating credit scores and immeasurable amounts of debt that they could not afford. In addition, having a more secure and fraud-protected credit card environment also increases the user’s confidence in the system, promoting and enhancing the payment services landscape. Finally, a model as such could reduce the number of fraud incidents, which can indirectly tackle the issue of proliferation of funds and terrorist financing, which is a major concern in the financial sector.

Problem Statement

Credit card fraud happens when someone makes unauthorized transactions using someone’s credit card. The usage of credit cards has increased over the years with online transactions and as a cashless payment method. Credit card fraud leads to implications such as financial loss, identity theft and inconvenience to the cardholders.

Project Objectives

To identify and understand patterns associated with fraud, analyze credit card transactions using advanced techniques, aiming to distinguish characteristics and indicators of legitimate transactions from potentially fraudulent ones.

To evaluate the performance and reliability of the fraud prediction model, assess its robustness through rigorous evaluation and validation processes, utilizing metrics and cross-validation on diverse datasets to ensure real-world applicability.

To develop an adaptive fraud detection model, create a machine learning system that dynamically adapts to evolving credit card fraud patterns, ensuring high performance on historical data and effectively identifying new tactics for a proactive defense.

Key Questions

These questions focus on understanding and analyzing the broader context and trends within the dataset, which can be crucial for developing effective strategies to prevent and manage credit card fraud.

  1. Fraud Pattern Identification: What are the common characteristics of fraudulent transactions? This includes understanding the time, location, amount, and frequency of such transactions.

  2. Transaction Analysis: How do the properties of fraudulent transactions differ from those of legitimate ones?

  3. Geographic Analysis: Are there specific regions or locations where fraud is more prevalent?

  4. Temporal Patterns: At what times do fraud incidents peak? Are there patterns related to days of the week, months, or specific events/holidays?

  5. Impact Assessment: What is the financial impact of fraud on both the customers and the institution?

1. Data Pre-Processing

description

# load the libraries needed 
library(dplyr)
library(knitr)
library(tidyr)
library(ggplot2)

# set the working directory to Downloads
setwd("C:/Users/User/Downloads")
# load dataset
credit_data <- read.csv("credit_card_fraud.csv")

# convert to numeric format
credit_data$amt <- as.numeric(credit_data$amt)
credit_data$lat <- as.numeric(credit_data$lat)
credit_data$long <- as.numeric(credit_data$long)
credit_data$merch_lat <- as.numeric(credit_data$merch_lat)
credit_data$merch_long <- as.numeric(credit_data$merch_long)

# convert categorical variables into factors
credit_data$category <- as.factor(credit_data$category)
credit_data$job <- as.factor(credit_data$job)
credit_data$city <- as.factor(credit_data$city)
credit_data$state <- as.factor(credit_data$state)
credit_data$merchant <- as.factor(credit_data$merchant)

# convert trans_date_trans_time & dob variables
credit_data$trans_date_trans_time <- as.POSIXct(credit_data$trans_date_trans_time)
credit_data$dob <- as.Date(credit_data$dob)

# these columns need scaling (feature scaling) to standardize these numerical features
credit_data[, c('amt', 'lat', 'long', 'city_pop')] <- scale(credit_data[, c('amt', 'lat', 'long', 'city_pop')])

# change 'is_fraud' variable to factor
credit_data$is_fraud <- as.factor(credit_data$is_fraud)
levels(credit_data$is_fraud) <- c("Not Fraud", "Fraud")

2. Explatory Data Analysis (EDA)

Data exploratory helps to gain details of the Credit Card Fraud dataset.

# check for missing values in the dataset
sum(is.na(credit_data))
## [1] 0
# display dataset columns 
names(credit_data)
##  [1] "trans_date_trans_time" "merchant"              "category"             
##  [4] "amt"                   "city"                  "state"                
##  [7] "lat"                   "long"                  "city_pop"             
## [10] "job"                   "dob"                   "trans_num"            
## [13] "merch_lat"             "merch_long"            "is_fraud"
# explore the first and last few rows of dataset
head(credit_data)
##   trans_date_trans_time                  merchant      category        amt
## 1   2019-01-01 00:00:44 Heller, Gutmann and Zieme   grocery_pos  0.2267015
## 2   2019-01-01 00:00:51            Lind-Buckridge entertainment  0.9248912
## 3   2019-01-01 00:07:27                 Kiehn Inc   grocery_pos  0.1590350
## 4   2019-01-01 00:09:03               Beier-Hyatt  shopping_pos -0.3884824
## 5   2019-01-01 00:21:32                Bruen-Yost      misc_pos -0.3941728
## 6   2019-01-01 00:22:06                 Kunze Inc   grocery_pos  0.1214906
##                       city state        lat        long   city_pop
## 1                   Orient    WA  1.7995837 -0.59976867 -0.3651227
## 2               Malad City    ID  0.4831851 -0.12958242 -0.3514552
## 3                  Grenada    CA  0.3716435 -0.94086218 -0.3636212
## 4 High Rolls Mountain Park    NM -1.3306069  0.37969841 -0.3625632
## 5                  Freedom    WY  0.6473473 -0.03213842 -0.3640238
## 6                  Honokaa    HI -3.8540608 -3.54628761 -0.3489844
##                                 job        dob                        trans_num
## 1 Special educational needs teacher 1978-06-21 1f76529f8574734946361c461b024d99
## 2       Nature conservation officer 1962-01-19 a1a22d70485983eac12b5b88dad1cf95
## 3                   Systems analyst 1945-12-21 413636e759663f264aae1819a4d4f231
## 4                   Naval architect 1967-08-30 8a6293af5ed278dea14448ded2685fea
## 5         Education officer, museum 1967-08-02 f3c43d336e92a44fc2fb67058d5949e3
## 6                   Physiotherapist 1966-12-03 95826e3caa9e0b905294c6dae985aec1
##   merch_lat merch_long  is_fraud
## 1  49.15905  -118.1865 Not Fraud
## 2  43.15070  -112.1545 Not Fraud
## 3  41.65752  -122.2303 Not Fraud
## 4  32.86326  -106.5202 Not Fraud
## 5  43.75373  -111.4549 Not Fraud
## 6  19.56001  -156.0459 Not Fraud
tail(credit_data)
##        trans_date_trans_time                       merchant       category
## 339602   2020-12-31 23:57:18 Larkin, Stracke and Greenfelde  entertainment
## 339603   2020-12-31 23:57:56                 Schmidt-Larkin           home
## 339604   2020-12-31 23:58:04      Pouros, Walker and Spence      kids_pets
## 339605   2020-12-31 23:59:07                Reilly and Sons health_fitness
## 339606   2020-12-31 23:59:15                      Rau-Robel      kids_pets
## 339607   2020-12-31 23:59:24                Breitenberg LLC         travel
##               amt               city state        lat       long   city_pop
## 339602 -0.1476292 Blairsden-Graeagle    CA 0.01839254 -0.7918427 -0.3597444
## 339603 -0.3581129              Wales    AK 4.91399395 -4.3512835 -0.3651364
## 339604 -0.3560099          Greenview    CA 0.35747264 -0.9733330 -0.3645801
## 339605 -0.1658138              Luray    MO 0.15193624  1.4805832 -0.3638600
## 339606  0.1008319            Burbank    WA 1.27137555 -0.6544031 -0.3530591
## 339607 -0.3871216               Mesa    ID 0.96301207 -0.4605584 -0.3651910
##                                                  job        dob
## 339602 Chartered legal executive (England and Wales) 1967-05-27
## 339603                      Administrator, education 1939-11-09
## 339604                           Call centre manager 1958-09-20
## 339605                                  Town planner 1966-02-13
## 339606                                      Musician 1981-11-29
## 339607                                  Cartographer 1965-12-15
##                               trans_num merch_lat merch_long  is_fraud
## 339602 a7105564935ea3977dc61ff9ced3bf5e  38.96354 -120.45712 Not Fraud
## 339603 a8310343c189e4a5b6316050d2d6b014  65.62359 -165.18603 Not Fraud
## 339604 bd7071fd5c9510a5594ee196368ac80e  41.97313 -123.55303 Not Fraud
## 339605 9b1f753c79894c9f4b71f04581835ada  39.94684  -91.33333 Not Fraud
## 339606 6c5b7c8add471975aa0fec023b2e8408  46.65834 -119.71505 Not Fraud
## 339607 14392d723bb7737606b2700ac791b7aa  44.47053 -117.08089 Not Fraud
# explore unique values of category column
unique_category <- unique(credit_data$category)
print(unique_category)
##  [1] grocery_pos    entertainment  shopping_pos   misc_pos       shopping_net  
##  [6] gas_transport  misc_net       grocery_net    food_dining    health_fitness
## [11] kids_pets      home           personal_care  travel        
## 14 Levels: entertainment food_dining gas_transport grocery_net ... travel
# statistical summary
summary(credit_data)
##  trans_date_trans_time                    merchant               category     
##  Min.   :2019-01-01 00:00:44.00   Kilback LLC :  1149   gas_transport: 35089  
##  1st Qu.:2019-07-22 21:51:49.00   Cormier LLC :   985   grocery_pos  : 32732  
##  Median :2019-12-31 15:11:23.00   Schumm PLC  :   931   home         : 32516  
##  Mean   :2020-01-20 13:19:14.69   Kuhn LLC    :   896   shopping_pos : 30329  
##  3rd Qu.:2020-07-23 11:22:32.00   Dickinson Lt:   891   kids_pets    : 29704  
##  Max.   :2020-12-31 23:59:24.00   Boyer PLC   :   869   shopping_net : 26379  
##                                   (Other)     :333886   (Other)      :152858  
##       amt                      city            state            lat         
##  Min.   : -0.4304   Phoenix      :  7297   CA     :80495   Min.   :-3.8650  
##  1st Qu.: -0.3772   Fort Washakie:  5116   MO     :54904   1st Qu.:-0.5895  
##  Median : -0.1492   Thompson     :  4386   NE     :34425   Median :-0.0200  
##  Mean   :  0.0000   Superior     :  4383   WY     :27776   Mean   : 0.0000  
##  3rd Qu.:  0.0790   Conway       :  4381   WA     :27040   3rd Qu.: 0.3908  
##  Max.   :178.6193   Centerview   :  4380   OR     :26408   Max.   : 5.2943  
##                     (Other)      :309664   (Other):88559                    
##       long             city_pop                             job        
##  Min.   :-4.35128   Min.   :-0.3655   Surveyor, minerals      :  6589  
##  1st Qu.:-0.74861   1st Qu.:-0.3640   Surveyor, land/geomatics:  5855  
##  Median :-0.03762   Median :-0.3600   Land/geomatics surveyor :  5119  
##  Mean   : 0.00000   Mean   : 0.0000   Insurance broker        :  5108  
##  3rd Qu.: 0.79052   3rd Qu.:-0.2447   Systems analyst         :  4398  
##  Max.   : 1.65942   Max.   : 7.7698   Geoscientist            :  4389  
##                                       (Other)                 :308149  
##       dob              trans_num           merch_lat       merch_long     
##  Min.   :1927-09-09   Length:339607      Min.   :19.03   Min.   :-166.67  
##  1st Qu.:1961-10-24   Class :character   1st Qu.:36.82   1st Qu.:-119.82  
##  Median :1974-03-10   Mode  :character   Median :39.59   Median :-111.04  
##  Mean   :1972-04-03                      Mean   :39.72   Mean   :-110.62  
##  3rd Qu.:1985-08-21                      3rd Qu.:42.19   3rd Qu.:-100.35  
##  Max.   :2001-07-26                      Max.   :67.51   Max.   : -88.63  
##                                                                           
##       is_fraud     
##  Not Fraud:337825  
##  Fraud    :  1782  
##                    
##                    
##                    
##                    
## 
# explore unique values of category column
unique_category <- unique(credit_data$category)
print(unique_category)
##  [1] grocery_pos    entertainment  shopping_pos   misc_pos       shopping_net  
##  [6] gas_transport  misc_net       grocery_net    food_dining    health_fitness
## [11] kids_pets      home           personal_care  travel        
## 14 Levels: entertainment food_dining gas_transport grocery_net ... travel
# table view of fraud summary (0: legitimate transaction, 1: fraud transaction)
fraud_summary_table<-table(credit_data$is_fraud)
print(fraud_summary_table)
## 
## Not Fraud     Fraud 
##    337825      1782
# table view of fraud summary by state
fraud_state_table <-table(credit_data$state,credit_data$is_fraud)
print(fraud_state_table)
##     
##      Not Fraud Fraud
##   AK      2913    50
##   AZ     15298    64
##   CA     80093   402
##   CO     19651   115
##   HI      3633    16
##   ID      8002    33
##   MO     54642   262
##   NE     34209   216
##   NM     23306   121
##   OR     26211   197
##   UT     15296    61
##   WA     26914   126
##   WY     27657   119
# table view of fraud summary by job
fraud_job_table <-table(credit_data$job,credit_data$is_fraud)
print(fraud_job_table)
##                                                    
##                                                     Not Fraud Fraud
##   Accountant, chartered                                     0    11
##   Administrator, education                               2188    15
##   Administrator, local government                        1457     9
##   Advertising account planner                            3639     9
##   Aeronautical engineer                                  2187    14
##   Agricultural consultant                                2190     5
##   Airline pilot                                          2910     6
##   Architect                                              2910    15
##   Architectural technologist                             1458     8
##   Armed forces training and education officer            2914     5
##   Associate Professor                                     729     5
##   Barista                                                2184     9
##   Barrister                                              2909     8
##   Building surveyor                                      1457    12
##   Buyer, industrial                                      2181    11
##   Call centre manager                                    2187     7
##   Careers information officer                               0    12
##   Cartographer                                           2910    11
##   Charity officer                                         728    12
##   Chartered legal executive (England and Wales)          1455     9
##   Chartered public finance accountant                    2190     0
##   Chemical engineer                                       729    11
##   Chief Marketing Officer                                1457     6
##   Chiropodist                                             730    13
##   Civil engineer, contracting                            2910    19
##   Civil Service administrator                             727    12
##   Civil Service fast streamer                             728    11
##   Clinical cytogeneticist                                   0     7
##   Clinical research associate                             728     3
##   Clothing/textile technologist                          3631    15
##   Colour technologist                                    2187    29
##   Commissioning editor                                      0    14
##   Community arts worker                                  1454     7
##   Comptroller                                             727    11
##   Contractor                                             4364     2
##   Counselling psychologist                               2916    15
##   Counsellor                                             2915     9
##   Cytogeneticist                                         2187     5
##   Dealer                                                 3645    19
##   Designer, exhibition/display                           4374     4
##   Development worker, international aid                     0    10
##   Early years teacher                                    2915     8
##   Economist                                               726    11
##   Editor, magazine features                              2179     8
##   Education administrator                                1457    10
##   Education officer, museum                              2912    15
##   Educational psychologist                               3643    18
##   Electronics engineer                                   4369    11
##   Engineer, agricultural                                 2186     9
##   Engineer, automotive                                   2911     8
##   Engineer, biomedical                                   1460    22
##   Engineer, building services                            1458    12
##   Engineer, civil (consulting)                            725     9
##   Engineer, communications                               2190     0
##   Engineer, electronics                                   726     7
##   Engineer, maintenance                                  2184    14
##   Engineer, petroleum                                    1452    13
##   Engineer, production                                   2185    11
##   Engineer, site                                            0    12
##   Exercise physiologist                                   730     4
##   Fine artist                                               0    10
##   Firefighter                                            3643     7
##   Forensic psychologist                                   729    12
##   Freight forwarder                                      2908    12
##   Further education lecturer                             1454    10
##   Futures trader                                         1454     8
##   Geologist, engineering                                 1457     9
##   Geoscientist                                           4371    18
##   Glass blower/designer                                   729    13
##   Health physicist                                       4371     3
##   Health service manager                                 2187     6
##   Historic buildings inspector/conservation officer      3641    12
##   Hotel manager                                           728     9
##   Human resources officer                                2909    23
##   Immigration officer                                    2914    11
##   Industrial/product designer                               0    11
##   Information officer                                       0     8
##   Information systems manager                            2187     9
##   Insurance broker                                       5093    15
##   Intelligence analyst                                   3636     5
##   Investment analyst                                     3644    10
##   Investment banker, corporate                           1454    11
##   IT consultant                                          1454     8
##   Journalist, newspaper                                   728     9
##   Land/geomatics surveyor                                5099    20
##   Landscape architect                                       0     9
##   Learning mentor                                        2183    12
##   Lecturer, higher education                             2915     7
##   Licensed conveyancer                                   2188    10
##   Local government officer                                728     4
##   Location manager                                       2184     9
##   Magazine features editor                               2181     8
##   Marketing executive                                     726    10
##   Materials engineer                                     1459    19
##   Medical technical officer                               726    14
##   Mental health nurse                                    2187     8
##   Metallurgist                                           1459    13
##   Museum education officer                               1459    13
##   Museum/gallery exhibitions officer                     2185     8
##   Music therapist                                        3629    14
##   Musician                                               3644     7
##   Nature conservation officer                             727    16
##   Naval architect                                        3639    24
##   Network engineer                                       2188    24
##   Nurse, children's                                      2914    16
##   Nurse, mental health                                   1455     6
##   Occupational hygienist                                 1457     8
##   Occupational psychologist                              2913    10
##   Osteopath                                              3640    11
##   Petroleum engineer                                     4376     7
##   Pharmacist, hospital                                    729     7
##   Physiotherapist                                        1454     9
##   Pilot, airline                                         2907    17
##   Planning and development surveyor                      2185     7
##   Podiatrist                                             2912    13
##   Private music teacher                                   728    13
##   Product designer                                       2913    11
##   Product/process development scientist                  1452     7
##   Production manager                                     3649     9
##   Public house manager                                   2908     8
##   Public librarian                                       2185    11
##   Public relations account executive                     3629    19
##   Radio broadcast assistant                               729     9
##   Radiographer, diagnostic                                729     5
##   Research officer, political party                      4372     9
##   Research scientist (maths)                             2174    11
##   Research scientist (medical)                              0     8
##   Research scientist (physical sciences)                 2916    23
##   Retail merchandiser                                    1456    11
##   Sales executive                                        2184    11
##   Sales professional, IT                                 2912    14
##   Science writer                                          730     9
##   Scientist, audiological                                3638    21
##   Scientist, marine                                       727    12
##   Scientist, physiological                               2177    12
##   Scientist, research (maths)                            2179     7
##   Set designer                                              0    19
##   Soil scientist                                          729     8
##   Solicitor, Scotland                                     729    11
##   Special educational needs teacher                      4355     7
##   Surveyor, land/geomatics                               5831    24
##   Surveyor, minerals                                     6564    25
##   Surveyor, mining                                       2177    14
##   Systems analyst                                        4370    28
##   Systems developer                                         0     9
##   Tax inspector                                          4371     8
##   Teacher, adult education                                727    10
##   Teacher, early years/pre                                728    11
##   Teaching laboratory technician                          727     3
##   TEFL teacher                                              0    10
##   Telecommunications researcher                          2913     9
##   Television floor manager                                724     5
##   Television/film/video producer                         1456    14
##   Therapist, art                                         3642     8
##   Therapist, horticultural                                728    10
##   Therapist, music                                       1458     8
##   Therapist, occupational                                2907    15
##   Tourist information centre manager                     2912     8
##   Town planner                                           2184    11
##   Video editor                                           1454    12
##   Water engineer                                         4373     2
##   Web designer                                           1458     7
##   Wellsite geologist                                     2182    20
# Overall Summary by is_fraud
isfraud_summary <- credit_data %>%
  group_by(is_fraud) %>%
  summarize (
    mean_amt = mean(amt),
    median_amt = median(amt),
    max_amt = round(max(amt),2),
    min_amt = min(amt),
    total_transactions = n())
print(isfraud_summary)
## # A tibble: 2 × 6
##   is_fraud  mean_amt median_amt max_amt min_amt total_transactions
##   <fct>        <dbl>      <dbl>   <dbl>   <dbl>              <int>
## 1 Not Fraud  -0.0146     -0.150  179.    -0.430             337825
## 2 Fraud       2.77        1.77     8.05  -0.426               1782

3. Plots

description

4. Reference

https://app.datacamp.com/workspace/sample-datasets/dataset-python-credit-card-fraud?searchQuery=cred