Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Created on Tue Sep 17 11:17:54 2019
- @author: Fmeessen
- """
- import tensorflow_core.keras as keras
- #import keras
- import numpy as np
- import pandas as pd
- import os
- from pprint import pprint
- ragged = False
- class ProxyModel:
- '''Object for loading in the neural networks and for marking predictions.
- Args:
- folder_path(str): Path to the folder where the models (json and hdf5
- files) are located. By default, it assumes that it is in the
- current working directory.
- Attributes:
- bl_dict(dict): Dictionary of the loaded neural networks. The dictionary
- is structrued as follows:
- {
- 'BE': {
- 'FLV': model,
- 'Klassik1': model,
- 'Klassik2': model,
- },
- 'rismar': {
- 'FLV': model,
- 'Klassik1': model,
- 'Klassik2': model,
- }
- }
- prediction_dict(dict): Dictionary of the predictions by the neural
- network based on the given input array. The structure of the
- dictionary is the same as of the bl_dict.
- '''
- def __init__(self, folder_path = 'models/'):
- self.bl_dict = {
- 'BE': {
- 'FLV': None,
- 'Klassik1': None,
- 'Klassik2': None,
- },
- 'rismar': {
- 'FLV': None,
- 'Klassik1': None,
- 'Klassik2': None,
- }
- }
- self.folder_path = folder_path
- self.prediction_dict = self.bl_dict.copy()
- def predict(self, bus_line, input_array):
- '''Make Predictions for both KPIs and all business lines.
- Args:
- input_array(np.ndarray): The x values based upon which the predictions
- are made.
- Returns:
- prediction_dict(dict): Dictionary, sorted by KPI then by business
- line of the corresponding predictions.
- '''
- #print('Predicting...')
- for kpi_name, kpi_businesslines in self.bl_dict.items():
- self.bl_dict[kpi_name][bus_line] = model = self.load_model(bus_line, kpi_name)
- self.prediction_dict[kpi_name][bus_line] = model.predict(input_array)
- #for bl, model in kpi_businesslines.items():
- # self.prediction_dict[kpi_name][bl] = model.predict(input_array)
- #print('Finished prediction.')
- return self.prediction_dict
- def predict_all(self, bus_line, input_array):
- '''Make Predictions for both KPIs and all business lines.
- Args:
- input_array(np.ndarray): The x values based upon which the predictions
- are made.
- Returns:
- prediction_dict_all(dict): Dictionary, sorted by KPI then by business
- line of the corresponding predictions.
- '''
- #print('Predicting all...')
- for kpi_name, kpi_businesslines in self.bl_dict.items():
- for bl, model in kpi_businesslines.items():
- self.prediction_dict_all[kpi_name][bl] = model.predict(input_array)
- #print('Finished all predictions.')
- return self.prediction_dict_all
- def load_model(self, business_line, kpi):
- '''Load model specification and weights from disk.
- Args:
- business_line(str): Corresponding Business Line (FLV, K1, K2).
- kpi(str): Corresponding KPI (BE or rismar).
- Returns:
- loaded_model(keras model): Corresponding keras model .
- '''
- file_name = self.folder_path + business_line + '_' + kpi
- # loading model
- json_file = open(file_name + '_model.json' )
- loaded_model_json = json_file.read()
- json_file.close()
- loaded_model = keras.models.model_from_json(loaded_model_json)
- # loading weights
- loaded_model.load_weights(file_name + '_weights.hdf5')
- #print('Loaded model from disk:', file_name)
- return loaded_model
- def load_all_models(self):
- '''Load all models into the business line dictionary.'''
- for kpi_name, kpi_businesslines in self.bl_dict.items():
- for bl in kpi_businesslines:
- self.bl_dict[kpi_name][bl] = self.load_model(bl, kpi_name)
- return self
- def get_EQ(self):
- return 650000000
- def get_RE(self):
- return 1037109768
- def get_FI_rate_down(self):
- return 4992928194 #calculated by using interests rate
- def get_FI_rate_up(self):
- return 4441480295 #calculated by using interests rate
- def get_OF_BE(self):
- return 6000000000
- def get_OF(self, BEL, RISMAR, FI):
- EQ = self.get_EQ()
- RE = self.get_RE()
- #pprint(":::FI")
- #pprint(FI)
- MW = float(EQ) + float(RE) + float(FI)
- OF = float(MW) - float(BEL) - float(RISMAR)
- #print("==============")
- #print("====EQ:: " + str(EQ))
- #print("====RE:: " + str(RE))
- #print("====FI:: " + str(FI))
- #print("====MW:: " + str(MW))
- #print("====BEL:: " + str(BEL))
- #print("====RISMAR:: " + str(RISMAR))
- #print("====OF:: " + str(OF))
- return OF
- def get_SCR(self, BEL, RISMAR):
- #cashflow = self.cashflow()
- #FI_rate_down = self.get_FI(cashflow, interestCurve)
- #FI_rate_up =
- OF_rate_down = self.get_OF(BEL, RISMAR, self.get_FI_rate_down())
- OF_rate_up = self.get_OF(BEL, RISMAR, self.get_FI_rate_up())
- OF_BE = self.get_OF_BE()
- SCR1 = OF_rate_down - OF_BE
- SCR2 = OF_rate_up - OF_BE
- #print("==============")
- #print("====OF_rate_down:: " + str(OF_rate_down))
- #print("====OF_rate_up:: " + str(OF_rate_up))
- #print("====OF_BE:: " + str(OF_BE))
- #print("====SCR1:: " + str(SCR1))
- #print("====SCR2:: " + str(SCR2))
- corr_mat = np.array([[0.5 ,0.5],[0.5, 0.5]])
- SCR_mat = np.array([[SCR1, SCR2]])
- SCR_mat_T = np.array([[SCR1], [SCR2]])
- SCR_mat_temp = np.matmul(SCR_mat, corr_mat)
- SCR = np.matmul(SCR_mat_temp, SCR_mat_T)
- return SCR[0][0] / 1000000000
- def interestCurve(self):
- points = pd.read_csv("models/interest_curve.csv", encoding = "utf8", header=None)
- return np.array(points)
- def cashflow(self):
- points = pd.read_csv("models/cashflow.csv", encoding = "utf8", header=None)
- return np.array(points)
- def stressedInterestCurve(self, shift, scale):
- interestCurve = self.interestCurve()
- points = []
- i = 0
- for x in np.nditer(interestCurve):
- points.append([(float(x) + float(shift)) * float(scale)])
- i = i + 1
- return np.array(points)
- def interestFactorList(self, stressedInterestCurve):
- iflist = []
- prev = 1.0
- i = 0
- for ic in stressedInterestCurve:
- inserted = prev / (1.0 + float(ic))
- iflist.append(inserted)
- prev = inserted
- i = i + 1
- return iflist
- def get_FI(self, cashflow, interestFactors):
- total = 0.0
- i = 0
- for ifx in interestFactors:
- prod = interestFactors[i] * cashflow[i]
- total = total + prod
- return total
- class Octopus:
- def __init__(self):
- # Singleton
- self.ProxyClass = ProxyModel()
- def data(self, busLine, shift=None, scale=None, alpha=None, sigma=None):
- if shift is None :
- shift = 0
- if scale is None :
- scale = 1
- if alpha is None :
- alpha = 0.1
- if sigma is None :
- sigma = 0.0145
- print('BL: '+busLine+'; '+'shift: '+str(shift)+'; '+'scale: '+str(scale)+'; '+'alpha: '+str(alpha)+'; ' +'sigma: '+str(sigma)+';')
- x = np.array([[shift, scale, 0, 0, alpha, sigma, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]])
- predictions = self.ProxyClass.predict(busLine, x)
- dataKPI = {}
- for kpi, values in predictions.items():
- dataKPI[kpi] = values[busLine][0][0].item()
- BEL = dataKPI['BE']
- RISMAR = dataKPI['rismar']
- stressedInterestCurve = self.ProxyClass.stressedInterestCurve(shift, scale)
- interestFactors = self.ProxyClass.interestFactorList(stressedInterestCurve)
- cashflow = self.ProxyClass.cashflow()
- FI = self.ProxyClass.get_FI(cashflow, interestFactors)
- OF = self.ProxyClass.get_OF(BEL, RISMAR, FI)
- dataKPI['OF'] = OF
- SCR = self.ProxyClass.get_SCR(BEL, RISMAR);
- dataKPI['SCR'] = SCR
- # String formatted
- dataKPI['BE'] = self.number(dataKPI['BE'])
- dataKPI['rismar'] = self.number(dataKPI['rismar'])
- dataKPI['OF'] = self.number(dataKPI['OF'])
- dataKPI['SCR'] = self.number(dataKPI['SCR'])
- return dataKPI
- def number(self, value):
- return format(value, ',.0f')
- def stressedInterestCurve(self, shift, scale):
- return self.ProxyClass.stressedInterestCurve(shift, scale)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement