Setup

Load Packages

library( irs990efile )  # functions for parsing efile XMLs
library( dplyr )        # data wrangling
library( purrr )        # data wrangling 
library( pander )       # formatting
library( knitr )        # formatting
library( DT )           # table printing
library( httr )         # web requests 
library( xmltools )     # xml utilities
library( xml2 )         # xml utilities
library( XML )          # xml utilities 
library( data.tree )    # network visualization
library( networkD3 )    # network visualization
library( igraph )       # network visualization

source( "R/rdb-functions-v2.R")
source( "R/utils.R")

Data

head( index )

The Concordance File

The concordance is an RDB to XML Crosswalk that maps all xpaths onto a specified set of variables. It is located in the irs990efile package.


The full data dictionary is available on GitHub.

DATA DICTIONARY


concordance %>% 
  filter( rdb_table == table.name )  








xpath id
/Return/ReturnData/IRS990ScheduleD/CloselyHeldEquityInterests/BookValue 1
/Return/ReturnData/IRS990ScheduleD/CloselyHeldEquityInterests/MethodOfValuation 2
/Return/ReturnData/IRS990ScheduleD/CloselyHeldEquityInterestsGrp/BookValueAmt 3
/Return/ReturnData/IRS990ScheduleD/CloselyHeldEquityInterestsGrp/MethodValuationCd 4
/Return/ReturnData/IRS990ScheduleD/FinancialDerivatives/BookValue 5
/Return/ReturnData/IRS990ScheduleD/FinancialDerivatives/MethodOfValuation 6
/Return/ReturnData/IRS990ScheduleD/FinancialDerivativesGrp/BookValueAmt 7
/Return/ReturnData/IRS990ScheduleD/FinancialDerivativesGrp/MethodValuationCd 8
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/CloselyHeldEquityInterests/BookValue 9
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/CloselyHeldEquityInterests/MethodOfValuation 10
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/FinancialDerivatives/BookValue 11
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/FinancialDerivatives/MethodOfValuation 12
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/Other/BookValue 13
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/Other/Description 14
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/Other/MethodOfValuation 15
/Return/ReturnData/IRS990ScheduleD/OtherSecurities/BookValue 16
/Return/ReturnData/IRS990ScheduleD/OtherSecurities/Description 17
/Return/ReturnData/IRS990ScheduleD/OtherSecurities/MethodOfValuation 18
/Return/ReturnData/IRS990ScheduleD/OtherSecuritiesGrp/BookValueAmt 19
/Return/ReturnData/IRS990ScheduleD/OtherSecuritiesGrp/Desc 20
/Return/ReturnData/IRS990ScheduleD/OtherSecuritiesGrp/MethodValuationCd 21
xpaths <- as.character( t.xpaths$xpath )
el <- create_edgelist_v1( xpaths )
nd <- FromDataFrameNetwork( network=el )
print( nd )
##                                     levelName
## 1  Return                                    
## 2   °--ReturnData                            
## 3       °--IRS990ScheduleD                   
## 4           ¦--CloselyHeldEquityInterests    
## 5           ¦   ¦--BookValue                 
## 6           ¦   °--MethodOfValuation         
## 7           ¦--CloselyHeldEquityInterestsGrp 
## 8           ¦   ¦--BookValueAmt              
## 9           ¦   °--MethodValuationCd         
## 10          ¦--FinancialDerivatives          
## 11          ¦   ¦--BookValue                 
## 12          ¦   °--MethodOfValuation         
## 13          ¦--FinancialDerivativesGrp       
## 14          ¦   ¦--BookValueAmt              
## 15          ¦   °--MethodValuationCd         
## 16          ¦--Form990ScheduleDPartVII       
## 17          ¦   ¦--CloselyHeldEquityInterests
## 18          ¦   ¦   ¦--BookValue             
## 19          ¦   ¦   °--MethodOfValuation     
## 20          ¦   ¦--FinancialDerivatives      
## 21          ¦   ¦   ¦--BookValue             
## 22          ¦   ¦   °--MethodOfValuation     
## 23          ¦   °--Other                     
## 24          ¦       ¦--BookValue             
## 25          ¦       ¦--Description           
## 26          ¦       °--MethodOfValuation     
## 27          ¦--OtherSecurities               
## 28          ¦   ¦--BookValue                 
## 29          ¦   ¦--Description               
## 30          ¦   °--MethodOfValuation         
## 31          °--OtherSecuritiesGrp            
## 32              ¦--BookValueAmt              
## 33              ¦--Desc                      
## 34              °--MethodValuationCd
SetGraphStyle( nd, rankdir = "LR")
SetEdgeStyle( nd, arrowhead = "vee", color = "grey20", penwidth = 2 )
SetNodeStyle( nd, 
              style = "filled,rounded", 
              shape = "box", 
              fillcolor = "LightBlue", 
              fontname = "helvetica", 
              fontcolor="black",
              tooltip = GetDefaultTooltip )

# SetNodeStyle(acme$IT, fillcolor = "LightBlue", penwidth = "5px")
plot( nd )
# old version
find_group_names( table.name )
## [1] "//FinancialDerivatives"          "//FinancialDerivativesGrp"      
## [3] "//Form990ScheduleDPartVII"       "//CloselyHeldEquityInterests"   
## [5] "//CloselyHeldEquityInterestsGrp" "//OtherSecurities"              
## [7] "//OtherSecuritiesGrp"
# new version
find_table_headers( table.name )
##  [1] "//FinancialDerivatives/FinancialDerivatives"            
##  [2] "//FinancialDerivatives/Form990ScheduleDPartVII"         
##  [3] "//FinancialDerivativesGrp/BookValueAmt"                 
##  [4] "//FinancialDerivativesGrp/MethodValuationCd"            
##  [5] "//Form990ScheduleDPartVII/FinancialDerivatives"         
##  [6] "//Form990ScheduleDPartVII/CloselyHeldEquityInterests"   
##  [7] "//Form990ScheduleDPartVII/Other"                        
##  [8] "//Form990ScheduleDPartVII/TotalOfBookValue"             
##  [9] "//CloselyHeldEquityInterests/CloselyHeldEquityInterests"
## [10] "//CloselyHeldEquityInterests/Form990ScheduleDPartVII"   
## [11] "//CloselyHeldEquityInterestsGrp/BookValueAmt"           
## [12] "//CloselyHeldEquityInterestsGrp/MethodValuationCd"      
## [13] "//OtherSecurities/IRS990"                               
## [14] "//OtherSecurities/IRS990ScheduleD"                      
## [15] "//OtherSecuritiesGrp/IRS990"                            
## [16] "//OtherSecuritiesGrp/IRS990ScheduleD"
# manual
if( ! is.null(table.headers) )
{table.headers}
## [1] "//IRS990ScheduleD/CloselyHeldEquityInterests"                        
## [2] "//IRS990ScheduleD/CloselyHeldEquityInterestsGrp"                     
## [3] "//IRS990ScheduleD/FinancialDerivatives"                              
## [4] "//IRS990ScheduleD/FinancialDerivativesGrp"                           
## [5] "//IRS990ScheduleD/Form990ScheduleDPartVII/CloselyHeldEquityInterests"
## [6] "//IRS990ScheduleD/Form990ScheduleDPartVII/FinancialDerivatives"      
## [7] "//IRS990ScheduleD/Form990ScheduleDPartVII/Other"                     
## [8] "//IRS990ScheduleD/OtherSecurities"                                   
## [9] "//IRS990ScheduleD/OtherSecuritiesGrp"








Build the Table

# create new folder
dir.create( folder.name )
setwd( folder.name )

# create sample
set.seed( 1234 )
sample.index <- sample_n( index, sample.size )
write.csv( index, "sample-index.csv", row.names=F )
sample.urls <- sample.index$URL

# erase existing log files
file.create("XPATH-LOG.txt") 
file.create("FAIL-LOG.txt")


start.build.time <- Sys.time()    # --------------------

results.list <- list()
xpath.list <- list()


for( i in 1:length( sample.urls ) )
{
  
  url <- sample.urls[i]
  
  results.list[[i]] <- 
    build_rdb_table_v2( url, 
                        table.name, 
                        table.headers=table.headers )
  
  xpath.list[[i]]   <- 
    get_table_xpaths( url, 
                      table.name, 
                      table.headers=table.headers )
  
  if( i %% 100 == 0 ){ print(i) }
  
}


end.build.time <- Sys.time()      # --------------------


df <- dplyr::bind_rows( results.list )


fail.log <- readLines( "FAIL-LOG.txt" )
all.xpaths <- xpath.list %>% unlist() %>% unique() %>% sort()
cat( all.xpaths, sep="\n", file="XPATH-LOG.txt" )

TABLE: SD-P07-T01-INVESTMENTS-OTH-SECURITIES

## [1] "NUMBER OF RETURNS PROCESSED:   1000"
## [1] "TOTAL NUMBER OF TABLE ROWS:   253"

TOTAL RUN TIME:

## Time difference of 14.15723 mins
## Time difference of -0.2359539 hours

Write to File

write.csv( df, paste0( folder.name, "/", table.name, ".csv" ), row.names=F )
head(df) 

Are all names standardized?

names(df)
##  [1] "OBJECT_ID"                        
##  [2] "EIN"                              
##  [3] "NAME"                             
##  [4] "TAXYR"                            
##  [5] "FORMTYPE"                         
##  [6] "URL"                              
##  [7] "SD_07_INVEST_SEC_OTH_DESC"        
##  [8] "SD_07_INVEST_SEC_DERIVATIVE_BV"   
##  [9] "SD_07_INVEST_SEC_DERIVATIVE_MOV"  
## [10] "SD_07_INVEST_SEC_DERIVATIVE_BV.1" 
## [11] "SD_07_INVEST_SEC_DERIVATIVE_MOV.1"
## [12] "SD_07_INVEST_SEC_DERIVATIVE_BV.2" 
## [13] "SD_07_INVEST_SEC_DERIVATIVE_MOV.2"
## [14] "ArtPublicExhibitionAmountsGrp"    
## [15] "HeldWorksArtGrp"                  
## [16] "PrmnntEndowmentBalanceEOYPct"     
## [17] "EndowmentsHeldUnrelatedOrgInd"    
## [18] "EndowmentsHeldRelatedOrgInd"      
## [19] "LandGrp"                          
## [20] "BuildingsGrp"                     
## [21] "LeaseholdImprovementsGrp"         
## [22] "EquipmentGrp"                     
## [23] "OtherLandBuildingsGrp"            
## [24] "FinancialDerivativesGrp"          
## [25] "CloselyHeldEquityInterestsGrp"    
## [26] "TotalBookValueSecuritiesAmt"      
## [27] "FederalIncomeTaxLiabilityAmt"     
## [28] "TotalLiabilityAmt"                
## [29] "FootnoteTextInd"                  
## [30] "CollectionUsedPubExhibitionInd"   
## [31] "SolicitedAssetsSaleInd"           
## [32] "CYMinus3YrEndwmtFundGrp"          
## [33] "CYMinus4YrEndwmtFundGrp"          
## [34] "TermEndowmentBalanceEOYPct"       
## [35] "TotalBookValueLandBuildingsAmt"   
## [36] "AgentTrusteeEtcInd"               
## [37] "InclEscrowCustodialAcctLiabInd"   
## [38] "BoardDesignatedBalanceEOYPct"     
## [39] "TotalRevEtcAuditedFinclStmtAmt"   
## [40] "NetUnrealizedGainsInvstAmt"       
## [41] "OtherRevenueAmt"                  
## [42] "RevenueNotReportedAmt"            
## [43] "RevenueSubtotalAmt"               
## [44] "OtherRevenuesNotIncludedAmt"      
## [45] "RevenueNotReportedFinclStmtAmt"   
## [46] "TotalRevenuePerForm990Amt"        
## [47] "TotExpnsEtcAuditedFinclStmtAmt"   
## [48] "ExpensesSubtotalAmt"              
## [49] "InvestmentExpensesNotIncld2Amt"   
## [50] "ExpensesNotRptFinclStmtAmt"       
## [51] "TotalExpensesPerForm990Amt"       
## [52] "InvestmentExpensesNotIncldAmt"    
## [53] "DonatedServicesAndUseFcltsAmt"    
## [54] "DonatedServicesUseFcltsAmt"       
## [55] "OtherExpensesIncludedAmt"         
## [56] "ExpensesNotReportedAmt"








Diagnostics

Missing or Extra XPATHS

Check for xpaths that were used in the tables but do not exist in the Concordance file.

c.table <- dplyr::filter( concordance, rdb_table == table.name ) 
xpath.concordance <- c.table$xpath
setdiff( all.xpaths, xpath.concordance )
## [1] ""                                                                
## [2] "/Return/ReturnData/IRS990ScheduleD/CloselyHeldEquityInterestsGrp"
## [3] "/Return/ReturnData/IRS990ScheduleD/FinancialDerivativesGrp"      
## [4] "/Return/ReturnData/IRS990ScheduleD/OtherSecuritiesGrp"

Capture to update the Concordance file.

these <- setdiff( all.xpaths, xpath.concordance )
cat( these, sep="\n", file=paste0( folder.name, "/MISSING-XPATHS.txt" ) )

Failes URLs

Check the status of failed URLs.

if( length(fail.log) > 0 )
{ 
  sapply( fail.log, get_message ) %>% 
  table() %>% 
  pander() 
} else {
  print("ALL URLs ARE VALID")
}
## [1] "ALL URLs ARE VALID"








XML Table Structure

Create Network Edgelists

The create_edgelist() functions v1 and v2 are in R/utils.R.

V1 retains the root nodes Return and ReturnData.

V2 drops the root nodes and uses form versions “990” and “990EZ” as the root to visualize the sets of tables separately.

# KEEP ROOT NOTES Return & ReturnData
el <- create_edgelist_v1( all.xpaths )



Edgelist format:

V1 V2
Return ReturnData
ReturnData IRS990
IRS990 Form990PartVIISectionAGrp
Form990PartVIISectionAGrp PersonNm
Form990PartVIISectionAGrp TitleTxt
Form990PartVIISectionAGrp AverageHoursPerWeekRt
Form990PartVIISectionAGrp IndividualTrusteeOrDirectorInd
Form990PartVIISectionAGrp OfficerInd
Form990PartVIISectionAGrp ReportableCompFromOrgAmt
Form990PartVIISectionAGrp ReportableCompFromRltdOrgAmt








Visualize Tree Structure

# library( data.tree )
nd <- FromDataFrameNetwork( network=el )
print( nd )
##                                    levelName
## 1  Return                                   
## 2   °--ReturnData                           
## 3       °--IRS990ScheduleD                  
## 4           ¦--CloselyHeldEquityInterestsGrp
## 5           ¦   ¦--BookValueAmt             
## 6           ¦   °--MethodValuationCd        
## 7           ¦--FinancialDerivativesGrp      
## 8           ¦   ¦--BookValueAmt             
## 9           ¦   °--MethodValuationCd        
## 10          °--OtherSecuritiesGrp           
## 11              ¦--BookValueAmt             
## 12              ¦--Desc                     
## 13              °--MethodValuationCd
SetGraphStyle( nd, rankdir = "LR")
SetEdgeStyle( nd, arrowhead = "vee", color = "grey20", penwidth = 2 )
SetNodeStyle( nd, 
              style = "filled,rounded", 
              shape = "box", 
              fillcolor = "LightBlue", 
              fontname = "helvetica", 
              fontcolor="black",
              tooltip = GetDefaultTooltip )

# SetNodeStyle(acme$IT, fillcolor = "LightBlue", penwidth = "5px")
plot( nd )
# library( networkD3 )
# net <- ToDataFrameNetwork( nd, "name" )
# simpleNetwork( net, fontSize = 12 )
simpleNetwork( el, fontSize = 12 )
#plot with networkD3
radnet <- ToListExplicit( nd, unname = TRUE )
radialNetwork( radnet, fontSize = 12 )








XPATH Summary

Unique Xpaths for this RDB Table

t.xpaths <- 
  concordance %>%
  filter( rdb_table == table.name ) %>% 
  select( xpath ) %>% 
  unique() %>% 
  arrange( xpath ) %>% 
  mutate( id=row_number() ) 

t.xpaths %>% 
  kable( align="l" )
xpath id
/Return/ReturnData/IRS990ScheduleD/CloselyHeldEquityInterests/BookValue 1
/Return/ReturnData/IRS990ScheduleD/CloselyHeldEquityInterests/MethodOfValuation 2
/Return/ReturnData/IRS990ScheduleD/CloselyHeldEquityInterestsGrp/BookValueAmt 3
/Return/ReturnData/IRS990ScheduleD/CloselyHeldEquityInterestsGrp/MethodValuationCd 4
/Return/ReturnData/IRS990ScheduleD/FinancialDerivatives/BookValue 5
/Return/ReturnData/IRS990ScheduleD/FinancialDerivatives/MethodOfValuation 6
/Return/ReturnData/IRS990ScheduleD/FinancialDerivativesGrp/BookValueAmt 7
/Return/ReturnData/IRS990ScheduleD/FinancialDerivativesGrp/MethodValuationCd 8
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/CloselyHeldEquityInterests/BookValue 9
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/CloselyHeldEquityInterests/MethodOfValuation 10
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/FinancialDerivatives/BookValue 11
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/FinancialDerivatives/MethodOfValuation 12
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/Other/BookValue 13
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/Other/Description 14
/Return/ReturnData/IRS990ScheduleD/Form990ScheduleDPartVII/Other/MethodOfValuation 15
/Return/ReturnData/IRS990ScheduleD/OtherSecurities/BookValue 16
/Return/ReturnData/IRS990ScheduleD/OtherSecurities/Description 17
/Return/ReturnData/IRS990ScheduleD/OtherSecurities/MethodOfValuation 18
/Return/ReturnData/IRS990ScheduleD/OtherSecuritiesGrp/BookValueAmt 19
/Return/ReturnData/IRS990ScheduleD/OtherSecuritiesGrp/Desc 20
/Return/ReturnData/IRS990ScheduleD/OtherSecuritiesGrp/MethodValuationCd 21

Grouping Variables

Identify all unique groups used in xpaths.

if( is.null(table.headers) )
{ find_table_headers( table.name ) } else
table.headers
## [1] "//IRS990ScheduleD/CloselyHeldEquityInterests"                        
## [2] "//IRS990ScheduleD/CloselyHeldEquityInterestsGrp"                     
## [3] "//IRS990ScheduleD/FinancialDerivatives"                              
## [4] "//IRS990ScheduleD/FinancialDerivativesGrp"                           
## [5] "//IRS990ScheduleD/Form990ScheduleDPartVII/CloselyHeldEquityInterests"
## [6] "//IRS990ScheduleD/Form990ScheduleDPartVII/FinancialDerivatives"      
## [7] "//IRS990ScheduleD/Form990ScheduleDPartVII/Other"                     
## [8] "//IRS990ScheduleD/OtherSecurities"                                   
## [9] "//IRS990ScheduleD/OtherSecuritiesGrp"

Groups can then be used to extract the 1:M RDB tables:

if( is.null(table.headers) )
{ table.headers <- find_table_headers( table.name ) }
demo.url <- "https://nccs-efile.s3.us-east-1.amazonaws.com/xml/201913079349300206_public.xml"
doc <- xml2::read_xml( demo.url )
xml2::xml_ns_strip( doc )
df.demo <- get_table_v2( doc, table.name, table.headers )
df.demo 
## NULL

Standardize Variable Names

Mapping of xml variable names to concordance variable names:

get_var_map( table.name=table.name )

A table with proper names:

v.map <- get_var_map( table.name=table.name )

if( ! is.null(df.demo) )
{re_name( df.demo, v.map ) %>% as.data.frame()}