Advertisement
monchimon00

9.2.3 Shiny

Apr 24th, 2024
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 7.64 KB | None | 0 0
  1. library(shiny)
  2. library(pROC)
  3. library(plyr)
  4. library(here)
  5.  
  6. shinyUI(fluidPage(
  7.  
  8.   titlePanel(HTML('<div style="text-align: left;"><b>EVALUACION CREDITICIA</b></div>')),
  9.   style = "background-color: #e6ffe6;",
  10.   sidebarLayout(
  11.    
  12.     sidebarPanel(
  13.       column(width = 6,
  14.              numericInput("loanAmount",HTML('<span style="color: black;">MONTO DEL CREDITO</span>'), value = NULL),
  15.              selectInput("paymentFrequency", "FRECUENCIA PAGO NOMINA", choices = c("Semanal", "Catorcenal", "Quincenal", "Mensual"), selected = "Semanal"),
  16.              numericInput("Plazo", "PLAZO DE CREDITO", value = NULL),
  17.              numericInput("Ingresos", "INGRESOS MENSUALES", value = NULL, min = 1),
  18.              numericInput("Deducciones", "DEDUCCIONES MENSUALES", value = NULL, min = 1),
  19.       ),
  20.       column(width = 6,
  21.              numericInput("Edad", "EDAD", value = NULL, min = 1),
  22.              dateInput("Fechaingreso", "FECHA INGRESO LABORAL", value = Sys.Date()),
  23.              selectInput("Empresapagadora", "EMPRESA", choices = c("Accionistas", "Denso", "La Tradicional", "MINCO", "Muebles Krill", "Roan", "Seguridad MG", "Otros"), selected = "Denso"),
  24.              radioButtons("Comisiones", "COMISION CREDITO", choices = c("2%" = 1.02, "3%" = 1.03), selected = NULL),
  25.              actionButton("calculate", "Calcular Probabilidad de Pago")
  26.       )
  27.      
  28.     ),
  29.    
  30.     mainPanel(
  31.       column(width = 6,
  32.              textOutput("Predictiontext"),
  33.              textOutput("optimalPlazoOutput")
  34.       ),
  35.       style = "background-color: #f0f8ff;"
  36.     )
  37.   )
  38. ))
  39. library(shiny)
  40.  
  41. shinyServer(function(input, output) {
  42.  
  43.   observeEvent(input$calculate, {
  44.     monto_prestamoo <- input$loanAmount
  45.     ingresos <- input$Ingresos
  46.     deducciones <- input$Deducciones
  47.     edad <- input$Edad
  48.     plazo_credito <- input$Plazo
  49.     fecha_inicio <- input$Fechaingreso
  50.     empresa_pagadora <- input$Empresapagadora
  51.     frecuencia_pago <- input$paymentFrequency
  52.     comisiones <- as.numeric(input$Comisiones)
  53.    
  54.     # Ajusta la tasa de interés según la frecuencia de pago
  55.     if (frecuencia_pago == "Semanal") {
  56.       plazo_credito_m <- plazo_credito / 360 * 7
  57.       dias_entre_pagos <- 7
  58.     } else if (frecuencia_pago == "Catorcenal") {
  59.       plazo_credito_m <- plazo_credito / 360 * 14
  60.       dias_entre_pagos <- 14
  61.     } else if (frecuencia_pago == "Quincenal") {
  62.       plazo_credito_m <- plazo_credito / 360 * 15
  63.       dias_entre_pagos <- 15
  64.     } else if (frecuencia_pago == "Mensual") {
  65.       plazo_credito_m <- plazo_credito / 360 * 30
  66.       dias_entre_pagos <- 30
  67.     }
  68.    
  69.     #Obtener Antiguedad
  70.     antiguedad <- as.numeric(Sys.Date()-fecha_inicio) / 360
  71.     sueldo_neto <- ingresos - deducciones
  72.    
  73.     library(pROC)
  74.    
  75.     # Construct the path to the CSV file
  76.     partial_filename <- paste0("FlexiCredit - Datos Modelo ")
  77.    
  78.     # Encontrar archivos que coincidan con la parte conocida del nombre
  79.     matching_files <- list.files(path = dirname(partial_filename), pattern = basename(partial_filename))
  80.    
  81.     # Mostrar los archivos coincidentes encontrados
  82.     print(matching_files)
  83.    
  84.     wd <- getwd()
  85.     data_path <- file.path(wd, matching_files)
  86.     data_flexi <- read.csv(file = data_path)
  87.    
  88.     data_flexi$Impago <- as.factor(data_flexi$Impago)
  89.     data_flexi$Periodicidad <- as.factor(data_flexi$Periodicidad)
  90.     data_flexi$Sexo <- as.factor(data_flexi$Sexo)
  91.     data_flexi$Empresa_Pagadora <- as.factor(data_flexi$Empresa_Pagadora)
  92.    
  93.     order <- c('Semanal','Catorcenal','Quincenal','Mensual')
  94.     data_flexi$Periodicidad <- factor(data_flexi$Periodicidad, levels = order)
  95.     levels(data_flexi$Periodicidad)
  96.    
  97.     set.seed(450)
  98.     index_train <- cbind(runif(1 : nrow(data_flexi), 0 , 1),c(1 : nrow(data_flexi)))
  99.     index_train <- order(index_train[, 1])
  100.     index_train <- index_train[1: (2/3 * nrow(data_flexi))]
  101.     training_set <- data_flexi[index_train, ]
  102.     test_set <- data_flexi[-index_train, ]
  103.    
  104.    
  105.     log_model_full  <- glm(Impago ~ PeriodicidadDos + Empresa_Pagadora + Edad  + Antiguedad + Sueldo_Neto, family = "binomial",
  106.                            data = training_set)
  107.    
  108.     Nuevo_Contrato <- data.frame(Sueldo_Neto = sueldo_neto, Antiguedad = antiguedad, PeriodicidadDos = plazo_credito_m, Edad = edad, Empresa_Pagadora = empresa_pagadora)
  109.     my_prediction <- predict(log_model_full, Nuevo_Contrato, type = "response")
  110.     my_prediction <- unname(my_prediction)
  111.    
  112.     # Amortizacion data
  113.     # Ajusta la tasa de interés según la frecuencia de pago
  114.    
  115.     if (empresa_pagadora == "Mondelez") {
  116.       tasa_interes_anual <- .63
  117.     } else if (empresa_pagadora == "Ladrillera") {
  118.       tasa_interes_anual <- .63
  119.     } else {
  120.       tasa_interes_anual <- .60
  121.     }
  122.    
  123.     if (frecuencia_pago == "Semanal") {
  124.       tasa_interes_anual <- tasa_interes_anual / 360 * 7 * 1.16
  125.       dias_entre_pagos <- 7
  126.     } else if (frecuencia_pago == "Catorcenal") {
  127.       tasa_interes_anual <- tasa_interes_anual / 360 * 14 * 1.16
  128.       dias_entre_pagos <- 14
  129.     } else if (frecuencia_pago == "Quincenal") {
  130.       tasa_interes_anual <- tasa_interes_anual / 360 * 15 * 1.16
  131.       dias_entre_pagos <- 15
  132.     } else if (frecuencia_pago == "Mensual") {
  133.       tasa_interes_anual <- tasa_interes_anual / 360 * 30 * 1.16
  134.       dias_entre_pagos <- 30
  135.     }
  136.    
  137.     tasa_interes <- tasa_interes_anual
  138.     plazo_prestamo <- plazo_credito
  139.    
  140.     pago_mensual <- (monto_prestamoo * comisiones) * ((tasa_interes) / (1 - (1 + tasa_interes)^ (-plazo_prestamo)))
  141.    
  142.     #ajustes
  143.     # Assuming plazo_values is a vector of values you want to test
  144.     plazo_values <- seq(-20, 10, by = .01)  # Adjust max_plazo_value as needed
  145.    
  146.     # Create an empty vector to store the optimal values
  147.     optimal_plazo <- numeric(length(plazo_values))
  148.    
  149.    
  150.     # Loop over each value of plazo_credito_m
  151.     for (i in seq_along(plazo_values)) {
  152.       Nuevo_Contrato$PeriodicidadDos <- plazo_values[i]
  153.      
  154.       prediccion_2 <- predict(log_model_full, Nuevo_Contrato, type = "response")
  155.       prediccion_2 <- unname(prediccion_2)
  156.      
  157.       # Check if the prediction is greater than or equal to 0.35
  158.       if (any(prediccion_2 >= 0.30)) {
  159.         break  # Exit the loop if the condition is met
  160.       }
  161.       # If the condition is not met, update optimal_plazo
  162.       optimal_plazo <- plazo_values[i]
  163.     }
  164.    
  165.     if (frecuencia_pago == "Semanal") {
  166.       optimal_plazo <- optimal_plazo * 360 / 7
  167.     } else if (frecuencia_pago == "Catorcenal") {
  168.       optimal_plazo <- optimal_plazo * 360 / 14
  169.     } else if (frecuencia_pago == "Quincenal") {
  170.       optimal_plazo <- optimal_plazo * 360 / 15
  171.     } else if (frecuencia_pago == "Mensual") {
  172.       optimal_plazo <- optimal_plazo * 360 / 30
  173.     }
  174.    
  175.     optimal_plazo
  176.     Nuevo_Contrato
  177.     #ajustes
  178.    
  179.     output$optimalPlazoOutput <- renderText({
  180.       if(optimal_plazo > 0){ paste("PlazoMaximo", floor(optimal_plazo))}
  181.       else { paste("Su plazo maximo sugiere valores negativos")
  182.       }
  183.     })
  184.    
  185.    
  186.     # Display the prediction
  187.     output$Predictiontext <- renderText({
  188.       prediction_value <- round(my_prediction, 4) * 100
  189.      
  190.       if (prediction_value >= 30) {
  191.         paste("Prediction:", prediction_value, "% Rechazado")
  192.       } else if(ingresos - deducciones <= 0) {
  193.         paste("Rechazado")
  194.       } else if(edad < 18) {
  195.         paste("Rechazado")
  196.       } else if(monto_prestamoo > 75000 || monto_prestamoo < 2000){
  197.         paste("Rechazado")
  198.       } else {
  199.         paste(prediction_value, "% Aceptado. Pago ", frecuencia_pago, ": $", round(pago_mensual, 2))
  200.       }
  201.  
  202.     })
  203.    
  204.   })
  205. })
  206.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement