here are few functions
2.2.1 Broker location adjustment -----------------------------------------
load_broker_standardization_parameters_with_states()
nonLocalBrokerMapCREATE(nonLocalMapFile="nonLocalBrokersToEIN")
localBrokerRevertMapCREATE(
addressMapFile="BrokerAddressZipcodeMap",
localRevertMapFile="localBrokerReversionMap",
)
nonLocalBrokerMap = pd.read_pickle(
dataDir + "brokers/nonLocalBrokersToEIN.pkl")
revertToLocalMap = pd.read_pickle(
dataDir + "brokers/localBrokerReversionMap.pkl")
brokAddressMap = pd.read_pickle(brokerDir + "/BrokerAddressZipcodeMap.pkl")
loadAllBrokers(FROM_DELME=False)
Create_Broker_Comm_Fee()
BrokerComp = pd.read_pickle(
dataDir + "brokers/BrokerCompensationByCarrier.pkl")
products = [
"All",
"Medical",
"Dental",
"Vision",
"Life",
"Disab",
"Stoploss",
"PBM",
"Other",
]
gc.collect()
here are the functions that are being called
in this entire code can u please help me identify what exact function is doing
-- coding: utf-8 --
"""
Created on Mon Mar 20 18:47:35 2023
@author: lkumarbln
"""
import os
import copy
import gc
import re
import pandas as pd
import numpy as np
from datetime import datetime
import time
import pickle
import string
from collections import OrderedDict
def execfile(filepath, gl=globals(), lc=locals()):
#filepath='geography.py'
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), gl, lc)
Execute the file.
execfile("/path/to/somefile.py")
global start_yr, end_yr
global datawd
global PrimaryPlanPerEIN, PlanLevelByYear, AdminByYear, PlanName, employerFields
global notMedicalCarrierStrings, notMedicalCarrierEINs
global BrokerComp, planEffectiveMap
print("Start callem.py")
TODO: Before running this script, please set the variables: rootDir, start_yr, and end_yr
rootDir_sync = "C:/Users/sswank/MetLife/Kumar B L N, Lohit - 20230303_MetLife code base transfer_vS_Python/GRIP codebase/"
#rootDir = "C:/Users/sswank/OneDrive - MetLife/Documents/Workplace/5500 Data Curation/20230303_MetLife code base transfer_vS/GRIP codebase/"
rootDir = "H:/5500 Curation run/2024 Run/"
global start_yr, end_yr
start_yr = 2009
end_yr = 2022
###- Your root directory should have two folders
1] For code, leave this as the existing repo
codewd = "H:/5500 Curation run/2024 Run/Code/"
os.chdir(codewd)
2] For data files, this should be set to your local machine. Do not store data on the repo
datawd = rootDir + "Data_files/"
def sub_set_root_directory_default(codewd):
codewd = codewd + "/Code/"
os.chdir(codewd)
return
sub_set_root_directory_default(rootDir)
execfile("config.py")
- Run this step ONLY ONCE, AT THE START OF THE REFRESH
Keep this commented for the rest of the run
#create_Endogenous_Parameters_initial(end_yr)
#createMeansAllYears(startYear = start_yr,
endYear = end_yr,
outDir = pitAllYearsDir)
- Set up Endogeneous parameters
loadEndogenousParameters(y=end_yr, baseDir=pitByYearDir, DETAILS=False)
loadVarsFromEndogenous()
- Set up Carrier standardization parameters
load_Carrier_Standardization_Parameters()
NOTE: changed this to output a var needed later
brokToParent = load_broker_Standardization_Parameters()
load_broker_Standardization_Parameters()
2.1.2 Prebase ----------------------------------------------------------------
- STEP 1 : DATA DOWNLOAD AND INITIAL CLEANING
start_time = time.time()
for y in range(start_yr, end_yr + 1):
print('already done')
filingsDownload(y=y, SF=False, outDir=sourceDir)
filingsInitClean(
y=y,
SF=False,
G=True,
RET=True,
SINK=False,
inDir=sourceDir,
outDirBase=pitByYearDir,
)
#print("--- %s seconds ---" % (time.time() - start_time))
- STEP 2 : PREPPING BASE FORMS AND SCHEDULES
start_time = time.time()
for y in range(start_yr, end_yr + 1):
callByYearDataGenPrep(y=y)
end_time = time.time()
print("--- %s seconds ---" % (end_time - start_time))
sys.stdout.close()
print(start_yr)
- STEP 3 : SEPARATING THE FILINGS BY YEAR AND LATE FILINGS
for file_name in [
"e5500.all",
"schA_prepped",
"schC_prepped",
"schR_prepped",
"schH_prepped",
]:
separateAndStackLateFilings(
files=[file_name],
startYr=start_yr,
endYr=end_yr,
thisDir=pitByYearDir,
SINK=False,
)
- STEP 4 : STACKING FILINGS AND CREATING PLAN LEVEL MAPS
start_time = time.time()
stackBaseFilingsForPlanLevelMaps(
inFile="e5500.all", startYr=start_yr, endYr=end_yr)
planNameByPN(
inFile="e5500.all_allYears",
inDir=pitAllYearsDir,
outFile="planNameByPN",
WELF_ONLY=False,
)
stackScheduleA(inFile="schA_prepped", startYr=start_yr, endYr=end_yr)
end_time = time.time()
time_taken =end_time - start_time
with open(f"{rootDir}/time_tracker.txt", "a") as f:
f.write(
f"'The time taken for creating e5500.all.allYears, planNamesByPN, schA_prepped_allYears is {time_taken}\n"
)
- STEP 5 : MERGING ALL SCHEDULES BY YEAR
gc.collect()
for y in range(start_yr, end_yr + 1):
start_time = time.time()
mergeSchedules_singleYr(
y=y,
WELF_ONLY=False,
RET_ONLY=False,
baseDir=pitByYearDir,
outFileBase="SchedAll",
)
end_time = time.time()
time_taken =end_time - start_time
with open(f"{rootDir}/time_tracker.txt", "a") as f:
f.write(
f"'The time taken to complete mergeAllSchedules module is {time_taken}\n"
)
Run till here### two days target
2.1.3 Carrier Standardization ------------------------------------------------
- STEP 6 : CARRIER STANDARDIZATION
Declare parameters
carrierDir = datawd + "carriers/"
start_yr = 2009
end_yr = 2022
COMPILE_CA = True
MANUAL_CLEAN = True
REGEN_NAME_CLEAN = True
REGEN_ADDR_CLEAN = True
REGEN_FUZZY = True
APPLY_FUZZY = True
1 Compile carrier information
if COMPILE_CA:
compileCarriersAllYrs(
startYr=start_yr,
endYr=end_yr,
thisDir=carrierDir,
baseInFile="SchedAll",
outFile="carriers.all.yrs.noClean",
)
2 Manual Cleaning
if MANUAL_CLEAN:
carriers_ManualCleanPreFuzzy(
inFile="carriers.all.yrs.noClean",
inDir=carrierDir,
outFile="carriers.all.yrs.BasicClean",
REGEN_NAME_CLEAN=REGEN_NAME_CLEAN,
REGEN_ADDR_CLEAN=REGEN_ADDR_CLEAN,
)
gc.collect()
3 Create Map using Fuzzy Match logic for carrier standardization
if REGEN_FUZZY:
CreateFuzzyMatchMap(
var="Carrier_Orig",
thisDir=carrierDir,
inFile="carriers.all.yrs.BasicClean",
outFile="carriers.all.yrs.FuzzyMapped",
)
4 Apply the Fuzzy map for carrier standardization
if APPLY_FUZZY:
applyFuzzyMatchMap(
var="Carrier_Orig",
thisDir=carrierDir,
inFile="carriers.all.yrs.BasicClean",
mappingFile="carriers.all.yrs.FuzzyMapped",
outFile="carriers.all.yrs.Cleaned",
)
5 Final step of carrier standardization
standardizeCarriers(
inFile="carriers.all.yrs.Cleaned",
inDir=carrierDir,
outFile="carriers.all.yrs.Standardized",
LOG=False,
)
6 Create map of Carriers and NAICs
carrierNAICxwalkCreate(inDir=carrierDir)
7 Create map of Carriers and Carrier EINs
carrierEINXwalkCreate(
inFile="carriers.all.yrs.Standardized", inDir=carrierDir, outFile="carrierEINxwalk"
)
import gc
gc.collect()
2.1.4 Broker Standardization -------------------------------------------------
- STEP 7 : BROKER STANDARDIZATION
Broker cleaining
COMPILE = True
MANUAL_CLEAN = True
REGEN_NAME_CLEAN = True
REGEN_ADDR_CLEAN = True
REGEN_FUZZY = True
APPLY_FUZZY = True
STANDARDIZE = True
APPEND_BASE_FIELDS = True
start_yr = 2009
endYr = 2022
brokerDir = datawd + "brokers/"
1 Compile broker information
print("Begin broker information")
if COMPILE:
compileBrokersAllYrs(
startYr=start_yr,
endYr=end_yr,
thisDir=brokerDir,
outFile="brokers.all.yrs.noClean",
)
2 Manual cleaning
if MANUAL_CLEAN:
brokers_manualClean(
inFile="brokers.all.yrs.noClean",
outFile="brokers.all.yrs.BasicClean",
thisDir=brokerDir,
REGEN_NAME_CLEAN=True,
REGEN_ADDR_CLEAN=True,
)
3 Create map using Fuzzy Match logic for broker standardization
if REGEN_FUZZY:
CreateFuzzyMatchMap(
var="BROKER_NAME",
thisDir=brokerDir,
inFile="brokers.all.yrs.BasicClean",
outFile="brokers.all.yrs.FuzzyMapped",
)
from datetime import datetime
4 Apply fuzzy map for broker standardization
if APPLY_FUZZY:
applyFuzzyMatchMap(
var="BROKER_NAME",
thisDir=brokerDir,
inFile="brokers.all.yrs.BasicClean",
mappingFile="brokers.all.yrs.FuzzyMapped",
outFile="brokers.all.yrs.Cleaned",
)
5 Final step of carrier standardization
if STANDARDIZE:
standardizeBROKER(
thisDir=brokerDir,
inFile="brokers.all.yrs.Cleaned",
outFile="brokers.all.yrs.Standardized.B4Address",
)
standardizeBROKERwithADDRESS(
thisDir=brokerDir,
PRINT_QC=False,
inFile="brokers.all.yrs.Standardized.B4Address",
addressMapFile="BrokerAddressZipcodeMap",
baseInFile="brokers.all.yrs.noClean",
outFile="brokers.StandardizedStaging",
)
6 Append Base filing information to the broker standardization
if APPEND_BASE_FIELDS:
appendBaseFields(infile="brokers.StandardizedStaging")
#completd work till here on 1/21
2.1.5 Creation of Plan and Employer level fields -----------------------------
- STEP 8 : CREATE PLAN, EMPLOYER RELATED FILES
NOTE: this python code wasn't here before. Adding in
planAdminByYearCREATE()
planLevelWelfareLOBSByYear(WELF_ONLY = True)
planNameByPN(inDir = pitAllYearsDir, WELF_ONLY = True)
PNandPlanNameByEINxProduct(WELF_ONLY = True)
employerLevelFieldsCREATE(WELF_ONLY = True)
planEffectiveDatebyPN(WELF_ONLY = True)
map_rawGroupAddress()
2.2. Primary Broker Creation
start_time=time.time()
start_yr = 2009
end_yr = 2022
startYr = 2009
endYr = 2022
- STEP 9 : BROKER LOCATION ADJUSTMENTS AND PRIMARY BROKER CREATION
groupByVars = ["State_HQ", "EIN", "PN"]
brokFlowsBase = "brokInflowOutflow"
brokToBrokBase = "brokToBrokerFlows"
endYr = end_yr
2.2.1 Broker location adjustment -----------------------------------------
load_broker_standardization_parameters_with_states()
nonLocalBrokerMapCREATE(nonLocalMapFile="nonLocalBrokersToEIN")
localBrokerRevertMapCREATE(
addressMapFile="BrokerAddressZipcodeMap",
localRevertMapFile="localBrokerReversionMap",
)
nonLocalBrokerMap = pd.read_pickle(
dataDir + "brokers/nonLocalBrokersToEIN.pkl")
revertToLocalMap = pd.read_pickle(
dataDir + "brokers/localBrokerReversionMap.pkl")
brokAddressMap = pd.read_pickle(brokerDir + "/BrokerAddressZipcodeMap.pkl")
loadAllBrokers(FROM_DELME=False)
Create_Broker_Comm_Fee()
BrokerComp = pd.read_pickle(
dataDir + "brokers/BrokerCompensationByCarrier.pkl")
products = [
"All",
"Medical",
"Dental",
"Vision",
"Life",
"Disab",
"Stoploss",
"PBM",
"Other",
]
gc.collect()
2.2.2 Primary broker identification --------------------------------------
groupBrokerAddressMap(
groupByVars=groupByVars, globalEnvtOutNm="groupToBrokToAddr"
) # takes 1-2 mins to run
employerFields = pd.read_pickle(
dataDir + "/employerAndPlanLevelFields/" + "employerLevelFields_Welfare.pkl"
)
agForEINtoBroker(
groupByVars=["State_HQ", "EIN", "PN"],
agInFileBase="brokersAggregated_byEIN"
) # takes 8-9 mins to run, some aggregation is present, hence more time consuming
for p in products:
createPrimaryBrokerMap(
product=p,
groupByVars=groupByVars,
agInFileBase="brokersAggregated_byEIN",
outFileBase="primaryBroker_byEIN",
)
compilePrimaryBrokers(outFile="primaryBroker_byEINPN_merged")
loadBrokerPrimary(inFile="primaryBroker_byEINPN_merged")
gc.collect()
end_time = time.time()
time_taken = end_time - start_time
with open(f"{rootDir}/time_tracker.txt", "a") as f:
f.write(
f"'The time taken for creation of primary broker table [Broker standardization part 2] is {time_taken}\n"
)
2.3. Imputation and PIT transformation
print("Starting Imputation & PIT Transformation ")
start_time = time.time()
2.3.1 Impute_LOB -------------------------------------------------------------
- STEP 10 : IMPUTE LINE OF BUSINESSES
Remove large files from the environment
list_files = [
"brokStd",
"carStd",
"carStdwelf",
"PrimaryBrokerMapping",
"BrokerComp",
"beforeSuffix",
"beforeEndTerms",
"groupToBrokToAddr",
"beforeFIRST",
"employerFields",
]
for file in list_files:
try:
del globals()[file]
except:
print("Didn't remove file from env:", file)
gc.collect()
Load Endogenous parameters for all years
loadEndogenousParametersAll(baseDir=pitByYearDir)
Execute ImputeLOB function
start_time = time.time()
Comment out once you run once. Takes a little over 1 hour to run for 1 year
for y in range(end_yr, start_yr - 1, -1):
impute_lob(y=y, inFile="welfSchedAll", outFile="welfImputeLob", SINK=True)
gc.collect()
end_time = time.time()
time_taken = end_time - start_time
with open(rootDir + "/time_tracker.txt", "a") as f:
f.write(
f"The time taken to complete imputeLob module is {round(time_taken / 3600, 2)} hours.\n"
)
- STEP 11 : STACK OUTPUT OF IMPUTE_LOB
start_time = time.time()
stackImpLobAndFback(
fileNm="welfImputeLob", outFile="welfImputeLob", startYr=start_yr, endYr=end_yr
)
end_time = time.time()
time_taken = end_time - start_time
with open(rootDir + "/time_tracker.txt", "a") as f:
f.write(
f"The time taken to complete stack imputeLob module is {round(time_taken / 3600, 2)} hours.\n"
)
INTERMEDIATE STEP : CLEAN IMPUTELOB PARAMETERS
FOR IMPUTE_LOB, WE HAVE ADDED ENDOGENOUS PARAMETERS FOR ALL YEARS
THIS MAY DISTURB THE COMPUTATIONS IN FURTHER STEPS
TO AVOID THIS, WE CLEAN THESE FILES.
if "endogenousParamsDt" in globals():
# Remove the parameters
param_list = endogenousParamsDt.query(f"Year == {start_yr}")["PARAMETER"]
for param in param_list:
del globals()[param]
for var in list(globals().keys()):
if "memb_to_emp" in var:
del globals()[var]
del globals()["endogenousParamsDt"]
del globals()["pmpm_thresh_fi"]
del globals()["pmpm_thresh_aso"]
# Reload the parameters
loadEndogenousParameters(y=end_yr, baseDir=pitByYearDir, DETAILS=False)
loadVarsFromEndogenous()
2.3.2 Funding Reclassification -----------------------------------------------
- STEP 12 : EXECUTE FUNCDING RECLASSIFICATION
start_time = time.time()
fundingReclassTriage(
startYr=start_yr,
endYr=end_yr,
SINK=False,
inFile="welfImputeLob",
outFileFundingKnown="fundingKnownAppend",
outFileForReclass="forReclass",
)
gc.collect()
fundingReclass(
startYr=start_yr,
endYr=end_yr,
inFile="forReclass",
outFile="fundingReclass",
SINK=False,
)
gc.collect()
fundingBindKnownAndUnknown(
inFile="fundingReclass",
inFileKnown="fundingKnownAppend",
startYr=start_yr,
endYr=end_yr,
outFile="welfFunding",
)
gc.collect()
end_time = time.time()
time_taken = end_time - start_time
with open(rootDir + "/time_tracker.txt", "a") as f:
f.write(
f"The time taken to complete funding reclassification module is {round(time_taken / 3600, 2)} hours.\n"
)
2.3.3 Member & Premium Adjustment --------------------------------------------
- STEP 13 : EXECUTE MEMBER AND PREMIUM ADJUSTMENT
start_time = time.time()
schAmemberAdjust(
startYr=start_yr,
endYr=end_yr,
inFile="welfFunding",
outFile="schAmemberAdjust",
SINK=False,
)
gc.collect()
schCmemberAdjust(
startYr=start_yr,
endYr=end_yr,
inFile="schAmemberAdjust",
outFile="schCmemberAdjust",
SINK=False,
)
gc.collect()
end_time = time.time()
time_taken = end_time - start_time
with open(rootDir + "/time_tracker.txt", "a") as f:
f.write(
f"The time taken to complete member and premium adjustment module is {round(time_taken / 3600, 2)} hours.\n"
)
- INTERMEDIATE STEP : CLEAN OLD ENDOGENOUS PARAMETERS AND CREATE NEW SET
WE DELETE OLD PARAMETERS AND CREATE NEW SET
THEN WE LOAD NEW PARAMETERS
Remove the parameters
for var in list(globals().keys()):
if "memb_to_emp" in var or "pmpm_fi" in var or "pmpm_aso" in var:
del globals()[var]
try:
del globals()["pmpm_thresh_fi"]
del globals()["pmpm_thresh_aso"]
except:
print('np')
create new parameters
NOTE: the following function takes a while to run
create_Endogenous_Parameters_final()
createMeansAllYears(startYear=end_yr, endYear=end_yr, outDir=pitAllYearsDir)
Reload the parameters
loadEndogenousParameters(y=end_yr, baseDir=pitByYearDir, DETAILS=False)
loadVarsFromEndogenous()
2.3.4 FTE mapping and Identification of Direct groups ------------------------
- STEP 14 : CREATION OF FTE FILE AND FLAGGING DIRECT GROUP
start_time = time.time()
infile = f"schCmemberAdjust_{start_yr}to{end_yr}"
create_EIN_FTE_file(infile=infile, outfile="Mapping_EIN_FTE")
FlagDirectGroup()
end_time = time.time()
time_taken = end_time - start_time
with open(rootDir + "/time_tracker.txt", "a") as f:
f.write(
f"The time taken to complete ein_fte_mapping and direct broker flagging is {round(time_taken / 3600, 2)} hours.\n"
)
2.3.5 to 2.3.7 PIT generation ------------------------------------------------
- STEP 15 : PIT GENERATION
start_time = time.time()
Loading necessary information
loadVarsFromEndogenous()
endYr = end_yr
prods = [
"Medical",
"Dental",
"Life",
"LTD",
"STD",
"Vision",
"CI",
"Accident",
"Hospital",
"Legal",
"Stoploss",
"PBM",
]
allprods = [
"Medical",
"Dental",
"Life",
"LTD",
"STD",
"Vision",
"CI",
"Accident",
"Hospital",
"Legal",
"Stoploss",
"PBM",
]
CoreProducts = ["Medical", "Dental", "Life",
"LTD", "STD", "Stoploss", "PBM", "Vision"]
QCvars = [
"Year",
"State_HQ",
"EIN",
"PN",
"Members",
"Part_EOY",
"Funding",
"Sch",
"Rules",
"Carrier",
]
Transforming data into PIT format by product
PrimaryPlanPerEIN = pd.read_pickle(employer_dir + "EINxProduct_to_PN.pkl")
PrimaryPlanPerEIN.PN=PrimaryPlanPerEIN.PN.astype(str).str.split('.',expand=True)[0]
PlanLevelByYear = pd.read_pickle(
employer_dir + "planLevelWelfareOfferings.pkl")
PlanLevelByYear.PN=PlanLevelByYear.PN.astype(str).str.split('.',expand=True)[0]
AdminByYear = pd.read_pickle(employer_dir + "planAdminStandardizedByYear.pkl")
PlanName = pd.read_pickle(employer_dir + "planNameByPN.pkl")
employerFields = pd.read_pickle(
dataDir + "/employerAndPlanLevelFields/" + "employerLevelFields_Welfare.pkl"
)
employerFields.rename(columns={"Phone": "Admin_Phone"}, inplace=True)
Function for preparation before transforming data into PIT format
infile = f"schCmemberAdjust_{start_yr}to{end_yr}"
#i ran ttill her 12/21 12 25 pm
PIT_allYear_transform_prep(
inDir=pitAllYearsDir,
inFile=infile,
SINK=False,
CoreProducts=CoreProducts,
allprods=allprods,
outFile="StackedFinal.pkl",
outDir=dataDir + "pit/PIT_transform_Intermediate/",
)
del globals()[infile]
gc.collect()
Transforming data into PIT format by product
notMedicalCarrierStrings = carrier_exact.query("NOT_MEDICAL == 1")[
"Carrier_String"
].unique()
notMedicalCarrierEINs = carrier_exact.query("NOT_MEDICAL == 1")["EIN"].unique()
prods = [
"Medical",
"Dental",
"Life",
"LTD",
"STD",
"Vision",
"CI",
"Accident",
"Hospital",
"Legal",
"Stoploss",
"PBM",
]
for p in prods:
p='Hospital'
PIT_transformation(
p=p,
BY_PN=True,
endYr=endYr,
lastimputeyear=end_yr,
intermDir="pit/PIT_transform_Intermediate/",
outDir="pit/",
out_sub="EINxProdxCarrier_",
RECREATE_INTERM=True,
PrintSample=False,
SINK=False,
)
gc.collect()
Stacking PITs by products
prods = [
"Medical",
"Dental",
"Life",
"LTD",
"STD",
"Vision",
"CI",
"Accident",
"Hospital",
"Legal",
"Stoploss",
"PBM",
]
NOTE: using converted 2009_2022 files from original R code to ensure correct input data
start_yr = 2009
stacking(
prods=prods,
inDir="pit/",
in_sub="EINxProdxCarrier_",
outDir="pit/",
out_sub="EINxProdxCarrier_",
maxy=end_yr,
)
Enhancing PIT with Broker information
planEffectiveMap = pd.read_pickle(employer_dir + "planEffectiveDateByPN.pkl")
planEffectiveMap["PN"] = planEffectiveMap["PN"].astype(str)
BrokerComp = pd.read_pickle(brokerDir + "/BrokerCompensationByCarrier.pkl")
nonLocalBrokerMap = pd.read_pickle(brokerDir + "/nonLocalBrokersToEIN.pkl")
revertToLocalMap = pd.read_pickle(brokerDir + "/localBrokerReversionMap.pkl")
brokAddressMap = pd.read_pickle(brokerDir + "/BrokerAddressZipcodeMap.pkl")
loadBrokerPrimary(inFile="primaryBroker_byEINPN_merged")
gc.collect()
#Load or change in gloabl einxprod_al
#load EIN is pending
loadEINxProduct_allProducts_part1(endYear = end_yr,
REGEN_PIT = True)
remove_RecordsFromPit(start_yr, end_yr)
loadEINxProduct_allProducts_part2()
broker_rawNames_associate()
adHocCarrierAndMemberAdjustment(start_yr, end_yr)
end_time = time.time()
time_taken = end_time - start_time
with open(rootDir + "/time_tracker.txt", "a") as f:
f.write(
f"The time taken to complete PIT generation Part 1 process is {round(time_taken / 3600, 2)} hours.\n"
)
2.4. Product Longitudinal Generation
einxprod_all.PN
- STEP 16 : GENERATION OF PRODUCT LONGITUDINAL FILES
einxprod_all = pd.read_pickle(os.path.join(wd_delme, "einxprod_all.pkl"))
employerFields = pd.read_pickle(
dataDir + "/employerAndPlanLevelFields/" + "employerLevelFields_Welfare.pkl"
)
if "Phone" in employerFields.columns:
employerFields = employerFields.rename(columns={"Phone": "Admin_Phone"})
planEffectiveMap = pd.read_pickle(employer_dir + "planEffectiveDateByPN.pkl")
planEffectiveMap["PN"] = planEffectiveMap["PN"].astype(str)
longDataDir = dataDir + "longitudinal/"
volProducts = ["CI", "Hospital", "Accident"]
productsRefresh = CoreProducts + volProducts + ["Legal"]
missingUp = [""] + [imputed_term.upper()] + [imputed_term]
prods = list(set(productsRefresh) - set(["Legal"]))
basePost = ["_Base", "Post"]
yrSuffix = ["" + str(yr) for yr in range(start_yr, end_yr + 1)]
varSuff = [""] + basePost + yrSuffix
basePostVars = [
"Carrier",
"Carrier_Orig",
"Carrier_EIN",
"Broker",
"BrokerComp",
"Broker_State",
"Broker_Zip",
"Members",
"Premiums",
"Funding",
"Sch",
"EIN_FTE",
"Part_EOY",
"Plan_LOBs",
"BrokerCrossProduct",
"BrokerCrossProductZIP",
"Admin",
"Admin_Orig",
"HMO",
"PN",
"CTR_NUM",
"CTR_NUM2",
"Renewal_Month",
"Accounts",
"Rules",
"PN_Orig",
]
basePostOnly = [
"Admin_Orig",
"CTR_NUM2",
"Renewal_Month",
"PN",
"Broker_State",
"BrokerCrossProductZIP",
"Carrier_EIN",
"EIN_FTE",
"HMO",
]
di = list(set(basePostOnly) - set(basePostVars))
gc.collect()
if len(di) > 0:
raise Exception("\nMssing from basePost vars.." + str(di))
basePostVars_all = [var + post for var in basePostVars for post in basePost]
byYearVars = list(set(basePostVars) - set(basePostOnly))
byYearVars_allYears = [var + yr for var in byYearVars for yr in yrSuffix]
appendedAccountsTag = "end_yrAppend_missingInLong"
keyIdFields = [
"Group",
"EIN",
"State_HQ",
"County",
"City",
"Zipcode",
"Broker_State",
"Broker_Zip",
"Region",
"Plan_Name",
]
industryVars = ["Industry", "Sub_Industry", "Detailed_Industry"]
additionalIdFields = (
["Admin_Orig", "Admin_Phone", "Union", "MEWA", "Multiemp"]
+ industryVars
+ ["Zipcode", "City", "Address", "PN", "EIN_FTE", "Group_Orig"]
)
prospectV1_addFeatures = ["Renewal_Month", "YrsInGRIP"]
gc.collect()
secondaryAccountsByProduct_create(outDir=dataDir + "BundlingAndProduct")
for p in prods:
print("\n STARTING FOR PRODUCT ", p)
# folderpath = longDataDir + 'temp/' + p.lower()
# os.makedirs(folderpath)
print("\n Directory created ", longDataDir + "/temp/" + p.lower(), "\n")
longMatchTriage(product=p, startYr=start_yr, endYr=end_yr, SINK=False)
for p in prods:
print("\n STARTING FOR PRODUCT ", p)
convertMatchesToBasePost(
product=p, startYr=start_yr, endYr=end_yr, matchFiles=matchFiles, SINK=False
)
gc.collect()
for p in prods:
print("\n STARTING FOR PRODUCT ", p, "\n.")
longitudinalDaisyChain(
product=p, startYr=start_yr, endYr=end_yr, outFileBase="daisyChain", SINK=False
)
for p in prods:
finalLongitudinalPrep(
product=p, startYr=start_yr, endFinal=end_yr, SINK=False,
PRINT_NONSTD=False
)
for p in prods:
print("\n STARTING LOADLONGITUDINALTRANSITIONS FOR ", p)
loadLongitudinalTransitionsData_debug(product=p)
gc.collect()
end_time = time.time()
time_taken = end_time - start_time
with open(rootDir + "/time_tracker.txt", "a") as f:
f.write(
"The time taken to complete Product Longitudinal process is "
+ format(round(time_taken / 3600, 3), ".2f")
+ " hours.\n"
)
gc.collect()
# 2.5. Dependent file generation
###- STEP 17 : GENERATION OF DEPENDENT FILES
start_time_fin = pd.Timestamp.now()
os.system("ulimit -S -n 2048")
global einxprod_all
einxprod_all = pd.read_pickle(os.path.join(wd_delme, "einxprod_all.pkl"))
nonLocalBrokerMap = pd.read_pickle(
os.path.join(dataDir, "brokers/nonLocalBrokersToEIN.pkl"))
revertToLocalMap = pd.read_pickle(
os.path.join(dataDir, "brokers/localBrokerReversionMap.pkl"))
brokAddressMap = pd.read_pickle(brokerDir + "/BrokerAddressZipcodeMap.pkl")
employerFields = pd.read_pickle(dataDir + "/employerAndPlanLevelFields/" + "employerLevelFields_Welfare.pkl")
if "Phone" in employerFields.columns:
employerFields.rename(columns={"Phone": "Admin_Phone"}, inplace=True)
planEffectiveMap = pd.read_pickle(
os.path.join(employer_dir, "planEffectiveDateByPN.pkl"))
planEffectiveMap["PN"] = planEffectiveMap["PN"].astype(str).str.split(".",expand=True)[0]
inFile = f"EINxProdxCarrier__{start_yr}_{end_yr}.pkl"
print(f"\nLoad {inFile}")
if "einXProdBaseDt" not in globals():
einXProdBaseDt = pd.read_pickle(os.path.join(dataDir, "pit/", inFile))
einXProdBaseDt.PN=einXProdBaseDt.PN.astype(str)
einxprod_all.PN=einxprod_all.PN.astype(str)
# 2.einXProdBaseDt.1 Broker Longitudinal --------------------------------------------------
start_time = pd.Timestamp.now()
loadAllBrokers(UPDATE_FILE=False)
for p in ["Medical", "Dental", "Life", "LTD", "STD", "Vision"]:
print("Starting EINLevelPrimaryCarrierByProductCREATE for product:", p)
EINLevelPrimaryCarrierByProductCREATE(
dt=einxprod_all.copy(), product=p, outDir=employer_dir)
brokerLongitudinal(product="all")
end_time = pd.Timestamp.now()
time_taken = end_time - start_time
with open(os.path.join(rootDir, "time_tracker.txt"), "a") as f:
f.write(
f"The time taken to complete Broker Longitudinal process is {round(time_taken.total_seconds() / 3600, 2)} hours.\n")
gc.collect()
# 2.5.2 Product Bundling -----------------------------------------------------
start_time_prod_bund = pd.Timestamp.now()
CoreProducts = ["Medical", "Dental", "Life", "LTD", "STD", "Vision", "Stoploss", "PBM"]
volProducts = ["CI", "Hospital", "Accident"]
productsRefresh = CoreProducts + volProducts + ["Legal"]
inFile = f"EINxProdxCarrier__{start_yr}_{end_yr}.pkl"
print(f"\nLoad {inFile}")
if "einXProdBaseDt" not in globals():
einXProdBaseDt = pd.read_pickle(os.path.join(dataDir, "pit/", inFile))
NOTE: validation here
secondaryAccountsByProduct_create(outDir=os.path.join(dataDir, "BundlingAndProduct"))
create_ProductFeatures_bundling_updated(
PIT=einXProdBaseDt.copy(),
allLobs=productsRefresh,
SINK=False,
out_dir_sub="BundlingAndProduct",
outFile="EIN_Product_bundling",
BCBS_rollup=True,
exclude_PBMandStoploss=True)
end_time_prod_bund = pd.Timestamp.now()
time_taken = end_time_prod_bund - start_time_prod_bund
with open(os.path.join(rootDir, "time_tracker.txt"), "a") as f:
f.write(
f"The time taken to complete Product Bundling process is {round(time_taken.total_seconds() / 3600, 2)} hours.\n")
gc.collect()
2.5.3 BrokerxCarrier Share -------------------------------------------------
start_time = pd.Timestamp.now()
dt_sharedata = datagen_CarrierXBrokerShares(
standOnly=True,
saveOutputRDS=True,
outFile="shares_brokerXcarrier",
outDir=os.path.join(dataDir, "penetrationAndShare/"),
BCBS_rollup=True)
end_time = pd.Timestamp.now()
time_taken = end_time - start_time
with open(os.path.join(rootDir, "time_tracker.txt"), "a") as f:
f.write(
f"The time taken to complete creation shareBrokerXCarrier is {round(time_taken.total_seconds() / 3600, 2)} hours.\n")
gc.collect()
2.5.4 Carrier per Group ----------------------------------------------------
start_time = pd.Timestamp.now()
dt_carr_per_grp = datagen_carriers_per_group(
PIT=einXProdBaseDt,
saveFile=True,
returnDataTable=True,
outFile="EINxYear_carriers_per_group",
outDir=employer_dir,
BCBS_rollup=True,
exclude_PBMandStoploss=True)
end_time = pd.Timestamp.now()
time_taken = end_time - start_time
with open(os.path.join(rootDir, "time_tracker.txt"), "a") as f:
f.write(
f"The time taken to complete creation of CarrierPerGroup is {round(time_taken.total_seconds() / 3600, 2)} hours.\n")
gc.collect()
2.5.5 Member Change --------------------------------------------------------
start_time = pd.Timestamp.now()
dt_member_change = datagen_group_change_in_members_FIXED(
PIT=einXProdBaseDt,
rawChange_thresh=100,
outFile="EINxYear_member_change_FIXED",
outDir=employer_dir,
pctChange_thresh=0.1,
saveFile=True,
returnDataTable=True,
BCBS_rollup=True,
exclude_PBMandStoploss=True)
end_time = pd.Timestamp.now()
time_taken = end_time - start_time
with open(os.path.join(rootDir, "time_tracker.txt"), "a") as f:
f.write(f"The time taken to complete creation MemberChange is {round(time_taken.total_seconds() / 3600, 2)} hours.\n")
gc.collect()
2.5.6 Empirical switching --------------------------------------------------
start_time = pd.Timestamp.now()
createEmpiricalSwitchingAccount(
products=["Medical", "Dental", "Life", "STD", "LTD", "Vision"])
end_time = pd.Timestamp.now()
time_taken = end_time - start_time
with open(os.path.join(rootDir, "time_tracker.txt"), "a") as f:
f.write(f"The time taken to complete Empirical switching process is {round(time_taken.total_seconds() / 3600, 2)} hours.\n")
#2.6. Final formatting and Quality check ######################################
#2.6.1 Final formatting and file export ---------------------------------------
#- STEP 18 : FINAL FORMATTING
#For PIT
end_yr=2022
create_GAIN_PIT(
start_yr=start_yr,
end_yr=end_yr,
BCBS_rollup=True,
thisdate=dateSuffix,
metTransferPrefix="GAIN_McKinsey_")
For PIT_StandardizedGroupExtract
create_PIT_StandardizedGroupExtract(
thisdate=dateSuffix,
metTransferPrefix="GAIN_McKinsey_",
outFile="PIT_extract_standardizedGroupNames_")
For Product Bundling
create_GAIN_Product_Bundling(thisdate=dateSuffix, metTransferPrefix="GAIN_McKinsey_")
For Member Change
create_GAIN_MemberChange(thisdate=dateSuffix, metTransferPrefix="GAIN_McKinsey_")
For Carrier Per Group
create_GAIN_CarrierPerGroup(thisdate=dateSuffix, metTransferPrefix="GAIN_McKinsey_")
For Share BrokerXCarrier
create_GAIN_BrokerXCarrierShare(thisdate=dateSuffix, metTransferPrefix="GAIN_McKinsey_")
For Broker Longitudinal
create_GAIN_BrokerLongitudinal(thisdate=dateSuffix, metTransferPrefix="GAIN_McKinsey_")
For Empirical Switching
create_GAIN_EmpiricalSwitching(thisdate=dateSuffix, metTransferPrefix="GAIN_McKinsey_")
For Product Longitudinal
create_GAIN_ProductLongitudinal(BCBS_rollup=True, thisdate=dateSuffix, metTransferPrefix="GAIN_McKinsey_")
GenerateProfileReport(dateForInfile = dateSuffix,
metTransferPrefix = "GAIN_McKinsey_")
#InputValidationAuto(dateForInfile = dateSuffix,
metTransferPrefix = "GAIN_McKinsey_")
execfile("H:/5500 Curation run/2024 Run/Code/Metlife_Customizations/broker_tittle_fix.py")
brokerDir