Browse Source

Auto prediction and forecasting added

main
Asitav Sen 4 years ago
parent
commit
bdb1f315df
  1. 4
      .Rproj.user/178A6739/sources/prop/A1AE5A83
  2. 8
      .Rproj.user/178A6739/sources/session-99529da2/FE6BB309
  3. 328
      .Rproj.user/178A6739/sources/session-99529da2/FE6BB309-contents
  4. 328
      app.R

4
.Rproj.user/178A6739/sources/prop/A1AE5A83

@ -1,6 +1,6 @@
{ {
"source_window_id": "", "source_window_id": "",
"Source": "Source", "Source": "Source",
"cursorPosition": "8,11", "cursorPosition": "27,0",
"scrollLine": "0" "scrollLine": "4"
} }

8
.Rproj.user/178A6739/sources/session-99529da2/FE6BB309

@ -12,15 +12,15 @@
"properties": { "properties": {
"source_window_id": "", "source_window_id": "",
"Source": "Source", "Source": "Source",
"cursorPosition": "8,11", "cursorPosition": "27,0",
"scrollLine": "0" "scrollLine": "4"
}, },
"folds": "", "folds": "",
"lastKnownWriteTime": 1686049765, "lastKnownWriteTime": 1686050003,
"encoding": "UTF-8", "encoding": "UTF-8",
"collab_server": "", "collab_server": "",
"source_window": "", "source_window": "",
"last_content_update": 1686049765357, "last_content_update": 1686050003754,
"read_only": false, "read_only": false,
"read_only_alternatives": [] "read_only_alternatives": []
} }

328
.Rproj.user/178A6739/sources/session-99529da2/FE6BB309-contents

@ -30,30 +30,27 @@ source("modals.R")
# Define UI for application # Define UI for application
ui <- navbarPage( ui <- navbarPage(theme = shinytheme("cosmo"),
theme = shinytheme("cosmo"), title = "LoanRisk",
title = "LoanRisk", panel1)
panel1
)
# Define server logic required to draw a histogram # Define server logic required to draw a histogram
server <- function(input, output) { server <- function(input, output) {
# Data # Data
# Some reactive values # Some reactive values
collateral.dt<-reactiveVal() collateral.dt <- reactiveVal()
transaction.dt<-reactiveVal() transaction.dt <- reactiveVal()
# Adding initial data to reactive values # Adding initial data to reactive values
collateral.dt(read.csv("./data/collateral.csv") ) collateral.dt(read.csv("./data/collateral.csv"))
transaction.dt(read.csv("./data/transactions.csv") ) transaction.dt(read.csv("./data/transactions.csv"))
# Transforming Data # Transforming Data
new.data <- reactive({ new.data <- reactive({
ndt<- transaction.dt() ndt <- transaction.dt()
withProgress(message = "Trying to read", withProgress(message = "Trying to read",
detail = "Hope the handwriting is legible!", detail = "Hope the handwriting is legible!",
value = 0, value = 0,
@ -68,12 +65,8 @@ server <- function(input, output) {
report_date = ymd(report_date) report_date = ymd(report_date)
) %>% ) %>%
# Add age of loan, loan tenure in months, which are compulsory parameters # Add age of loan, loan tenure in months, which are compulsory parameters
mutate(age_of_asset_months = round(as.numeric( mutate(age_of_asset_months = round(as.numeric(report_date - origination_date) / 30)) %>%
report_date - origination_date mutate(loan_tenure_months = round(as.numeric(maturity_date - origination_date) / 30)) %>%
) / 30)) %>%
mutate(loan_tenure_months = round(as.numeric(
maturity_date - origination_date
) / 30)) %>%
group_by(id) %>% group_by(id) %>%
# Arranging to avoid mistakes in lag # Arranging to avoid mistakes in lag
arrange(report_date) %>% arrange(report_date) %>%
@ -104,7 +97,6 @@ server <- function(input, output) {
# Show uploaded data # Show uploaded data
output$up_data <- renderDataTable({ output$up_data <- renderDataTable({
DT::datatable( DT::datatable(
new.data(), new.data(),
extensions = c("Buttons"), extensions = c("Buttons"),
@ -114,15 +106,17 @@ server <- function(input, output) {
dom = 'Bfrtip', dom = 'Bfrtip',
filter = list(position = 'top', clear = FALSE), filter = list(position = 'top', clear = FALSE),
buttons = list( buttons = list(
list(extend = "csv", text = "Download Visible", filename = "page", list(
exportOptions = list( extend = "csv",
modifier = list(page = "current") text = "Download Visible",
) filename = "page",
exportOptions = list(modifier = list(page = "current"))
), ),
list(extend = "csv", text = "Download All", filename = "data", list(
exportOptions = list( extend = "csv",
modifier = list(page = "all") text = "Download All",
) filename = "data",
exportOptions = list(modifier = list(page = "all"))
) )
) )
) )
@ -146,7 +140,7 @@ server <- function(input, output) {
databaseID <- "IFS" databaseID <- "IFS"
startdate = min(new.data()$report_date) startdate = min(new.data()$report_date)
enddate = max(new.data()$report_date) enddate = max(new.data()$report_date)
country = countries[countries$Country == input$country,]$Alpha.2.code country = countries[countries$Country == input$country, ]$Alpha.2.code
withProgress(message = "Extracting data from IMF", withProgress(message = "Extracting data from IMF",
detail = "Hope their server is up!", detail = "Hope their server is up!",
value = 0, value = 0,
@ -154,7 +148,7 @@ server <- function(input, output) {
setProgress(value = 1, message = "Trying to reach..") setProgress(value = 1, message = "Trying to reach..")
print(country) print(country)
imf.data <- tryCatch( imf.data <- tryCatch(
expr={ expr = {
imf_data( imf_data(
databaseID, databaseID,
c("NGDP_NSA_XDC", c("NGDP_NSA_XDC",
@ -166,21 +160,25 @@ server <- function(input, output) {
return_raw = FALSE, return_raw = FALSE,
print_url = T, print_url = T,
times = 3 times = 3
) )
}, },
error = function(e){ # Specifying error message error = function(e) {
# Specifying error message
showModal( showModal(
modalDialog( modalDialog(
"Error in IMF database. Sorry for the inconvenience. Can you please try again later?" "Error in IMF database. Sorry for the inconvenience. Can you please try again later?"
) )
) )
message("Error with IMF database. This is usually temporary. Sorry for the inconvenience. Please try again later.") message(
"Error with IMF database. This is usually temporary. Sorry for the inconvenience. Please try again later."
)
}, },
finally = { # Specifying final message finally = {
# Specifying final message
message("Error with IMF database. Please try again later.") message("Error with IMF database. Please try again later.")
} }
) )
setProgress(value = 2, message = "Done") setProgress(value = 2, message = "Done")
}) })
@ -212,7 +210,7 @@ server <- function(input, output) {
# removing rows with no macroeconomic data # removing rows with no macroeconomic data
dataset_eco <- dataset_eco <-
dataset_with_eco[!is.na(dataset_with_eco$gdp_lag) & dataset_with_eco[!is.na(dataset_with_eco$gdp_lag) &
!is.na(dataset_with_eco$prices_lag), ] !is.na(dataset_with_eco$prices_lag),]
setProgress(value = 2, message = "working..") setProgress(value = 2, message = "working..")
}) })
@ -284,15 +282,17 @@ server <- function(input, output) {
dom = 'Bfrtip', dom = 'Bfrtip',
filter = list(position = 'top', clear = FALSE), filter = list(position = 'top', clear = FALSE),
buttons = list( buttons = list(
list(extend = "csv", text = "Download Visible", filename = "page", list(
exportOptions = list( extend = "csv",
modifier = list(page = "current") text = "Download Visible",
) filename = "page",
exportOptions = list(modifier = list(page = "current"))
), ),
list(extend = "csv", text = "Download All", filename = "data", list(
exportOptions = list( extend = "csv",
modifier = list(page = "all") text = "Download All",
) filename = "data",
exportOptions = list(modifier = list(page = "all"))
) )
) )
) )
@ -325,8 +325,9 @@ server <- function(input, output) {
# Model Selection. Using functions. In production these are to be converted to APIs # Model Selection. Using functions. In production these are to be converted to APIs
selected_model <- reactive({ selected_model <- reactive({
req(input$start_model_selection,!is.null(dataset_with_eco())) req(input$start_model_selection,
model_sel(dff=dataset_with_eco()) !is.null(dataset_with_eco()))
model_sel(dff = dataset_with_eco())
}) })
# Preparing tables with predictions. Using functions. In production these are to be converted to APIs # Preparing tables with predictions. Using functions. In production these are to be converted to APIs
@ -334,11 +335,13 @@ server <- function(input, output) {
input$start_model_selection input$start_model_selection
req(!is.null(selected_model())) req(!is.null(selected_model()))
z<-predic_t(dff=dataset_with_eco(), z <- predic_t(
gdpfor=gdp.forecast(), dff = dataset_with_eco(),
prfor=pats.forecast(), gdpfor = gdp.forecast(),
maxdate=maxdate(), prfor = pats.forecast(),
final.model= selected_model()) maxdate = maxdate(),
final.model = selected_model()
)
z z
}) })
@ -368,11 +371,9 @@ server <- function(input, output) {
) )
)) %>% )) %>%
filter(!is.na(name)) %>% filter(!is.na(name)) %>%
ggplot(aes( ggplot(aes(x = name,
x = name, y = value,
y = value, fill = name)) +
fill = name
)) +
geom_violin() + geom_violin() +
geom_boxplot(width = 0.1, geom_boxplot(width = 0.1,
color = "black", color = "black",
@ -459,7 +460,7 @@ server <- function(input, output) {
output$exposure_on_default <- renderPlot({ output$exposure_on_default <- renderPlot({
input$update input$update
req(nrow(predicted_table())>0) req(nrow(predicted_table()) > 0)
discount_rate_pa <- input$discount_rate discount_rate_pa <- input$discount_rate
withProgress(message = "Plotting", withProgress(message = "Plotting",
@ -550,9 +551,7 @@ server <- function(input, output) {
"Please click an drag to check the probabilities between ranges of possible loss." "Please click an drag to check the probabilities between ranges of possible loss."
), ),
plotOutput("simres", plotOutput("simres",
brush = brushOpts( brush = brushOpts(id = "sim_res_sel", direction = "x")),
id = "sim_res_sel", direction = "x"
)),
verbatimTextOutput("cumprob") verbatimTextOutput("cumprob")
), ),
column( column(
@ -571,10 +570,10 @@ server <- function(input, output) {
# }) # })
simdata <- reactive({ simdata <- reactive({
req(nrow(predicted_table())>0) req(nrow(predicted_table()) > 0)
req(!is.null(input$discount_rate)) req(!is.null(input$discount_rate))
input$update input$update
collateral<-collateral.dt() collateral <- collateral.dt()
discount_rate_pa <- input$discount_rate discount_rate_pa <- input$discount_rate
withProgress(message = "Monte Carlo Simulation", withProgress(message = "Monte Carlo Simulation",
detail = "1000 simulations", detail = "1000 simulations",
@ -647,7 +646,7 @@ server <- function(input, output) {
}) })
output$cumprob <- renderText({ output$cumprob <- renderText({
req(!is.null(input$sim_res_sel), !is.null(simresdata())) req(!is.null(input$sim_res_sel),!is.null(simresdata()))
hist.pro <- simresdata() hist.pro <- simresdata()
pro_dens <- data.frame(hist.pro$x, hist.pro$y) pro_dens <- data.frame(hist.pro$x, hist.pro$y)
res <- brushedPoints(pro_dens, input$sim_res_sel) res <- brushedPoints(pro_dens, input$sim_res_sel)
@ -751,29 +750,28 @@ server <- function(input, output) {
# File uploading Module # File uploading Module
observeEvent(input$uploadnew, { observeEvent(input$uploadnew, {
showModal( showModal(modal1)
modal1
)
}) })
observeEvent(input$closemodal1,{ observeEvent(input$closemodal1, {
removeModal() removeModal()
}) })
observeEvent(input$closemodal2,{ observeEvent(input$closemodal2, {
removeModal() removeModal()
}) })
# Uploading temp file and collecting info about the columns # Uploading temp file and collecting info about the columns
observeEvent(input$uploadfiles,{ observeEvent(input$uploadfiles, {
df.tr <- reactive({ df.tr <- reactive({
inFile <- input$transaction inFile <- input$transaction
if (is.null(inFile)) if (is.null(inFile))
return(NULL) return(NULL)
df <- read.csv(inFile$datapath, df <- read.csv(
header = input$header, inFile$datapath,
sep = input$sep, header = input$header,
quote = input$quote) sep = input$sep,
quote = input$quote
)
df df
}) })
@ -781,98 +779,130 @@ server <- function(input, output) {
inFile <- input$collaterals inFile <- input$collaterals
if (is.null(inFile)) if (is.null(inFile))
return(NULL) return(NULL)
df <- read.csv(inFile$datapath, df <- read.csv(
header = input$header, inFile$datapath,
sep = input$sep, header = input$header,
quote = input$quote) sep = input$sep,
quote = input$quote
)
df df
}) })
updateVarSelectInput("collateralid","Select id column", df.c(),session = getDefaultReactiveDomain()) updateVarSelectInput("collateralid", "Select id column", df.c(), session = getDefaultReactiveDomain())
updateVarSelectInput("collateralvalue","Select Collateral value column", df.c(),session = getDefaultReactiveDomain()) updateVarSelectInput("collateralvalue",
updateVarSelectInput("reportdate","Select report date column", df.tr(),session = getDefaultReactiveDomain()) "Select Collateral value column",
updateVarSelectInput("origindate","Select origin date column", df.tr(),session = getDefaultReactiveDomain()) df.c(),
updateVarSelectInput("maturitydate","Select maturity date column", df.tr(),session = getDefaultReactiveDomain()) session = getDefaultReactiveDomain())
updateVarSelectInput("assettype","Select asset classifier column", df.tr(),session = getDefaultReactiveDomain()) updateVarSelectInput("reportdate",
updateVarSelectInput("customertype","Select customer classifier column", df.tr(),session = getDefaultReactiveDomain()) "Select report date column",
updateVarSelectInput("otherfact","Select any other classifier column", df.tr(),session = getDefaultReactiveDomain()) df.tr(),
updateVarSelectInput("bureauscore","Select bureau score column", df.tr(),session = getDefaultReactiveDomain()) session = getDefaultReactiveDomain())
updateVarSelectInput("balance","Select asset balance column", df.tr(),session = getDefaultReactiveDomain()) updateVarSelectInput("origindate",
updateVarSelectInput("status","Select loan status", df.tr(),session = getDefaultReactiveDomain()) "Select origin date column",
updateVarSelectInput("defaultflag","Select default flag column", df.tr(),session = getDefaultReactiveDomain()) df.tr(),
updateVarSelectInput("transid","Select id column", df.tr(),session = getDefaultReactiveDomain()) session = getDefaultReactiveDomain())
updateVarSelectInput("maturitydate",
"Select maturity date column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("assettype",
"Select asset classifier column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("customertype",
"Select customer classifier column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("otherfact",
"Select any other classifier column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("bureauscore",
"Select bureau score column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("balance",
"Select asset balance column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("status", "Select loan status", df.tr(), session = getDefaultReactiveDomain())
updateVarSelectInput("defaultflag",
"Select default flag column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("transid", "Select id column", df.tr(), session = getDefaultReactiveDomain())
}) })
# Modal 2 # Modal 2
observeEvent(input$uploadfiles, { observeEvent(input$uploadfiles, {
showModal( showModal(modal2)
modal2
)
}) })
observeEvent(input$confirmupload,{ observeEvent(input$confirmupload, {
transaction.dt( transaction.dt({
{ df <- read.csv(
df <- read.csv(input$transaction$datapath, input$transaction$datapath,
header = input$header, header = input$header,
sep = input$sep, sep = input$sep,
quote = input$quote) quote = input$quote
head(df) )
head(df)
df<-
df %>% df <-
rename(report_date=input$reportdate, df %>%
origination_date=input$origindate, rename(
maturity_date=input$maturitydate, report_date = input$reportdate,
asset_type=input$assettype, origination_date = input$origindate,
customer_type=input$customertype, maturity_date = input$maturitydate,
bureau_score_orig=input$bureauscore, asset_type = input$assettype,
balance=input$balance, customer_type = input$customertype,
loan_status=input$status, bureau_score_orig = input$bureauscore,
default_flag=input$defaultflag, balance = input$balance,
id=input$transid) loan_status = input$status,
default_flag = input$defaultflag,
if(input$dateformat=="ymd"){ id = input$transid
df$report_date<-ymd(df$report_date) )
df$origination_date<-ymd(df$origination_date)
df$maturity_date<-ymd(df$maturity_date) if (input$dateformat == "ymd") {
} else { df$report_date <- ymd(df$report_date)
df$report_date<-dmy(df$report_date) df$origination_date <- ymd(df$origination_date)
df$origination_date<-dmy(df$origination_date) df$maturity_date <- ymd(df$maturity_date)
df$maturity_date<-dmy(df$maturity_date) } else {
} df$report_date <- dmy(df$report_date)
df$origination_date <- dmy(df$origination_date)
df$loan_status<-as.integer(df$loan_status) df$maturity_date <- dmy(df$maturity_date)
}
# Covert to factors
df$asset_type<-as.factor(df$asset_type) df$loan_status <- as.integer(df$loan_status)
df$customer_type<-as.factor(df$customer_type)
if(!is.null(input$otherfact)){ # Covert to factors
for(i in 1:length(input$otherfact)){ df$asset_type <- as.factor(df$asset_type)
df$input$otherfact[i]<-as.factor(df$input$otherfact[i]) df$customer_type <- as.factor(df$customer_type)
} if (!is.null(input$otherfact)) {
for (i in 1:length(input$otherfact)) {
df$input$otherfact[i] <- as.factor(df$input$otherfact[i])
} }
df
} }
)
df
})
collateral.dt( collateral.dt({
{ df <- read.csv(
df <- read.csv(input$collaterals$datapath, input$collaterals$datapath,
header = input$header, header = input$header,
sep = input$sep, sep = input$sep,
quote = input$quote) quote = input$quote
df<- )
df %>% df <-
rename(id=input$collateralid, df %>%
collateral=input$collateralvalue) rename(id = input$collateralid,
df collateral = input$collateralvalue)
} df
) })
removeModal() removeModal()
}) })

328
app.R

@ -30,30 +30,27 @@ source("modals.R")
# Define UI for application # Define UI for application
ui <- navbarPage( ui <- navbarPage(theme = shinytheme("cosmo"),
theme = shinytheme("cosmo"), title = "LoanRisk",
title = "LoanRisk", panel1)
panel1
)
# Define server logic required to draw a histogram # Define server logic required to draw a histogram
server <- function(input, output) { server <- function(input, output) {
# Data # Data
# Some reactive values # Some reactive values
collateral.dt<-reactiveVal() collateral.dt <- reactiveVal()
transaction.dt<-reactiveVal() transaction.dt <- reactiveVal()
# Adding initial data to reactive values # Adding initial data to reactive values
collateral.dt(read.csv("./data/collateral.csv") ) collateral.dt(read.csv("./data/collateral.csv"))
transaction.dt(read.csv("./data/transactions.csv") ) transaction.dt(read.csv("./data/transactions.csv"))
# Transforming Data # Transforming Data
new.data <- reactive({ new.data <- reactive({
ndt<- transaction.dt() ndt <- transaction.dt()
withProgress(message = "Trying to read", withProgress(message = "Trying to read",
detail = "Hope the handwriting is legible!", detail = "Hope the handwriting is legible!",
value = 0, value = 0,
@ -68,12 +65,8 @@ server <- function(input, output) {
report_date = ymd(report_date) report_date = ymd(report_date)
) %>% ) %>%
# Add age of loan, loan tenure in months, which are compulsory parameters # Add age of loan, loan tenure in months, which are compulsory parameters
mutate(age_of_asset_months = round(as.numeric( mutate(age_of_asset_months = round(as.numeric(report_date - origination_date) / 30)) %>%
report_date - origination_date mutate(loan_tenure_months = round(as.numeric(maturity_date - origination_date) / 30)) %>%
) / 30)) %>%
mutate(loan_tenure_months = round(as.numeric(
maturity_date - origination_date
) / 30)) %>%
group_by(id) %>% group_by(id) %>%
# Arranging to avoid mistakes in lag # Arranging to avoid mistakes in lag
arrange(report_date) %>% arrange(report_date) %>%
@ -104,7 +97,6 @@ server <- function(input, output) {
# Show uploaded data # Show uploaded data
output$up_data <- renderDataTable({ output$up_data <- renderDataTable({
DT::datatable( DT::datatable(
new.data(), new.data(),
extensions = c("Buttons"), extensions = c("Buttons"),
@ -114,15 +106,17 @@ server <- function(input, output) {
dom = 'Bfrtip', dom = 'Bfrtip',
filter = list(position = 'top', clear = FALSE), filter = list(position = 'top', clear = FALSE),
buttons = list( buttons = list(
list(extend = "csv", text = "Download Visible", filename = "page", list(
exportOptions = list( extend = "csv",
modifier = list(page = "current") text = "Download Visible",
) filename = "page",
exportOptions = list(modifier = list(page = "current"))
), ),
list(extend = "csv", text = "Download All", filename = "data", list(
exportOptions = list( extend = "csv",
modifier = list(page = "all") text = "Download All",
) filename = "data",
exportOptions = list(modifier = list(page = "all"))
) )
) )
) )
@ -146,7 +140,7 @@ server <- function(input, output) {
databaseID <- "IFS" databaseID <- "IFS"
startdate = min(new.data()$report_date) startdate = min(new.data()$report_date)
enddate = max(new.data()$report_date) enddate = max(new.data()$report_date)
country = countries[countries$Country == input$country,]$Alpha.2.code country = countries[countries$Country == input$country, ]$Alpha.2.code
withProgress(message = "Extracting data from IMF", withProgress(message = "Extracting data from IMF",
detail = "Hope their server is up!", detail = "Hope their server is up!",
value = 0, value = 0,
@ -154,7 +148,7 @@ server <- function(input, output) {
setProgress(value = 1, message = "Trying to reach..") setProgress(value = 1, message = "Trying to reach..")
print(country) print(country)
imf.data <- tryCatch( imf.data <- tryCatch(
expr={ expr = {
imf_data( imf_data(
databaseID, databaseID,
c("NGDP_NSA_XDC", c("NGDP_NSA_XDC",
@ -166,21 +160,25 @@ server <- function(input, output) {
return_raw = FALSE, return_raw = FALSE,
print_url = T, print_url = T,
times = 3 times = 3
) )
}, },
error = function(e){ # Specifying error message error = function(e) {
# Specifying error message
showModal( showModal(
modalDialog( modalDialog(
"Error in IMF database. Sorry for the inconvenience. Can you please try again later?" "Error in IMF database. Sorry for the inconvenience. Can you please try again later?"
) )
) )
message("Error with IMF database. This is usually temporary. Sorry for the inconvenience. Please try again later.") message(
"Error with IMF database. This is usually temporary. Sorry for the inconvenience. Please try again later."
)
}, },
finally = { # Specifying final message finally = {
# Specifying final message
message("Error with IMF database. Please try again later.") message("Error with IMF database. Please try again later.")
} }
) )
setProgress(value = 2, message = "Done") setProgress(value = 2, message = "Done")
}) })
@ -212,7 +210,7 @@ server <- function(input, output) {
# removing rows with no macroeconomic data # removing rows with no macroeconomic data
dataset_eco <- dataset_eco <-
dataset_with_eco[!is.na(dataset_with_eco$gdp_lag) & dataset_with_eco[!is.na(dataset_with_eco$gdp_lag) &
!is.na(dataset_with_eco$prices_lag), ] !is.na(dataset_with_eco$prices_lag),]
setProgress(value = 2, message = "working..") setProgress(value = 2, message = "working..")
}) })
@ -284,15 +282,17 @@ server <- function(input, output) {
dom = 'Bfrtip', dom = 'Bfrtip',
filter = list(position = 'top', clear = FALSE), filter = list(position = 'top', clear = FALSE),
buttons = list( buttons = list(
list(extend = "csv", text = "Download Visible", filename = "page", list(
exportOptions = list( extend = "csv",
modifier = list(page = "current") text = "Download Visible",
) filename = "page",
exportOptions = list(modifier = list(page = "current"))
), ),
list(extend = "csv", text = "Download All", filename = "data", list(
exportOptions = list( extend = "csv",
modifier = list(page = "all") text = "Download All",
) filename = "data",
exportOptions = list(modifier = list(page = "all"))
) )
) )
) )
@ -325,8 +325,9 @@ server <- function(input, output) {
# Model Selection. Using functions. In production these are to be converted to APIs # Model Selection. Using functions. In production these are to be converted to APIs
selected_model <- reactive({ selected_model <- reactive({
req(input$start_model_selection,!is.null(dataset_with_eco())) req(input$start_model_selection,
model_sel(dff=dataset_with_eco()) !is.null(dataset_with_eco()))
model_sel(dff = dataset_with_eco())
}) })
# Preparing tables with predictions. Using functions. In production these are to be converted to APIs # Preparing tables with predictions. Using functions. In production these are to be converted to APIs
@ -334,11 +335,13 @@ server <- function(input, output) {
input$start_model_selection input$start_model_selection
req(!is.null(selected_model())) req(!is.null(selected_model()))
z<-predic_t(dff=dataset_with_eco(), z <- predic_t(
gdpfor=gdp.forecast(), dff = dataset_with_eco(),
prfor=pats.forecast(), gdpfor = gdp.forecast(),
maxdate=maxdate(), prfor = pats.forecast(),
final.model= selected_model()) maxdate = maxdate(),
final.model = selected_model()
)
z z
}) })
@ -368,11 +371,9 @@ server <- function(input, output) {
) )
)) %>% )) %>%
filter(!is.na(name)) %>% filter(!is.na(name)) %>%
ggplot(aes( ggplot(aes(x = name,
x = name, y = value,
y = value, fill = name)) +
fill = name
)) +
geom_violin() + geom_violin() +
geom_boxplot(width = 0.1, geom_boxplot(width = 0.1,
color = "black", color = "black",
@ -459,7 +460,7 @@ server <- function(input, output) {
output$exposure_on_default <- renderPlot({ output$exposure_on_default <- renderPlot({
input$update input$update
req(nrow(predicted_table())>0) req(nrow(predicted_table()) > 0)
discount_rate_pa <- input$discount_rate discount_rate_pa <- input$discount_rate
withProgress(message = "Plotting", withProgress(message = "Plotting",
@ -550,9 +551,7 @@ server <- function(input, output) {
"Please click an drag to check the probabilities between ranges of possible loss." "Please click an drag to check the probabilities between ranges of possible loss."
), ),
plotOutput("simres", plotOutput("simres",
brush = brushOpts( brush = brushOpts(id = "sim_res_sel", direction = "x")),
id = "sim_res_sel", direction = "x"
)),
verbatimTextOutput("cumprob") verbatimTextOutput("cumprob")
), ),
column( column(
@ -571,10 +570,10 @@ server <- function(input, output) {
# }) # })
simdata <- reactive({ simdata <- reactive({
req(nrow(predicted_table())>0) req(nrow(predicted_table()) > 0)
req(!is.null(input$discount_rate)) req(!is.null(input$discount_rate))
input$update input$update
collateral<-collateral.dt() collateral <- collateral.dt()
discount_rate_pa <- input$discount_rate discount_rate_pa <- input$discount_rate
withProgress(message = "Monte Carlo Simulation", withProgress(message = "Monte Carlo Simulation",
detail = "1000 simulations", detail = "1000 simulations",
@ -647,7 +646,7 @@ server <- function(input, output) {
}) })
output$cumprob <- renderText({ output$cumprob <- renderText({
req(!is.null(input$sim_res_sel), !is.null(simresdata())) req(!is.null(input$sim_res_sel),!is.null(simresdata()))
hist.pro <- simresdata() hist.pro <- simresdata()
pro_dens <- data.frame(hist.pro$x, hist.pro$y) pro_dens <- data.frame(hist.pro$x, hist.pro$y)
res <- brushedPoints(pro_dens, input$sim_res_sel) res <- brushedPoints(pro_dens, input$sim_res_sel)
@ -751,29 +750,28 @@ server <- function(input, output) {
# File uploading Module # File uploading Module
observeEvent(input$uploadnew, { observeEvent(input$uploadnew, {
showModal( showModal(modal1)
modal1
)
}) })
observeEvent(input$closemodal1,{ observeEvent(input$closemodal1, {
removeModal() removeModal()
}) })
observeEvent(input$closemodal2,{ observeEvent(input$closemodal2, {
removeModal() removeModal()
}) })
# Uploading temp file and collecting info about the columns # Uploading temp file and collecting info about the columns
observeEvent(input$uploadfiles,{ observeEvent(input$uploadfiles, {
df.tr <- reactive({ df.tr <- reactive({
inFile <- input$transaction inFile <- input$transaction
if (is.null(inFile)) if (is.null(inFile))
return(NULL) return(NULL)
df <- read.csv(inFile$datapath, df <- read.csv(
header = input$header, inFile$datapath,
sep = input$sep, header = input$header,
quote = input$quote) sep = input$sep,
quote = input$quote
)
df df
}) })
@ -781,98 +779,130 @@ server <- function(input, output) {
inFile <- input$collaterals inFile <- input$collaterals
if (is.null(inFile)) if (is.null(inFile))
return(NULL) return(NULL)
df <- read.csv(inFile$datapath, df <- read.csv(
header = input$header, inFile$datapath,
sep = input$sep, header = input$header,
quote = input$quote) sep = input$sep,
quote = input$quote
)
df df
}) })
updateVarSelectInput("collateralid","Select id column", df.c(),session = getDefaultReactiveDomain()) updateVarSelectInput("collateralid", "Select id column", df.c(), session = getDefaultReactiveDomain())
updateVarSelectInput("collateralvalue","Select Collateral value column", df.c(),session = getDefaultReactiveDomain()) updateVarSelectInput("collateralvalue",
updateVarSelectInput("reportdate","Select report date column", df.tr(),session = getDefaultReactiveDomain()) "Select Collateral value column",
updateVarSelectInput("origindate","Select origin date column", df.tr(),session = getDefaultReactiveDomain()) df.c(),
updateVarSelectInput("maturitydate","Select maturity date column", df.tr(),session = getDefaultReactiveDomain()) session = getDefaultReactiveDomain())
updateVarSelectInput("assettype","Select asset classifier column", df.tr(),session = getDefaultReactiveDomain()) updateVarSelectInput("reportdate",
updateVarSelectInput("customertype","Select customer classifier column", df.tr(),session = getDefaultReactiveDomain()) "Select report date column",
updateVarSelectInput("otherfact","Select any other classifier column", df.tr(),session = getDefaultReactiveDomain()) df.tr(),
updateVarSelectInput("bureauscore","Select bureau score column", df.tr(),session = getDefaultReactiveDomain()) session = getDefaultReactiveDomain())
updateVarSelectInput("balance","Select asset balance column", df.tr(),session = getDefaultReactiveDomain()) updateVarSelectInput("origindate",
updateVarSelectInput("status","Select loan status", df.tr(),session = getDefaultReactiveDomain()) "Select origin date column",
updateVarSelectInput("defaultflag","Select default flag column", df.tr(),session = getDefaultReactiveDomain()) df.tr(),
updateVarSelectInput("transid","Select id column", df.tr(),session = getDefaultReactiveDomain()) session = getDefaultReactiveDomain())
updateVarSelectInput("maturitydate",
"Select maturity date column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("assettype",
"Select asset classifier column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("customertype",
"Select customer classifier column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("otherfact",
"Select any other classifier column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("bureauscore",
"Select bureau score column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("balance",
"Select asset balance column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("status", "Select loan status", df.tr(), session = getDefaultReactiveDomain())
updateVarSelectInput("defaultflag",
"Select default flag column",
df.tr(),
session = getDefaultReactiveDomain())
updateVarSelectInput("transid", "Select id column", df.tr(), session = getDefaultReactiveDomain())
}) })
# Modal 2 # Modal 2
observeEvent(input$uploadfiles, { observeEvent(input$uploadfiles, {
showModal( showModal(modal2)
modal2
)
}) })
observeEvent(input$confirmupload,{ observeEvent(input$confirmupload, {
transaction.dt( transaction.dt({
{ df <- read.csv(
df <- read.csv(input$transaction$datapath, input$transaction$datapath,
header = input$header, header = input$header,
sep = input$sep, sep = input$sep,
quote = input$quote) quote = input$quote
head(df) )
head(df)
df<-
df %>% df <-
rename(report_date=input$reportdate, df %>%
origination_date=input$origindate, rename(
maturity_date=input$maturitydate, report_date = input$reportdate,
asset_type=input$assettype, origination_date = input$origindate,
customer_type=input$customertype, maturity_date = input$maturitydate,
bureau_score_orig=input$bureauscore, asset_type = input$assettype,
balance=input$balance, customer_type = input$customertype,
loan_status=input$status, bureau_score_orig = input$bureauscore,
default_flag=input$defaultflag, balance = input$balance,
id=input$transid) loan_status = input$status,
default_flag = input$defaultflag,
if(input$dateformat=="ymd"){ id = input$transid
df$report_date<-ymd(df$report_date) )
df$origination_date<-ymd(df$origination_date)
df$maturity_date<-ymd(df$maturity_date) if (input$dateformat == "ymd") {
} else { df$report_date <- ymd(df$report_date)
df$report_date<-dmy(df$report_date) df$origination_date <- ymd(df$origination_date)
df$origination_date<-dmy(df$origination_date) df$maturity_date <- ymd(df$maturity_date)
df$maturity_date<-dmy(df$maturity_date) } else {
} df$report_date <- dmy(df$report_date)
df$origination_date <- dmy(df$origination_date)
df$loan_status<-as.integer(df$loan_status) df$maturity_date <- dmy(df$maturity_date)
}
# Covert to factors
df$asset_type<-as.factor(df$asset_type) df$loan_status <- as.integer(df$loan_status)
df$customer_type<-as.factor(df$customer_type)
if(!is.null(input$otherfact)){ # Covert to factors
for(i in 1:length(input$otherfact)){ df$asset_type <- as.factor(df$asset_type)
df$input$otherfact[i]<-as.factor(df$input$otherfact[i]) df$customer_type <- as.factor(df$customer_type)
} if (!is.null(input$otherfact)) {
for (i in 1:length(input$otherfact)) {
df$input$otherfact[i] <- as.factor(df$input$otherfact[i])
} }
df
} }
)
df
})
collateral.dt( collateral.dt({
{ df <- read.csv(
df <- read.csv(input$collaterals$datapath, input$collaterals$datapath,
header = input$header, header = input$header,
sep = input$sep, sep = input$sep,
quote = input$quote) quote = input$quote
df<- )
df %>% df <-
rename(id=input$collateralid, df %>%
collateral=input$collateralvalue) rename(id = input$collateralid,
df collateral = input$collateralvalue)
} df
) })
removeModal() removeModal()
}) })

Loading…
Cancel
Save