SHARE
TWEET

Untitled

a guest Jan 22nd, 2020 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """
  2. Created on Tue Sep 17 11:17:54 2019
  3.  
  4. @author: Fmeessen
  5. """
  6. import tensorflow_core.keras as keras
  7. #import keras
  8. import numpy as np
  9. import pandas as pd
  10. import os
  11. from pprint import pprint
  12.  
  13. ragged = False
  14.  
  15. class ProxyModel:
  16.     '''Object for loading in the neural networks and for marking predictions.
  17.    
  18.     Args:
  19.         folder_path(str): Path to the folder where the models (json and hdf5
  20.            files) are located. By default, it assumes that it is in the
  21.            current working directory.
  22.                    
  23.     Attributes:
  24.         bl_dict(dict): Dictionary of the loaded neural networks. The dictionary
  25.             is structrued as follows:
  26.                 {
  27.                 'BE': {
  28.                         'FLV': model,
  29.                         'Klassik1': model,
  30.                         'Klassik2': model,
  31.                         },
  32.                 'rismar': {
  33.                         'FLV': model,
  34.                         'Klassik1': model,
  35.                         'Klassik2': model,
  36.                         }
  37.                 }
  38.         prediction_dict(dict): Dictionary of the predictions by the neural
  39.             network based on the given input array. The structure of the
  40.             dictionary is the same as of the bl_dict.
  41.     '''
  42.  
  43.     def __init__(self, folder_path = 'models/'):
  44.  
  45.         self.bl_dict = {
  46.             'BE': {
  47.                     'FLV': None,
  48.                     'Klassik1': None,
  49.                     'Klassik2': None,
  50.                     },
  51.             'rismar': {
  52.                     'FLV': None,
  53.                     'Klassik1': None,
  54.                     'Klassik2': None,
  55.                     }
  56.             }
  57.         self.folder_path = folder_path
  58.         self.prediction_dict = self.bl_dict.copy()
  59.        
  60.     def predict(self, bus_line, input_array):
  61.         '''Make Predictions for both KPIs and all business lines.
  62.        
  63.         Args:
  64.             input_array(np.ndarray): The x values based upon which the predictions
  65.                 are made.
  66.                
  67.         Returns:
  68.             prediction_dict(dict): Dictionary, sorted by KPI then by business
  69.                 line of the corresponding predictions.
  70.         '''
  71.         #print('Predicting...')
  72.         for kpi_name, kpi_businesslines in self.bl_dict.items():
  73.             self.bl_dict[kpi_name][bus_line] = model = self.load_model(bus_line, kpi_name)
  74.             self.prediction_dict[kpi_name][bus_line] = model.predict(input_array)
  75.             #for bl, model in kpi_businesslines.items():
  76.             #    self.prediction_dict[kpi_name][bl] = model.predict(input_array)
  77.         #print('Finished prediction.')
  78.         return self.prediction_dict
  79.  
  80.     def predict_all(self, bus_line, input_array):
  81.         '''Make Predictions for both KPIs and all business lines.
  82.        
  83.         Args:
  84.             input_array(np.ndarray): The x values based upon which the predictions
  85.                 are made.
  86.                
  87.         Returns:
  88.             prediction_dict_all(dict): Dictionary, sorted by KPI then by business
  89.                 line of the corresponding predictions.
  90.         '''
  91.         #print('Predicting all...')
  92.         for kpi_name, kpi_businesslines in self.bl_dict.items():
  93.             for bl, model in kpi_businesslines.items():
  94.                 self.prediction_dict_all[kpi_name][bl] = model.predict(input_array)
  95.         #print('Finished all predictions.')
  96.         return self.prediction_dict_all
  97.    
  98.     def load_model(self, business_line, kpi):
  99.         '''Load model specification and weights from disk.
  100.        
  101.         Args:
  102.             business_line(str): Corresponding Business Line (FLV, K1, K2).
  103.             kpi(str): Corresponding KPI (BE or rismar).
  104.            
  105.         Returns:
  106.            loaded_model(keras model): Corresponding keras model .
  107.         '''
  108.         file_name = self.folder_path + business_line + '_' + kpi
  109.         # loading model
  110.         json_file = open(file_name + '_model.json' )
  111.         loaded_model_json = json_file.read()
  112.         json_file.close()
  113.         loaded_model = keras.models.model_from_json(loaded_model_json)
  114.         # loading weights
  115.         loaded_model.load_weights(file_name + '_weights.hdf5')
  116.         #print('Loaded model from disk:', file_name)
  117.         return loaded_model
  118.        
  119.     def load_all_models(self):
  120.         '''Load all models into the business line dictionary.'''
  121.         for kpi_name, kpi_businesslines in self.bl_dict.items():
  122.             for bl in kpi_businesslines:
  123.                 self.bl_dict[kpi_name][bl] = self.load_model(bl, kpi_name)
  124.         return self
  125.  
  126.     def get_EQ(self):
  127.         return 650000000
  128.  
  129.     def get_RE(self):
  130.         return 1037109768
  131.  
  132.     def get_FI_rate_down(self):
  133.         return 4992928194    #calculated by using interests rate  
  134.  
  135.     def get_FI_rate_up(self):
  136.         return 4441480295    #calculated by using interests rate
  137.  
  138.     def get_OF_BE(self):
  139.         return 6000000000
  140.  
  141.     def get_OF(self, BEL, RISMAR, FI):
  142.         EQ = self.get_EQ()
  143.         RE = self.get_RE()
  144.         #pprint(":::FI")
  145.         #pprint(FI)
  146.         MW = float(EQ) + float(RE) + float(FI)
  147.         OF = float(MW) - float(BEL) - float(RISMAR)
  148.         #print("==============")
  149.         #print("====EQ:: " + str(EQ))
  150.         #print("====RE:: " + str(RE))
  151.         #print("====FI:: " + str(FI))
  152.         #print("====MW:: " + str(MW))
  153.         #print("====BEL:: " + str(BEL))
  154.         #print("====RISMAR:: " + str(RISMAR))
  155.         #print("====OF:: " + str(OF))
  156.         return OF
  157.  
  158.     def get_SCR(self, BEL, RISMAR):
  159.  
  160.         #cashflow = self.cashflow()
  161.         #FI_rate_down = self.get_FI(cashflow, interestCurve)
  162.         #FI_rate_up =
  163.         OF_rate_down = self.get_OF(BEL, RISMAR, self.get_FI_rate_down())
  164.         OF_rate_up = self.get_OF(BEL, RISMAR, self.get_FI_rate_up())
  165.         OF_BE = self.get_OF_BE()
  166.         SCR1 = OF_rate_down - OF_BE
  167.         SCR2 = OF_rate_up - OF_BE
  168.  
  169.         #print("==============")
  170.         #print("====OF_rate_down:: " + str(OF_rate_down))
  171.         #print("====OF_rate_up:: " + str(OF_rate_up))
  172.         #print("====OF_BE:: " + str(OF_BE))
  173.         #print("====SCR1:: " + str(SCR1))
  174.         #print("====SCR2:: " + str(SCR2))
  175.  
  176.         corr_mat = np.array([[0.5 ,0.5],[0.5, 0.5]])
  177.         SCR_mat = np.array([[SCR1, SCR2]])
  178.         SCR_mat_T = np.array([[SCR1], [SCR2]])
  179.         SCR_mat_temp = np.matmul(SCR_mat, corr_mat)
  180.         SCR = np.matmul(SCR_mat_temp, SCR_mat_T)
  181.  
  182.         return SCR[0][0] / 1000000000
  183.  
  184.     def interestCurve(self):
  185.         points = pd.read_csv("models/interest_curve.csv", encoding = "utf8", header=None)
  186.         return np.array(points)
  187.  
  188.     def cashflow(self):
  189.         points = pd.read_csv("models/cashflow.csv", encoding = "utf8", header=None)
  190.         return np.array(points)
  191.  
  192.     def stressedInterestCurve(self, shift, scale):
  193.         interestCurve = self.interestCurve()
  194.         points = []
  195.         i = 0
  196.         for x in np.nditer(interestCurve):
  197.             points.append([(float(x) + float(shift)) * float(scale)])
  198.             i = i + 1
  199.  
  200.         return np.array(points)
  201.  
  202.     def interestFactorList(self, stressedInterestCurve):
  203.  
  204.         iflist = []
  205.         prev = 1.0
  206.         i = 0
  207.         for ic in stressedInterestCurve:
  208.             inserted = prev / (1.0 + float(ic))
  209.             iflist.append(inserted)
  210.             prev = inserted
  211.             i = i + 1
  212.  
  213.         return iflist
  214.  
  215.     def get_FI(self, cashflow, interestFactors):
  216.         total = 0.0
  217.         i = 0
  218.         for ifx in interestFactors:
  219.             prod = interestFactors[i] * cashflow[i]
  220.             total = total + prod
  221.  
  222.         return total
  223.  
  224.  
  225. class Octopus:
  226.  
  227.     def __init__(self):
  228.         # Singleton
  229.         self.ProxyClass = ProxyModel()
  230.  
  231.     def data(self, busLine, shift=None, scale=None, alpha=None, sigma=None):
  232.         if shift is None :
  233.             shift = 0
  234.  
  235.         if scale is None :
  236.             scale = 1
  237.  
  238.         if alpha is None :
  239.             alpha = 0.1
  240.  
  241.         if sigma is None :
  242.             sigma = 0.0145
  243.  
  244.         print('BL: '+busLine+'; '+'shift: '+str(shift)+'; '+'scale: '+str(scale)+'; '+'alpha: '+str(alpha)+'; ' +'sigma: '+str(sigma)+';')
  245.  
  246.         x = np.array([[shift, scale, 0, 0, alpha, sigma, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]])
  247.         predictions = self.ProxyClass.predict(busLine, x)
  248.  
  249.         dataKPI = {}
  250.         for kpi, values in predictions.items():
  251.             dataKPI[kpi] = values[busLine][0][0].item()
  252.  
  253.         BEL = dataKPI['BE']
  254.         RISMAR = dataKPI['rismar']
  255.  
  256.         stressedInterestCurve = self.ProxyClass.stressedInterestCurve(shift, scale)
  257.         interestFactors = self.ProxyClass.interestFactorList(stressedInterestCurve)
  258.         cashflow = self.ProxyClass.cashflow()
  259.         FI = self.ProxyClass.get_FI(cashflow, interestFactors)
  260.  
  261.         OF = self.ProxyClass.get_OF(BEL, RISMAR, FI)
  262.         dataKPI['OF'] = OF
  263.  
  264.         SCR = self.ProxyClass.get_SCR(BEL, RISMAR);
  265.         dataKPI['SCR'] = SCR
  266.  
  267.         # String formatted
  268.         dataKPI['BE'] = self.number(dataKPI['BE'])
  269.         dataKPI['rismar'] = self.number(dataKPI['rismar'])
  270.         dataKPI['OF'] = self.number(dataKPI['OF'])
  271.         dataKPI['SCR'] = self.number(dataKPI['SCR'])
  272.  
  273.         return dataKPI
  274.  
  275.     def number(self, value):
  276.         return format(value, ',.0f')
  277.  
  278.     def stressedInterestCurve(self, shift, scale):
  279.         return self.ProxyClass.stressedInterestCurve(shift, scale)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top