R/sec_api_single_methods.R

Defines functions get_shares_out consolidate_cash_flow get_amortization_filing get_filing_leases consolidate_balance_sheet get_capex get_inventory get_long_debt get_short_debt get_acc_rec get_acc_pay get_cash get_market_security get_goodwill get_equity get_expense get_rnd get_revenues get_operating_income get_single_values_2 get_single_values get_all_10k_filings get_filing

Documented in consolidate_balance_sheet consolidate_cash_flow get_acc_pay get_acc_rec get_all_10k_filings get_amortization_filing get_capex get_cash get_equity get_expense get_filing get_filing_leases get_goodwill get_inventory get_long_debt get_market_security get_operating_income get_revenues get_rnd get_shares_out get_short_debt get_single_values get_single_values_2

#' Call SEC API and fetch company filing
#' @description
#' Call SEC API, fetch company filing of interest and parse it
#' @param url **Character** SEC filing html link (.htm)
#' @param api_key **Character** SEC API key
#' @return **Text data** JSON parsed data
#' @examples
#' # SEC filing html link
#' # url <- "https://www.sec.gov/Archives/edgar/data/1633917/000163391722000027/pypl-20211231.htm"
#' # API key
#' # api_key <- "XXXXXXXXX"
#' @importFrom httr GET
#' @importFrom jsonlite fromJSON
#' @export
get_filing <- function(url, api_key) {
    # Set xbrl converter endpoint
     xbrl_converter_api_endpoint <-  "https://api.sec-api.io/xbrl-to-json"
    # Create the final API call link
     final_url <- paste0(xbrl_converter_api_endpoint, "?htm-url=",
                                     url, "&token=", api_key)
    # API call
     api_response <- httr::GET(final_url)
    # Parse the response
     parsed_data <- jsonlite::fromJSON(as.character(api_response))
     return(parsed_data)
}

#' Fetch the links of all the 10-K filings (specific company)
#' @description
#' Call SEC API and fetch the links of all the 10-K filings attributed to a specific company
#' @param ticker **Character** Company ticker
#' @param api_key **Character** SEC API key
#' @return **List** List of 10-K URLs
#' @examples
#' # Company ticker
#' # ticker <- "AAPL"
#' # API key
#' # api_key <- "XXXXXXXXX"
#' @importFrom dplyr `%>%`
#' @importFrom reticulate import r_to_py py_install
#' @importFrom stringr str_subset
#' @importFrom purrr map
#' @export
get_all_10k_filings <- function(ticker, api_key) {
  py_install("sec_api", pip=T)
  sec <- import("sec_api")
  query_api <- sec$QueryApi(api_key = api_key)
  query <- list(query = list(query_string=list(query=paste0("(formType:\"10-K\") AND ticker:", ticker))),
                from = "0",
                size = "20",
                sort = list(filedAt = list(order="desc")))
  py_q <- r_to_py(query)
  query_result <- query_api$get_filings(py_q)
  result <- unlist(map(.x = seq_along(query_result$filings),
                   .f=function(.x) query_result$filings[[.x]]$linkToHtml))
  return(result)
}

#' Get parameter formatted values
#' @description
#' Get the tibble w/ tidy params values
#' @param filing_df **JSON text** Parsed param DataFrame
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent formatted param values (3Y)
#' @examples
#' # Parsed json filing
#' # filing_df
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom dplyr `%>%` select arrange slice_tail mutate
#' @importFrom stringr str_detect
#' @export
get_single_values <- function(filing_df, ticker, param) {
  if (any(str_detect(colnames(filing_df), "segment")) & any(str_detect(colnames(filing_df), "value"))) {
    result <- data.frame(filing_df) %>% arrange(segment) %>% slice_tail(n=3) %>% select(value) %>%
      mutate(ticker=ticker, value = as.numeric(value) / 1000000)
    names(result)[names(result)=="value"] <- param
    return(result)
  } else if(any(str_detect(colnames(filing_df), "value"))) {
    result <- data.frame(filing_df) %>% select(value) %>%
      mutate(ticker=ticker, value = as.numeric(value) / 1000000)
    names(result)[names(result)=="value"] <- param
    return(result)
  } else {
    print("Passing...")
  }
}

#' Get parameter formatted values (Balance Sheet)
#' @description
#' Get the tibble w/ tidy params values
#' @param filing_df **JSON text** Parsed param DataFrame
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent formatted param values (3Y)
#' @examples
#' # Parsed json filing
#' # filing_df
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom dplyr `%>%` select arrange slice_tail mutate
#' @importFrom stringr str_detect
#' @export
get_single_values_2 <- function(filing_df, ticker, param) {
  if (any(str_detect(colnames(filing_df), "segment")) & any(str_detect(colnames(filing_df), "value"))) {
    result <- data.frame(filing_df) %>% arrange(segment) %>% slice_tail(n=4) %>% select(value) %>%
      mutate(ticker=ticker, value = as.numeric(value) / 1000000)
    names(result)[names(result)=="value"] <- param
    return(result[1:2,])
  } else if(any(str_detect(colnames(filing_df), "value"))) {
    result <- data.frame(filing_df) %>% select(value) %>%
      mutate(ticker=ticker, value = as.numeric(value) / 1000000)
    names(result)[names(result)=="value"] <- param
    return(result[1:2,])
  } else {
    print("Passing...")
  }
}


#' Get operating income from the income statement
#' @description
#' Get the numeric value of the operating income / loss
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent EBIT values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_operating_income <- function(xbrl_json, ticker, param="ebit") {
  if (!is.null(xbrl_json$StatementsOfIncome) & length(xbrl_json$StatementsOfIncome) > 1) {
    if (any(str_detect(names(xbrl_json$StatementsOfIncome), "OperatingIncomeLoss"))) {
      result <- get_single_values(filing_df = xbrl_json$StatementsOfIncome$OperatingIncomeLoss,
                                  ticker = ticker, param = param)
      return(result)
    } else {
      print("No OperatingIncomeLoss statement")
    }
  } else {
    print("No StatementOfIncome")
  }
}

#' Get revenues from the income statement
#' @description
#' Get the numeric value of the revenues
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent revenues values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_revenues <- function(xbrl_json, ticker, param="revenue") {
  if (!is.null(xbrl_json$StatementsOfIncome) & length(xbrl_json$StatementsOfIncome) > 1) {
    if (any(str_detect(names(xbrl_json$StatementsOfIncome), "Revenues"))) {
      result <- get_single_values(filing_df = xbrl_json$StatementsOfIncome$Revenues,
                                  ticker = ticker, param=param)
    } else if (any(str_detect(names(xbrl_json$StatementsOfIncome), "SalesRevenueNet"))) {
      result <- get_single_values(xbrl_json$StatementsOfIncome$SalesRevenueNet,
                                  ticker = ticker, param=param)
    } else if (any(str_detect(names(xbrl_json$StatementsOfIncome),
                              "RevenueFromContractWithCustomerExcludingAssessedTax")))
      result <- get_single_values(xbrl_json$StatementsOfIncome$RevenueFromContractWithCustomerExcludingAssessedTax,
                                  ticker = ticker, param=param)
    else {
      print("Revenues data is missing")
    }
  }
  else {
    print("Missing Income Statement (NULL or length <=1")
  }
}

#' Get R&D from the income statement
#' @description
#' Get the numeric value of the R&D
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent R&D values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_rnd <- function(xbrl_json, ticker, param="rnd") {
  if (!is.null(xbrl_json$StatementsOfIncome) & length(xbrl_json$StatementsOfIncome) > 1) {
    if (any(str_detect(names(xbrl_json$StatementsOfIncome), "ResearchAndDevelopmentExpense"))) {
      result <- get_single_values(xbrl_json$StatementsOfIncome$ResearchAndDevelopmentExpense,
                                  ticker = ticker,
                                  param = param)
    } else if (any(str_detect(names(xbrl_json$StatementsOfIncome), "TechnologyAndDevelopmentExpense"))) {
      result <- get_single_values(xbrl_json$StatementsOfIncome$TechnologyAndDevelopmentExpense,
                                  ticker = ticker,
                                  param = param)
    } else {
      print("No R&D found")
    }
  }
  else {
    print("Missing Income Statement (NULL or length <=1")
  }
}


#' Get interest expense from the income statement
#' @description
#' Get the numeric value of the interest expense
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent interest expense values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_expense <- function(xbrl_json, ticker, param="expense") {
  if (!is.null(xbrl_json$StatementsOfIncome) & length(xbrl_json$StatementsOfIncome) > 1) {
    if (any(str_detect(names(xbrl_json$StatementsOfIncome), "InterestExpense"))) {
      result <- get_single_values(xbrl_json$StatementsOfIncome$InterestExpense,
                                  ticker = ticker,
                                  param = param)
    } else if(any(str_detect(names(xbrl_json$StatementsOfIncome), "NonoperatingIncomeExpense"))) {
      result <- get_single_values(xbrl_json$StatementsOfIncome$NonoperatingIncomeExpense,
                                  ticker = ticker,
                                  param = param)
    }
    else {
      print("InterestExpense data is missing")
    }

  }
  else {
    print("Missing Income Statement (NULL or length <=1")
  }
}

#' Get equity from the balance sheet
#' @description
#' Get the numeric value of the equity
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent equity values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_equity <- function(xbrl_json, ticker, param="equity") {
  if (!is.null(xbrl_json$BalanceSheets) & length(xbrl_json$BalanceSheets) > 1) {
    if (any(str_detect(names(xbrl_json$BalanceSheets), "StockholdersEquity"))) {
      result <- get_single_values_2(filing_df = xbrl_json$BalanceSheets$StockholdersEquity,
                                  ticker = ticker,
                                  param = param)
    } else {
      print("Equity data is missing")
    }
  }
  else {
    print("Missing Balance Sheet (NULL or length <=1")
  }

}

#' Get goodwiil from the balance sheet
#' @description
#' Get the numeric value of the goodwill
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent goodwill values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_goodwill <- function(xbrl_json, ticker, param="goodwill") {
  if (!is.null(xbrl_json$BalanceSheets) & length(xbrl_json$BalanceSheets) > 1) {
    if (any(str_detect(names(xbrl_json$BalanceSheets), "Goodwill"))) {
      result <- get_single_values_2(filing_df = xbrl_json$BalanceSheets$Goodwill,
                                    ticker = ticker,
                                    param = param)
    } else {
      print("Goodwill is missing")
    }
  }
  else {
    print("Missing Balance Sheet (NULL or length <=1")
  }

}

#' Get market securities from the balance sheet
#' @description
#' Get the numeric value of the market securities
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent market securities values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_market_security <- function(xbrl_json, ticker, param="market_security") {
  if (!is.null(xbrl_json$BalanceSheets) & length(xbrl_json$BalanceSheets) > 1) {
    if (any(str_detect(names(xbrl_json$BalanceSheets), "MarketableSecuritiesCurrent"))) {
      result <- get_single_values_2(filing_df = xbrl_json$BalanceSheets$MarketableSecuritiesCurrent,
                                    ticker = ticker,
                                    param = param)
    } else {
      print("Market security is missing")
    }
  }
  else {
    print("Missing Balance Sheet (NULL or length <=1")
  }

}

#' Get cash from the balance sheet
#' @description
#' Get the numeric value of the cash
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent cash values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_cash <- function(xbrl_json, ticker, param="cash") {
  if (!is.null(xbrl_json$BalanceSheets) & length(xbrl_json$BalanceSheets) > 1) {
    if (any(str_detect(names(xbrl_json$BalanceSheets), "CashAndCashEquivalentsAtCarryingValue"))) {
      result <- get_single_values_2(filing_df = xbrl_json$BalanceSheets$CashAndCashEquivalentsAtCarryingValue,
                                    ticker = ticker,
                                    param = param)
    } else {
      print("CashAndCashEquivalentsAtCarryingValue is missing")
    }
  }
  else {
    print("Missing Balance Sheet (NULL or length <=1")
  }

}

#' Get accounts payable from the balance sheet
#' @description
#' Get the numeric value of the accounts payable
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent accounts payable values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_acc_pay <- function(xbrl_json, ticker, param="acc_pay") {
  if (!is.null(xbrl_json$BalanceSheets) & length(xbrl_json$BalanceSheets) > 1) {
    if (any(str_detect(names(xbrl_json$BalanceSheets), "AccountsPayableCurrent"))) {
      result <- get_single_values_2(filing_df = xbrl_json$BalanceSheets$AccountsPayableCurrent,
                                    ticker = ticker,
                                    param = param)
    } else {
      print("AccountsPayableCurrent is missing")
    }
  }
  else {
    print("Missing Balance Sheet (NULL or length <=1")
  }

}


#' Get accounts receivable from the balance sheet
#' @description
#' Get the numeric value of the accounts receivable
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent accounts receivable values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_acc_rec <- function(xbrl_json, ticker, param="acc_rec") {
  if (!is.null(xbrl_json$BalanceSheets) & length(xbrl_json$BalanceSheets) > 1) {
    if (any(str_detect(names(xbrl_json$BalanceSheets), "AccountsAndOtherReceivablesNetCurrent"))) {
      result <- get_single_values_2(filing_df = xbrl_json$BalanceSheets$AccountsAndOtherReceivablesNetCurrent,
                                    ticker = ticker,
                                    param = param)
    } else if (any(str_detect(names(xbrl_json$BalanceSheets), "AccountsReceivableNetCurrent"))) {
      result <- get_single_values_2(filing_df = xbrl_json$BalanceSheets$AccountsReceivableNetCurrent,
                                    ticker = ticker,
                                    param = param)
    } else {
      print("AccountsAndOtherReceivablesNetCurrent is missing")
    }
  }
  else {
    print("Missing Balance Sheet (NULL or length <=1")
  }

}


#' Get debt current from the balance sheet
#' @description
#' Get the numeric value of the debt current
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent debt current values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_short_debt <- function(xbrl_json, ticker, param="debt_current") {
  if (!is.null(xbrl_json$BalanceSheets) & length(xbrl_json$BalanceSheets) > 1) {
    if (any(str_detect(names(xbrl_json$BalanceSheets), "LiabilitiesCurrent"))) {
      result <- get_single_values(xbrl_json$BalanceSheets$LiabilitiesCurrent,
                                  param="short_debt", ticker="AAPL")}
    else if (any(str_detect(names(xbrl_json$BalanceSheets), "DebtCurrent"))) {
      result <- get_single_values(xbrl_json$BalanceSheets$LiabilitiesCurrent,
                                  param="short_debt", ticker="AAPL")
    }
    else {
      print("Missing Balance Sheet (NULL or length <=1")
    }
}}

#' Get debt long from the balance sheet
#' @description
#' Get the numeric value of the debt long
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent debt long values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_long_debt <- function(xbrl_json, ticker, param="debt_long") {
  if (!is.null(xbrl_json$BalanceSheets) & length(xbrl_json$BalanceSheets) > 1) {
    if (any(str_detect(names(xbrl_json$BalanceSheets), "OtherLiabilitiesNoncurrent"))) {
      result <- get_single_values(xbrl_json$BalanceSheets$OtherLiabilitiesNoncurrent,
                                    param=param, ticker=ticker)}
    else if (any(str_detect(names(xbrl_json$BalanceSheets), "LiabilitiesNoncurrent"))) {
      result <- get_single_values(xbrl_json$BalanceSheets$LiabilitiesNoncurrent,
                                  param=param, ticker=ticker)
    } else if (any(str_detect(names(xbrl_json$BalanceSheets), "LongTermDebtNoncurrent"))) {
               result <- get_single_values(xbrl_json$BalanceSheets$LongTermDebtNoncurrent,
                                           param=param, ticker=ticker)
    } else {
      print("Missing Balance Sheet (NULL or length <=1")
    }}
}

#' Get inventory from the balance sheet
#' @description
#' Get the numeric value of the inventory
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent inventory values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_inventory <- function(xbrl_json, ticker, param="inventory") {
  if (!is.null(xbrl_json$BalanceSheets) & length(xbrl_json$BalanceSheets) > 1) {
    if (any(str_detect(names(xbrl_json$BalanceSheets), "InventoryNet"))) {
      result <- get_single_values(filing_df = xbrl_json$BalanceSheets$InventoryNet,
                                    ticker = ticker,
                                    param = param)
    } else {
      print("InventoryNet is missing")
    }
  }
  else {
    print("Missing Balance Sheet (NULL or length <=1")
  }

}

#' Get capex from the balance sheet
#' @description
#' Get the numeric value of the capex
#' @param xbrl_json **JSON text** Parsed xbrl filing
#' @param ticker **Character** Company ticker
#' @return **Tibble** Tibble w/ the recent capex values (3Y)
#' @examples
#' # Parsed json filing
#' # ebit <- filing
#' # Company ticker
#' # ticker <- "AAPL"
#' @importFrom stringr str_detect
#' @export
get_capex <- function(xbrl_json, ticker, param="capex") {
  if (!is.null(xbrl_json$StatementsOfCashFlows) & length(xbrl_json$StatementsOfCashFlows) > 1) {
    if (any(str_detect(names(xbrl_json$StatementsOfCashFlows), "PaymentsToAcquireProductiveAssets"))) {
      result <- get_single_values(filing_df = xbrl_json$StatementsOfCashFlows$PaymentsToAcquireProductiveAssets,
                                    ticker = ticker,
                                    param = param)
    } else if (any(str_detect(names(xbrl_json$StatementsOfCashFlows), "PaymentsToAcquirePropertyPlantAndEquipment"))) {
      result <- get_single_values(filing_df = xbrl_json$StatementsOfCashFlows$PaymentsToAcquirePropertyPlantAndEquipment,
                                  ticker = ticker,
                                  param = param)
    }
  }
  else {
    print("Missing Balance Sheet (NULL or length <=1")
  }

}










































 #' Get consolidated balance sheet from the filing
 #' @description
 #' Get thh consolidated balance sheet
 #' @param xbrl_json **JSON text** Parsed xbrl filing
 #' @return **Tibble** Tibble w/ the balance sheet (3Y)
 #' @examples
 #' # Parsed json filing
 #' # equity <- filing$BalanceSheets$InventoryNet
 #' # goodwill <- filing$BalanceSheets$BalanceSheets$Goodwill
 #' # market_securities <- filing$BalanceSheets$MarketableSecuritiesCurrent
 #' # cash <- filing$BalanceSheets$BalanceSheets$CashAndCashEquivalentsAtCarryingValue
 #' # acc_pay <- filing$BalanceSheets$AccountsPayableCurrent
 #' # acc_rec <- filing$BalanceSheets$AccountsAndOtherReceivablesNetCurrent
 #' # debt_current <- filing$BalanceSheets$DebtCurrent
 #' # debt_long <- filing$BalanceSheets$LongTermDebt
 #' # inventory <- filing$BalanceSheets$InventoryNet
 #' # Type of value column
 #' @importFrom dplyr `%>%` full_join
 #' @importFrom purrr reduce
 #' @export
 consolidate_balance_sheet <- function(...) {
   cash_flow_list <- list(...)
   cons <- reduce(cash_flow_list, full_join, by=c("ticker", "period"))
   return(cons)

 }


 #' Get leases from the filing
 #' @description
 #' Get the numeric value of the leases
 #' @param xbrl_json **JSON text** Parsed xbrl filing
 #' @return **Tibble** Tibble w/ the recent leases (current + 5Y future)
 #' @importFrom dplyr `%>%` mutate across everything relocate
 #' @importFrom readr parse_number
 #' @export
 get_filing_leases <- function(xbrl_json) {
   if (!is.null(xbrl_json$LeasesLeaseLiabilityMaturitiesDetails) & length(xbrl_json$LeasesLeaseLiabilityMaturitiesDetails) > 1) {
     list(current =last_filing$LeasesLeaseLiabilityMaturitiesDetails$OperatingLeaseLiability,
          y1 = last_filing$LeasesLeaseLiabilityMaturitiesDetails$LesseeOperatingLeaseLiabilityPaymentsDueNextTwelveMonths,
          y2 = last_filing$LeasesLeaseLiabilityMaturitiesDetails$LesseeOperatingLeaseLiabilityPaymentsDueYearTwo,
          y3 = last_filing$LeasesLeaseLiabilityMaturitiesDetails$LesseeOperatingLeaseLiabilityPaymentsDueYearThree,
          y4 = last_filing$LeasesLeaseLiabilityMaturitiesDetails$LesseeOperatingLeaseLiabilityPaymentsDueYearFour,
          y5 =last_filing$LeasesLeaseLiabilityMaturitiesDetails$LesseeOperatingLeaseLiabilityPaymentsDueYearFive,
          beyond = last_filing$LeasesLeaseLiabilityMaturitiesDetails$LesseeOperatingLeaseLiabilityPaymentsDueAfterYearFive)
   } else {
     print("No leases found")
   }

 }


 #' Get amortization from the filing
 #' @description
 #' Get the numeric value of the amortization
 #' @param xbrl_json **JSON text** Parsed xbrl filing
 #' @param type_of **Character** Name of value column
 #' @return **Tibble** Tibble w/ the recent capex (3Y)
 #' @examples
 #' # Parsed json filing
 #' # amortization <- filing$BalanceSheets$DepreciationDepletionAndAmortization
 #' # Type of value column
 #' # column_type <- "amortization"
 #' @importFrom dplyr `%>%` filter rename mutate select relocate
 #' @importFrom tidyr unnest
 #' @importFrom readr parse_number
 #' @importFrom lubridate year
 #' @export
 get_amortization_filing <- function(xbrl_json, type_of="amortization") {
   df <- xbrl_json$StatementsOfCashFlows$DepreciationDepletionAndAmortization
   ticker <- xbrl_json$CoverPage$TradingSymbol

   df_clean <- df %>% unnest(cols=period) %>%
     select(value, endDate) %>%
     mutate(endDate = year(endDate),
            value = parse_number(value) / 1000000,
            ticker=ticker) %>%
     rename(period = endDate) %>%
     relocate(ticker, .before=period) %>%
     relocate(value, .after = period)

   names(df_clean)[names(df_clean)=="value"] <- type_of
   return(df_clean)
 }

 #' Get consolidated cash flow from the filing
 #' @description
 #' Get thh consolidated cash flow data
 #' @param xbrl_json **JSON text** Parsed xbrl filing
 #' @return **Tibble** Tibble w/ the balance sheet (3Y)
 #' @examples
 #' # Parsed json filing
 #' # amortization <- filing$StatementsOfCashFlows$DepreciationDepletionAndAmortization
 #' # capex <- filing$StatementsOfCashFlows$PaymentsToAcquireProductiveAssets
 #' @importFrom dplyr `%>%` full_join
 #' @importFrom purrr reduce
 #' @export
 consolidate_cash_flow <- function(amortization, capex) {
   cash_flow_list <- list(amortization, capex)
   cons <- reduce(cash_flow_list, full_join, by=c("ticker", "period"))
   return(cons)

 }

 #' Get shares outstanding
 #' @description
 #' Get the numeric value of the shares outstanding
 #' @param xbrl_json **JSON text** Parsed xbrl filing
 #' @return **Numeric** Current share outstanding
 #' @examples
 #' # Parsed json filing
 #' # shares_out <- filing$CoverPage$EntityCommonStockSharesOutstanding$value
 #' @importFrom readr parse_number
 #' @export
 get_shares_out <- function(xbrl_json) {
   shares_out <- parse_number(filing$CoverPage$EntityCommonStockSharesOutstanding$value)/1000000
   return(shares_out)
 }
TracyRage/fun_valuation documentation built on Jan. 29, 2023, 8:41 a.m.