• Home
  • Readings
  • Github
  • MIES
  • TmVal
  • About
Gene Dan's Blog

Category Archives: Actuarial

No. 147: The Chain Ladder Method with FASLR

27 March, 2022 4:25 PM / 1 Comment / Gene Dan

Today marks an exciting milestone – FASLR (Free Actuarial System for Loss Reserving) – has now implemented its first reserving technique, the chain ladder method. This makes it a good time to update the version number for the project, so I’ve bumped it from its inception v0.0.0 to v0.0.1. Feel free to check out the source code on the CAS GitHub.

New features added:

  • Ultimate Loss Column calculated via the chain ladder technique
  • Rows for selected LDFs and CDFs
  • The ability to select LDFs by double-clicking averages
  • Dialog box for creating and storing custom link ratio average types
  • Link ratio heatmap

These features have been added to the development factor view of FASLR. The images below show a comparison to how it looked last month (first image) vs. how it looks now, with the new features highlighted in red boxes (second image):

The FASLR development view, last month.

The FASLR development view, newest version.

Project Status

When examining the views of the repo, I’ve seen a lot of people taking a look at the releases section, the setup.py file, and the documentation. This leads me to believe that some people either think this is an installable program or are checking to see if it is. Right now, the project exists as a collection of Python source code files, so it’s not there yet. I do have plans to eventually release installable binaries where you can just double click a file and have it installed on your operating system. But first, I would have to learn how to do that and I have yet to decide on which tool I want to use to make that happen (GNU Make, Bazel, fbs, pyinstaller, etc.). This will be a new skill for me to acquire so it will take some time.

If you do want to run FASLR, you can execute the file main.py in the shell. This will give you access to the main GUI window and project pane. Currently, I’m focused on setting up views for the various reserving methodologies, once I’ve either exhausted those available in the chainladder package, or reached a point where it would be nice to integrate them into the main window, I will begin to focus more on the reserving project methodology – i.e., making it possible to start from data importation and end with a reserving estimate.

Versioning Methodology

The versioning system consists of a three-part format: v#.#.#. The rightmost digit represents unstable versions. Excluding v0.0.0, if your installation happens to have a rightmost digit other than 0, you can assume that you are using the software for the purpose of testing out the latest features and not relying on stability. The middle digit represents stable releases, meaning that the features have been tested to the best of the ability of the developer(s) and provide a reasonable level of reliability. So something like v0.1.0 would represent the first stable version and v0.1.1 would represent the most recent unstable version released after v0.1.0. The next stable version after v0.1.0 will be v0.2.0.

The leftmost digit represents major cultural milestones in the project. Right now it seems to be in vogue to reserve version 1.whatever for a special occasion, to mark the point where the software has become the de-facto open-source standard for performing work in the field. I will adopt this convention for this project, but while I have no plans to ever reach this point, as FASLR is mostly a learning exercise for me, it would be a nice point to reach if it ever gains traction.

Ultimate Losses

Since there are numerous sources on actuarial reserving methods which can do a much better job of explaining how they work than I can, I won’t spend much detail here on them and you can always refer back to CAS Exam 5 papers if you are not familiar with them. These next few sections will start with a blank factor view, and I will gradually demonstrate how link ratio averages can be used, in combination with the chain ladder technique to project ultimate loss.

One purpose of actuarial reserving is to estimate the liabilities per unit of time (such as accident year) and we call this estimate the ultimate loss. Therefore, one of my goals for this month was to add a column for ultimate loss. Below shows the (mostly) blank factor view with the link ratio triangle and ultimate loss column to the right. The LDFs have not been selected, and the chainladder package defaults non-selection to 1.000:

You can confirm that the starting LDFs are 1.000 by looking at the source triangle – the ultimate loss values are the same as the latest diagonal:

LDF Selection

Below the triangle, you will find a section that has various link ratio averages that you can select by double-clicking on them. The image in the previous section only had one option, the all-year volume-weighted average, but you can add more by selecting the “Available Averages” button in the upper-right hand corner. Doing so will open up a dialog box with averages that you can add to the factor view:

The starting averages are All, 5-, and 3- year volume-weighted averages. You can add these by clicking the checkboxes in the table. Alternatively, you can add a custom type if you want to use a different kind of average like straight or regression. You can do this by clicking the “Add Average” button and then selecting the options for the new average. Right now, only these three are supported by chainladder, but I have proposed that we add others like medial and geometric to the list:

In this example I have added a 2-year regression and selected all 4 average types in the table. This expands the number of rows in the LDF section of the factor view:

Next, you can select the LDFs by double-clicking on the LDF section. Double-clicking an entire row will select that whole row, and the CDFs are automatically calculated. The image below shows that I have selected the 2-year regression, and the ultimate loss values are automatically updated:

Alternatively, you can enter in your own custom values by typing or copy-pasting into the cells directly. And you can delete the selections by pressing the delete key over the cells or by double-clicking the row header of the selected LDF row. You can also remove LDF average types by clicking on the “available averages” button and unchecking the ones you want to remove.

Heatmap

This last feature is something that comes from the chainladder package. It was quite challenging to implement even though on the surface, all you have to do is tick the checkbox. This helps you identify outlier link ratios that you may want to exclude in your analysis:

There are some performance enhancements to be made on this feature, I’ll write up another post once that’s done. Below, you’ll see a gif of all of what I described above in action:

Posted in: Actuarial

No. 146: Development Factors with FASLR

21 February, 2022 5:42 PM / Leave a Comment / Gene Dan

A few things have happened since this last time I’ve posted about a technical subject – I have gotten into contact with Brian Fannin over at the CAS and now have two projects hosted on their GitHub page – PCDM, which I wrote about a couple years ago, and FASLR, a new project I started last year, which I’ll be talking about today.

FASLR (pronounced fæzlɹ̩), is a GUI wrapper built using the PyQt framework to accommodate open-source actuarial reserving engines, such as the chainladder packages written in Python and R.

OK. The buzzword-free version of that sentence is that FASLR is open-source software that is intended to help actuaries do reserving with buttons, windows, and mouse clicks. There are a few open-source packages that let actuaries do reserving by writing programs, and some commercial solutions that let actuaries do reserving with buttons and mouse clicks. But at least to my knowledge, there had yet to be an open-source interface-based software for doing reserving, so I decided to make one. What motivated me to start was I have been wanting to build graphical interfaces for my other projects, such as MIES, but hadn’t made a decision whether to use web-based technologies like Django (letting people use the software in the browser) or something desktop-based like PyQt. I have decided on using PyQt since that would require me to learn fewer languages or deal with browser stuff like JavaScript.

FASLR stands for Free Actuarial System for Loss Reserving, named after Fazlur Rahman Khan, an architect who designed a number of famous buildings in Chicago.

Other motivations include:

  • Giving me an excuse to learn PyQt
  • Increasing transparency on how actuarial computations are done
  • Giving students a window into how actuarial work is done in practice as opposed to exams
  • Increasing accessibility of actuarial software to the general public
  • Making a GUI compatible with existing open-source technologies
  • Imposing my worldview on how actuarial models should be built and implemented in the workplace
  • Bragging rights on the CAS GitHub page
FASLR basic interface

FASLR basic interface

The Chainladder Packages

Chainladder is a fancy word for one of the techniques that actuaries use to guess how much money insurance companies need to pay for claims. It’s also the name of a pair of open-source actuarial packages – one written in R, and another in Python. The R library was written many years ago by Markus Gesmann. It seems to have been written starting around 2007, which is the year of the earliest release I have been able to find on CRAN. The Python package is a port of the R library, written by John S Bogaardt starting around 2017 or so based on the commit history. These packages, by being open-source, have not only helped to improve transparency to how actuarial computations are done but have also improved accessibility to the field by being available to people who do not have the means to pay for commercial software, such as students looking to get into the field. However, since they are lightweight libraries, actuaries must write programs to do reserving – which, depending on personal preference, may or may not be the most productive way to get reserving done.

I think that last sentence is a fair criticism of using a programming language to get actuarial work done – especially when we consider the selection of development factors, the topic of today’s post. This isn’t to disparage these packages – both of which are major contributions to modernizing actuarial science. And thanks to John, pretty much 75% of the work is already done to get FASLR working – all I have to do is design the interface (unlike MIES, which will take forever to be ready). It is their work that makes something like FASLR possible. On the subject of development factors – this is a family of various averages of age-to-age factors used to develop losses to ultimate. When you use a package, you might need to write a line of code picking out which link ratios you want to exclude and then visualize the resulting averages by executing another line. If you didn’t like your selection, you may have to edit that line of code or write a new one and recompute – over and over again. That may be tedious, and hard to keep track of if you have several attempts. However, if you could simply double-click on a triangle of link ratios to exclude them and see the factors update in near-real time, you can get your work done a lot faster.

Below is an example (taken from the Chainladder documentation) of how we can use Chainladder to load a sample triangle and see the link ratios:

Python
1
2
3
4
5
import chainladder as cl
 
genins = cl.load_sample("genins")
 
print(genins.link_ratio)

1
2
3
4
5
6
7
8
9
10
         12-24     24-36     36-48     48-60     60-72     72-84     84-96    96-108   108-120
2001  3.143200  1.542806  1.278299  1.237719  1.209207  1.044079  1.040374  1.063009  1.017725
2002  3.510582  1.755493  1.545286  1.132926  1.084493  1.128106  1.057268  1.086496       NaN
2003  4.448450  1.716718  1.458257  1.232079  1.036860  1.120010  1.060577       NaN       NaN
2004  4.568002  1.547052  1.711784  1.072518  1.087360  1.047076       NaN       NaN       NaN
2005  2.564198  1.872956  1.361545  1.174217  1.138315       NaN       NaN       NaN       NaN
2006  3.365588  1.635679  1.369162  1.236443       NaN       NaN       NaN       NaN       NaN
2007  2.922798  1.878099  1.439393       NaN       NaN       NaN       NaN       NaN       NaN
2008  3.953288  2.015651       NaN       NaN       NaN       NaN       NaN       NaN       NaN
2009  3.619179       NaN       NaN       NaN       NaN       NaN       NaN       NaN       NaN

And to view the volume-weighted LDFs for all years, we execute:

Python
1
2
3
vol = cl.Development(average="volume").fit(genins).ldf_
 
print(vol)

1
2
          12-24     24-36     36-48     48-60     60-72     72-84     84-96    96-108   108-120
(All)  3.490607  1.747333  1.457413  1.173852  1.103824  1.086269  1.053874  1.076555  1.017725

Now, to exclude certain periods, we can pass a list of excluded periods to the .Development() method:

1
2
3
ldfs_w_dropped = cl.Development(drop=[("2004", 12), ("2008", 24)]).fit(genins).ldf_
 
print(ldfs_w_dropped)

1
2
          12-24     24-36     36-48     48-60     60-72     72-84     84-96    96-108   108-120
(All)  3.379677  1.704149  1.457413  1.173852  1.103824  1.086269  1.053874  1.076555  1.017725

We can see that this has altered the 12-24 and 24-36 LDFs.

However, actuaries typically want to experiment with several exclusions with trial and error, so a GUI would be helpful here.

FASLR Example

I will now give a demo of how FASLR uses the Chainladder methods above to speed up LDF selection via a GUI. Below is an example of a window I designed to display a triangle of link ratios with the volume-weighted LDFs right below the triangle:

What I’d like to do is double-click a factor to exclude it. Ideally this will get the LDFs at the bottom to update immediately so I can see the results – without having to do all the typing we did with the Chainladder example. I have written FASLR to update the formatting of the link ratio to be struck-out with a pink background to indicate exclusion. Below are the first three accident years of the 12-24 column excluded.

You can see that the formatting has now updated with the first ldf changed from 1.733 to 1.717.

The GIF below demonstrates how fast we can preview the LDF changes using this feature:

The demo can be run from the FASLR source code, available on the CAS GitHub page.

This is just one feature preview out of what I hope will be many, so keep an eye open for future updates.

Technical Appendix

This was all much easier said than done. Getting that factor elimination feature to work was tricky, especially with me being new to PyQt and all. This feature makes use of a concept called Model-View-Controller which you can read more about here. Below is some example code from the FASLR module that does most of the work that we see in today’s post. It depends on all the other modules in the repository, so I don’t expect a full understanding from the code listing alone. To find out more, refer to the entire source code:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import chainladder as cl
import csv
import io
import numpy as np
import pandas as pd
 
from chainladder import Triangle
 
from pandas import DataFrame
 
from PyQt5.QtCore import (
    QAbstractTableModel,
    QEvent,
    Qt,
    QSize,
    QVariant
)
 
from PyQt5.QtGui import (
    QColor,
    QFont,
    QKeySequence
)
 
from PyQt5.QtWidgets import (
    QAbstractButton,
    QAction,
    QApplication,
    qApp,
    QLabel,
    QMenu,
    QStyle,
    QStylePainter,
    QStyleOptionHeader,
    QTableView,
    QVBoxLayout
)
 
from style.triangle import (
    BLANK_TEXT,
    LOWER_DIAG_COLOR,
    RATIO_STYLE,
    VALUE_STYLE
)
 
 
class FactorModel(QAbstractTableModel):
 
    def __init__(
            self,
            triangle: Triangle,
            value_type: str = "ratio"
    ):
        super(
            FactorModel,
            self
        ).__init__()
 
        self.triangle = triangle
        self._data = triangle.link_ratio.to_frame()
        self.link_frame = triangle.link_ratio.to_frame()
        self.n_rows = self.rowCount()
 
        self.development_factors = cl.Development(average="volume").fit(self.triangle)
 
        self._data = get_display_data(
            ratios=self.link_frame,
            factors=self.development_factors
        )
 
        self.value_type = value_type
        self.excl_frame = self._data.copy()
        self.excl_frame.loc[:] = False
        self.blank_row_num = self.n_rows + 1
 
    def data(
            self,
            index,
            role=None
    ):
 
        if role == Qt.DisplayRole:
 
            value = self._data.iloc[index.row(), index.column()]
 
            # Display blank when there are nans in the lower-right hand of the triangle.
            if str(value) == "nan":
 
                display_value = BLANK_TEXT
            else:
                # "value" means stuff like losses and premiums, should have 2 decimal places.
                if self.value_type == "value":
 
                    display_value = VALUE_STYLE.format(value)
 
                # for "ratio", want to display 3 decimal places.
                else:
 
                    display_value = RATIO_STYLE.format(value)
 
                display_value = str(display_value)
 
            self.setData(
                self.index(
                    index.row(),
                    index.column()
                ),
                QVariant(Qt.AlignRight),
                Qt.TextAlignmentRole
            )
 
            return display_value
 
        if role == Qt.TextAlignmentRole:
            return Qt.AlignRight
 
        if role == Qt.BackgroundRole:
            if (index.column() >= self.n_rows - index.row()) and \
                    (index.row() < self.blank_row_num):
                return LOWER_DIAG_COLOR
            elif index.row() < self.blank_row_num:
                exclude = self.excl_frame.iloc[[index.row()], [index.column()]].squeeze()
 
                if exclude:
                    return QColor(255, 230, 230)
                else:
                    return QColor(255, 255, 255)
        if (role == Qt.FontRole) and (self.value_type == "ratio") and (index.row() < self.blank_row_num):
            font = QFont()
            exclude = self.excl_frame.iloc[[index.row()], [index.column()]].squeeze()
            if exclude:
                font.setStrikeOut(True)
            else:
                font.setStrikeOut(False)
            return font
 
    def rowCount(
            self,
            parent=None,
            *args,
            **kwargs
    ):
 
        return self._data.shape[0]
 
    def columnCount(
            self,
            parent=None,
            *args,
            **kwargs
    ):
 
        return self._data.shape[1]
 
    def headerData(
            self,
            p_int,
            qt_orientation,
            role=None
    ):
 
        # section is the index of the column/row.
        if role == Qt.DisplayRole:
            if qt_orientation == Qt.Horizontal:
                return str(self._data.columns[p_int])
 
            if qt_orientation == Qt.Vertical:
                return str(self._data.index[p_int])
 
    def toggle_exclude(self, index):
        exclude = self.excl_frame.iloc[[index.row()], [index.column()]].squeeze()
 
        if exclude:
            self.excl_frame.iloc[[index.row()], [index.column()]] = False
        else:
            self.excl_frame.iloc[[index.row()], [index.column()]] = True
 
    def recalculate_factors(self, index):
 
        drop_list = []
        for i in range(self.link_frame.shape[0]):
            for j in range(self.link_frame.shape[1]):
 
                exclude = self.excl_frame.iloc[[i], [j]].squeeze()
                print(exclude)
 
                if exclude:
 
                    row_drop = str(self.link_frame.iloc[i].name)
                    col_drop = int(str(self.link_frame.columns[j]).split('-')[0])
 
                    drop_list.append((row_drop, col_drop))
 
                else:
 
                    pass
 
        development = cl.Development(drop=drop_list, average="volume")
 
        self.development_factors = development.fit(self.triangle)
        self._data = get_display_data(
            ratios=self.link_frame,
            factors=self.development_factors
        )
 
        # print(development.fit_transform(self.triangle).link_ratio)
 
        print(self._data)
        self.dataChanged.emit(index, index)
        self.layoutChanged.emit()
 
 
class FactorView(QTableView):
    def __init__(self):
        super().__init__()
 
        self.copy_action = QAction("&Copy", self)
        self.copy_action.setShortcut(QKeySequence("Ctrl+c"))
        self.copy_action.setStatusTip("Copy selection to clipboard.")
        # noinspection PyUnresolvedReferences
        self.copy_action.triggered.connect(self.copy_selection)
 
        self.installEventFilter(self)
 
        btn = self.findChild(QAbstractButton)
        btn.installEventFilter(self)
        btn_label = QLabel("AY")
        btn_label.setAlignment(Qt.AlignCenter)
        btn_layout = QVBoxLayout()
        btn_layout.setContentsMargins(0, 0, 0, 0)
        btn_layout.addWidget(btn_label)
        btn.setLayout(btn_layout)
        opt = QStyleOptionHeader()
 
        # Set the styling for the table corner so that it matches the rest of the headers.
        self.setStyleSheet(
            """
            QTableCornerButton::section{
                border-width: 1px;
                border-style: solid;
                border-color:none darkgrey darkgrey none;
            }
            """
        )
 
        s = QSize(btn.style().sizeFromContents(
            QStyle.CT_HeaderSection, opt, QSize(), btn).
                  expandedTo(QApplication.globalStrut()))
 
        if s.isValid():
            self.verticalHeader().setMinimumWidth(s.width())
 
        self.verticalHeader().setDefaultAlignment(Qt.AlignCenter)
 
        self.doubleClicked.connect(self.exclude_ratio)
 
    def exclude_ratio(self):
        selection = self.selectedIndexes()
 
        for index in selection:
            index.model().toggle_exclude(index=index)
            index.model().recalculate_factors(index=index)
 
    def eventFilter(self, obj, event):
        if event.type() != QEvent.Paint or not isinstance(
                obj, QAbstractButton):
            return False
 
        # Paint by hand (borrowed from QTableCornerButton)
        opt = QStyleOptionHeader()
        opt.initFrom(obj)
        style_state = QStyle.State_None
        if obj.isEnabled():
            style_state |= QStyle.State_Enabled
        if obj.isActiveWindow():
            style_state |= QStyle.State_Active
        if obj.isDown():
            style_state |= QStyle.State_Sunken
        opt.state = style_state
        opt.rect = obj.rect()
        # This line is the only difference to QTableCornerButton
        opt.text = obj.text()
        opt.position = QStyleOptionHeader.OnlyOneSection
        painter = QStylePainter(obj)
        painter.drawControl(QStyle.CE_Header, opt)
 
        return True
 
    def contextMenuEvent(self, event):
        """
        When right-clicking a cell, activate context menu.
 
        :param: event
        :return:
        """
        menu = QMenu()
        menu.addAction(self.copy_action)
        menu.exec(event.globalPos())
 
    def copy_selection(self):
        """Method to copy selected values to clipboard, so they can be pasted elsewhere, like Excel."""
        selection = self.selectedIndexes()
        if selection:
            rows = sorted(index.row() for index in selection)
            columns = sorted(index.column() for index in selection)
            rowcount = rows[-1] - rows[0] + 1
            colcount = columns[-1] - columns[0] + 1
            table = [[''] * colcount for _ in range(rowcount)]
            for index in selection:
                row = index.row() - rows[0]
                column = index.column() - columns[0]
                table[row][column] = index.data()
            stream = io.StringIO()
            csv.writer(stream, delimiter='\t').writerows(table)
            qApp.clipboard().setText(stream.getvalue())
        return
 
 
def get_display_data(ratios, factors: DataFrame):
 
    data = {"": [np.nan] * len(ratios.columns)}
 
    blank_row = pd.DataFrame.from_dict(
        data,
        orient="index",
        columns=ratios.columns
    )
 
    factor_frame = factors.ldf_.to_frame()
    factor_frame = factor_frame.rename(index={'(All)': 'Volume-Weighted LDF'})
    return pd.concat([ratios, blank_row, factor_frame])

Posted in: Actuarial

No. 144: MIES – Intertemporal Choice

26 July, 2020 10:11 PM / Leave a Comment / Gene Dan

This entry is part of a series dedicated to MIES – a miniature insurance economic simulator. The source code for the project is available on GitHub.

Current Status

This week, I’ve been continuing my work on incorporating risk into the consumer behavior component of MIES. The next step in this process involves the concept of intertemporal choice, an interpretation of the budget constraint problem whereby a consumer can shift consumption from one time period to another by means of savings and loans. The content of this post follows chapter 10 of Varian.

For example, a person can consume more in a future period by saving money. A person can also increase their consumption today by taking out a loan, which comes at a cost of future consumption because they have to pay interest. When making decisions between current and future consumption, we also have to think about time value of money. When I was reading through Varian, I was happy to see that many of the concepts I learned from the financial mathematics actuarial exam were also discussed by Varian – such as bonds, annuities, and perpetuities – albeit in much less detail.

This inspired me to create a new repo to handle time value of money computations, which is not yet ready for its own series of posts, but for which you can see the initial work here. I had intended to make this repo further out in the future, but I got excited and started early.

Also relevant, is the concept of actuarial communication. Now that I’m blogging more about actuarial work, I will need to be able to write the notation here. There are some \LaTeX packages that can render actuarial notation, such as actuarialsymbol. Actuaries are still in the stone age when it comes to sharing technical work over the Internet, not out of ignorance, since many actuaries are familiar with \LaTeX, but out of corporate inertia in getting the right tools at work (which I can suppose be due to failure to persuade the right people) and lack of momentum and willingness as many people simply just try to make do with using ASCII characters to express mathematical notation. I think this is a major impediment to adding rigor to practical actuarial work, which many young analysts complain about when they first start working, as they notice that spreadsheet models tend to be a lot more dull than what they see on the exams.

I was a bit anxious in trying to get the actuarialsymbol package working since, although I knew how to get it working on my desktop, I wasn’t sure if it would work with WordPress or Anki, a study tool that I use. Fortunately, it does work! For example, the famous annuity symbol can be rendered with the command \ax{x:\angln}:

Rendered by QuickLaTeX.com

That was easy. There’s no reason why intraoffice email can’t support this, so I hope that it encourages you to pick it up as well.

The Statics Module

Up until now, testing new features has been cumbersome since many of the previous demos I have written about required existing simulation data. That is, in order to test things like intertemporal choice, I would first need to set up a simulation, run it, and then use the results as inputs into the new functions, classes, or methods.

That really shouldn’t be necessary, especially since many of the concepts I have been making modules for apply to economics in general, and not just to insurance. To solve this problem, I created the statics module, which is named after the process of comparative statics, which examines how behavior changes when an exogenous variable in the model changes (aka all the charts I’ve been making about MIES).

The statics module currently has one class, Consumption, which can return attributes such as the optimal consumption of a person given a budget and utility function:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# used for comparative statics
import plotly.graph_objects as go
 
from plotly.offline import plot
 
from econtools.budget import Budget
from econtools.utility import CobbDouglas
 
 
class Consumption:
    def __init__(
            self,
            budget: Budget,
            utility: CobbDouglas
    ):
        self.budget = budget
        self.income = self.budget.income
        self.utility = utility
        self.optimal_bundle = self.get_consumption()
        self.fig = self.get_consumption_figure()
 
    def get_consumption(self):
        optimal_bundle = self.utility.optimal_bundle(
            p1=self.budget.good_x.adjusted_price,
            p2=self.budget.good_y.adjusted_price,
            m=self.budget.income
        )
 
        return optimal_bundle
 
    def get_consumption_figure(self):
        fig = go.Figure()
        fig.add_trace(self.budget.get_line())
        fig.add_trace(self.utility.trace(
            k=self.optimal_bundle[2],
            m=self.income / self.budget.good_x.adjusted_price * 1.5
        ))
 
        fig.add_trace(self.utility.trace(
            k=self.optimal_bundle[2] * 1.5,
            m=self.income / self.budget.good_x.adjusted_price * 1.5
        ))
 
        fig.add_trace(self.utility.trace(
            k=self.optimal_bundle[2] * .5,
            m=self.income / self.budget.good_x.adjusted_price * 1.5
        ))
 
        fig['layout'].update({
            'title': 'Consumption',
            'title_x': 0.5,
            'xaxis': {
                'title': 'Amount of ' + self.budget.good_x.name,
                'range': [0, self.income / self.budget.good_x.adjusted_price * 1.5]
            },
            'yaxis': {
                'title': 'Amount of ' + self.budget.good_y.name,
                'range': [0, self.income * 1.5]
            }
        })
 
        return fig
 
    def show_consumption(self):
        plot(self.fig)

A lot of the code here is the same as that which can be found in the Person class. However, instead of needing to instantiate a person to do comparative statics, I can just use the Consumption class directly from the statics module. This should make creating and testing examples much easier.

Since much of the code in statics is the same as in the Person class, that gives me a hint that I can make things more maintainable by refactoring the code. I would think the right thing to do is to have the Person class use the Consumption class in the statics module, rather than the other way around.

The Intertemporal Class

The intertemporal budget constraint is:

    \[c_1 + c_2/(1+r) = m_1 + m_2/(1+r)\]

Note that this has the same form as the endowment budget constraint:

    \[p_1 x_1 + p_2 x_2 = p_1 m_1 + p_2 m_2 \]

With the difference being that the two endowment goods are now replaced by consumption in times 1 and 2, represented by the cs and the prices, the ps are now replaced by discounted unit prices. The subscript 1 represents the current time and the subscript 2 represents the future time, with the price of future consumption being discounted to present value via the interest rate, r.

The consumer can shift consumption between periods 1 and 2 via saving and lending, subject to the constraint that the amount saved during the first period cannot exceed their first period income, and the amount borrowed during the first period cannot exceed the present value of the income of the second period.

Since the intertemporal budget constraint is a form of the endowment constraint, we can modify the Endowment class in MIES to accommodate this type of consumption. I have created a subclass called Intertemporal that inherits from the Endowment class:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Intertemporal(Endowment):
    def __init__(
            self,
            good_x: Good,
            good_y: Good,
            good_x_quantity: float,
            good_y_quantity: float,
            interest_rate: float = 0,
            inflation_rate: float = 0
            ):
        Endowment.__init__(
            self,
            good_x,
            good_y,
            good_x_quantity,
            good_y_quantity,
        )
        self.interest_rate = interest_rate
        self.inflation_rate = inflation_rate
        self.good_y.interest_rate = self.interest_rate
        self.good_y.inflation_rate = self.inflation_rate

The main difference here is that the Intertemporal class can accept an interest rate and an inflation rate to adjust the present value of future consumption.

Example

As an example, suppose we have a person who makes 5 dollars in each of time periods 1 and 2. The market interest rate is 10% and their utility function takes the Cobb Douglas form of:

    \[u(x_1, x_2) = x_1^{.5} x_2^{.5}\]

which means they will spend half of the present value of the endowment as consumption in period 1:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from econtools.budget import Budget, Intertemporal, Good
from econtools.statics import Consumption
from econtools.utility import CobbDouglas
 
# test if intercepts plot appropriately with an interest rate of 10%
m1 = Good(price=1, name='Time 1 Consumption')
 
m2 = Good(price=1, name='Time 2 Consumption')
 
endowment = Intertemporal(
    good_x=m1,
    good_y=m2,
    good_x_quantity=5,
    good_y_quantity=5,
    interest_rate=.10
)
 
budget = Budget.from_endowment(endowment, name='budget')
 
utility = CobbDouglas(.5, 0.5)
 
consumption = Consumption(budget=budget, utility=utility)
 
consumption.show_consumption()

The main thing that sticks out here is that the slope of the budget constraint has changed to reflect the adjustment of income to present value. The x-axis intercept is slightly less than 10 because the present value of income is slightly less than 10, and the y-axis intercept is slightly more than 10 because if a person saved all of their time 1 income, they would receive interest of 5 * .1 = .5, making maximum consumption in period 2 10.5.

Since the person allocates half of the present value of the endowment to time 1 consumption, this means they will spend (5 + 5/1.1) * .5 = 4.77 in period one, saving 5 – 4.77 = .23, which then grows to .23 * (1 + .1) = .25 in period 2, which allows for a time 2 consumption of 5 + .25 = 5.25. This is verified by calling the optimal_bundle() method of the Consumption class:

Python
1
2
consumption.optimal_bundle
Out[7]: (4.7727272727272725, 5.25, 5.005678593539359)

Further Improvements

The Varian chapter on intertemporal choice briefly explores present value calculations for various payment streams, such as bonds and perpetuities. I first made a small attempt at creating a tvm module, but quickly realized that the subject of time value of money is much more complex than what is introduced in Varian, since I know that other texts go further in depth, and hence it may be necessary to split a new repo off from MIES so that it can be distributed separately. This repo is called TmVal, the early stages of which I have uploaded here.

Neither of these are ready for demonstration, but you can click on the links if you are interested in seeing what I have done. The next chapter of Varian covers asset markets, which at first glance seems to just be some examples of economic models, so I’m not sure if it has any features I would like to add to MIES. There is still more work to be done on refactoring the code, so I may do that, or move further into risk aversion, or do some more work on TmVal.

Posted in: Actuarial, MIES / Tagged: economics, insurance, intertemporal choice, MIES

No. 143: MIES – Endowments

19 July, 2020 11:57 PM / Leave a Comment / Gene Dan

This entry is part of a series dedicated to MIES – a miniature insurance economic simulator. The source code for the project is available on GitHub.

Current Status

Last week, I took a break from MIES to focus on PCDM, a relational database specification for the P&C insurance industry. This week, I’m back to making progress on the consumer behavior portion of MIES, by shifting the focus from personal income to the personal endowment as the main financial constraint underlying purchasing decisions.

In short, an endowment is the consumer’s assets. When making consumption choices, people can use their income to purchase goods and services, but they can also draw from assets that they have accumulated over time, such as from savings and checking accounts, and by selling goods that they own. Furthermore, by taking the endowment into consideration, we will now be able to model situation when a person might not have a regular income, but can still make purchases using their assets (such as unemployed or retired persons who are not working).

In the context of insurance, the endowment is important because people purchase insurance to indemnify themselves against events that might damage or reduce the value of their assets. In the absence of the endowment, we would ignore an important determinant of insurance purchasing behavior. Incorporating wealth into MIES will take some time, and the textbook material I need to work on spans five chapters of Varian. Therefore, I estimate that this process will take me at least a month to do:

  1. Endowment
  2. Intertemporal Choice
  3. Asset Markets
  4. Uncertainty
  5. Risky Assets

These concepts will involve making some substantial changes to the utility functions as well. For now I’ll start with the endowment, which required me to modify the Budget, Slutsky, and Hicks classes of MIES.

The Endowment Class

An endowment is a bundle of goods or services that has a value based on the sum product of their prices and quantities:

    \[p_1 \omega_1 + p_2 \omega_2 = m \]

Where m represents income, each omega represents the quantity of each good, and each p represents the price. Rather than treat income as a flow quantity from an external source, in this interpretation of consumer choice theory we, we treat income as a stock quantity that includes the assets of of the consumer – that is, what the consumer has to spend at a certain point of time depends on the valuation of their assets.

This definition of income loosens the assumption of fixed income that I had made until now. This is because changes in asset values can now impact a person’s income. For example, if a person has a car and a house, their depreciation or appreciation changes the amount the person can sell them for on the market.

The good news is that MIES already has much of the machinery already coded up to allow us to work with endowments, so the new class definition is quite simple:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Endowment:
    def __init__(
            self,
            good_x: Good,
            good_y: Good,
            good_x_quantity: float,
            good_y_quantity: float,
            ):
        self.good_x = good_x
        self.good_y = good_y
        self.good_x_quantity = good_x_quantity
        self.good_y_quantity = good_y_quantity
 
    @property
    def income(self):
        income = self.good_x.price * self.good_x_quantity + self.good_y.price * self.good_y_quantity
        return income

An endowment takes two goods, and their quantities. Upon initialization, Python will automatically calculate the Endowment’s value by multiplying the prices of the goods by the quantities supplied. I wrote this function as a property decorator, which was introduced to fix a bug I discovered when working with the Budget class. Earlier, changing the price of a good failed to change the budget constraint of a consumer, but the property decorator will now dynamically calculate certain attributes that depend on the price, such as income in the case of an endowment.

To illustrate, we can define two goods, each with a price of 1. We then initialize an endowment with a quantity of 5 for each of these goods:

1
2
3
4
5
6
7
from econtools.budget import Endowment, Good
 
good_1 = Good(price=1, name='good_1')
 
good_2 = Good(price=1, name='good_2')
 
endowment = Endowment(good_x=good_1, good_y=good_2, good_x_quantity=5, good_y_quantity=5)

Now we can check that the income was properly calculated by calling endowment.income. Since each good has a price of 1, and there are 5 of each good, the income should be 5 x 1 + 5 x 1 = 10:

Python
1
2
endowment.income
Out[4]: 10

Now that we have the Endowment class defined, we need to modify the other classes that used goods, such as the Budget class. Previously, the Budget class accepted two goods, an income amount, and a name to refer to the budget. Now I would like the Budget class to an accept an endowment as an alternative to specifying each good individually. The tricky part here is that in the former case, the class needs to be able to keep income fixed when the prices of goods change, but in the latter case, the income needs to change dynamically based on the prices of the goods.

To handle this, I created an alternative constructor called from_endowment() that lets you pass an endowment to the Budget class to initialize a budget object. I also created another constructor called from_bundle() that lets you define a Budget the old way more explicitly, to make it more obvious to anyone reading the code whether the budget was initialized with an endowment or individual goods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Budget:
    def __init__(
            self,
            good_x,
            good_y,
            income,
            name=None,
            endowment=None
    ):
        self.good_x = good_x
        self.good_y = good_y
        self.income = income
        self.x_lim = self.income / (min(self.good_x.adjusted_price, self.good_x.price)) * 1.2
        self.y_lim = self.income / (min(self.good_y.adjusted_price, self.good_y.price)) * 1.2
        self.name = name
        self.endowment = endowment
 
        if endowment is not None:
            self.__check_endowment_consistency()
 
    @classmethod
    def from_bundle(
            cls,
            good_x,
            good_y,
            income,
            name=None
    ):
        return cls(
            good_x,
            good_y,
            income,
            name
        )
 
    @classmethod
    def from_endowment(
            cls,
            endowment: Endowment,
            name=None
    ):
        good_x = endowment.good_x
        good_y = endowment.good_y
        income = endowment.income
 
        return cls(
            good_x,
            good_y,
            income,
            name,
            endowment
        )
 
    def __check_endowment_consistency(self):
        # raise exception if endowment is not consistent with its components
        if self.endowment.good_x != self.good_x:
            raise Exception("Endowment good_x inconsistent with budget good_x. "
                            "It is recommended to use the from_endowment alternative "
                            "constructor when supplying an endowment")
 
        if self.endowment.good_y != self.good_y:
            raise Exception("Endowment good_y inconsistent with budget good_y. "
                            "It is recommended to use the from_endowment alternative "
                            "constructor when supplying an endowment")
 
        if (self.endowment.income != (self.endowment.good_x_quantity * self.good_x.price +
                                      self.endowment.good_y_quantity * self.good_y.price)) | \
                (self.endowment.income != self.income):
 
            raise Exception("Endowment income inconsistent with supplied good prices. "
                            "It is recommended to use the from_endowment alternative "
                            "constructor when supplying an endowment")
 
        if self.endowment.good_x.price != self.good_x.price:
            raise Exception("Endowment good_x price inconsistent with budget good_x price. "
                            "It is recommended to use the from_endowment alternative "
                            "constructor when supplying an endowment")
 
        if self.endowment.good_y.price != self.good_y.price:
            raise Exception("Endowment good_y price inconsistent with budget good_y price. "
                            "It is recommended to use the from_endowment alternative "
                            "constructor when supplying an endowment")
...

And lastly, I added some consistency checks to make sure that the endowment value equals the sum product of the prices and quantities of the goods provided. The reason why these checks are here is because a person can still use the default constructor to specify each good individually along with an endowment, just based on how the arguments are defined. While this is possible, I would discourage doing this since 1) it’s less explicit than using the alternative constructors, 2) supplying the individual goods along with the endowment is redundant, and 3) it can lead to errors being thrown.

To initialize a budget by passing an endowment, simply use the alternative constructor:

Python
1
budget_endowment = Budget.from_endowment(endowment=endowment)

Slutsky Decomposition

The loosening of assumptions brought about by the endowment introduces some changes to the Slutsky equation. In the examples I provided a few weeks ago, we assumed that income remained fixed when prices changed. Since changes in price now change the value of the endowment, we must now account for this change in the Slutsky equation. The derivation of this modified form can be found in Varian, so I’ll skip to the result:

    \[\frac{\Delta x_1}{\Delta p_1} = \frac{\Delta x_1^s}{\Delta p_1} + (\omega_1 - x_1)\frac{\Delta x_1^m}{\Delta m}\]

The Slutsky equation can now be explained by three effects: the substitution and ordinary income effects, which are the same as before, and an endowment effect, which models how consumer choice changes when the value of the endowment changes.

Like the Budget class, the Slutsky class has been modified to take budgets that were constructed from individual goods or an endowment. Plotting the Slutsky class is now quite bit messier, since a new budget line, bundle, and utility curve are now added to an already crowded plot.

I have not yet gotten endowments to work within the context of insurance, so the image below comes from a modified version of an example provided in Varian where a milk producer faces a $1 increase in the price of milk – his endowment increases in value, and hence income. However with the graph as cluttered as it is, it can be hard to visually isolate the effects:

It does look better with a larger plotting area if you try it with MIES, but not so much when I have to shrink the image to fit it within the margins here.

Posted in: Actuarial, MIES

No. 142: The Property Casualty Data Model Specification

12 July, 2020 10:31 PM / 4 Comments / Gene Dan

Introduction

A few weeks ago, I stumbled across something neat – the Property Casualty Data Model (PCDM). PCDM is a relational database specification that covers all major parts of an insurance company’s operations. At first glance, the web page on which it is located seemed mundane to me, so I almost overlooked it, but when I opened the accompanying documentation, I realized I had stumbled upon a goldmine of useful information. This document contains enough information to implement an entire data warehouse and then tweak it to an organization’s specific needs.

Although we actuaries have a reputation for being able to handle data, most of us have not received any kind of formal training in handling relational database systems, and have had little interaction with standards organizations outside of our own governing organizations like the CAS, SOA, and AAA. When I tried searching for PCDM in the CAS library, I was astonished to find just a handful of references to the specification, and flabbergasted that there had been a document floating around on another profession’s website for the last seven years that almost no actuaries had ever heard about, but contained the exact type of information that many actuaries wanted but thought had never existed in the public domain (and in my case, it contains more than what I need for parts of the MIES backend).

One benefit that I’ve had from working several jobs, and also as a consultant, is that I’ve been able to witness widely varying levels of maturity of data warehouse systems at commercial insurance companies of different sizes and functions (specialty, commercial, and reinsurance) as well as those of a major stock exchange to get some perspective of how insurance database implementations compare to those of other industries. I have seen many actuaries at small and midsize carriers struggle with how to create OLAP data warehouses, not knowing what tables, relationships, and fields to define, how to do it in a way that conforms to commonly accepted data management practices (if they even knew what they were), or even where to look or whom to talk to to find out what data are stored at the company, and in what form.

Earlier in my career, at a small insurer, a few years before this document existed, I would sometimes encounter databases with hundreds of undocumented tables, not knowing what any of the tables stored, if they were the right tables I needed, or if they were designed appropriately. I was one of the few actuaries in my department who knew SQL (and even then, I wasn’t good at it). So, with my introductory textbook on database management systems at my side and a landline I used to contact people in the IT deparment, I embarked upon the long journey of understanding insurance information systems.

In those days, the game kind of went like this. I would ask my boss if they knew anyone in IT, then I’d pick up the phone and call them to ask if they maintained the database I was looking at or knew of anyone who did or anyone who might know anyone who did. That chain of phone calls typically went 5 people deep until I finally reached someone who actually worked on the relevant database, and if I was lucky, they’d have some documentation, and I’d slowly figure out what kind of data I was working with.

It might have looked like this. What the hell? Boss, this is gonna take me a while to understand. (Actually this is PCDM, but the good news about PCDM is that it’s documented – but imagine what it would be like if it weren’t and the last person who touched it left 3 years ago).

When I moved to a larger organization, I came to realize how large of a knowledge/talent gap there was between companies when I actually got to use a well-documented data warehouse that had all the entities, relationships, and fields defined as well a data dictionary detailing what all the values were – a rare practice that even many established insurers don’t follow. Unfortunately, when I left that organization, I also lost access to that documentation, and with it, a wealth of knowledge on what a proper data warehouse should look like.

I had thought to myself if only the CAS had a standard that actuaries and students could access, we’d have something that would actually resemble what a database at a real insurer actually looked like, instead of just having just theoretical papers from which to learn that might have some code copy-pasted in. If we had a standard, knowledge of proper database design and implementation would then not be employer dependent, and new research papers could reference the standard rather than just imagining what a data warehouse would look like or omitting proprietary parts of a company’s database.

When I came across PCDM, I realized the significance of a document I randomly found while eating breakfast on holiday. Therefore, I immediately got to work in writing an implementation of it in Python so that other actuaries could finally have what I wish I had when I was younger. I completed the first release at the end of the July 4th weekend, and made it available on GitHub. My hope is that somebody out there finds this post and clones my repository – and understands how important it is to spread word of this specification.

Subject Area Models

PCDM details 13 subject area models (SAMs), each of which comes with an entity-relationship (ER) diagram. Each subject area model represents a major portion of an insurance company’s operations:

  1. Party
  2. Account and Agreement
  3. Policy
  4. Claim
  5. Assessment
  6. Agreement Role
  7. Claim Role
  8. Staffing Role
  9. Party Subtype
  10. Insurable
  11. Money
  12. Event
  13. Product Coverage

For example, the Party SAM contains information on all parties that are involved in insurance transactions, such as households, employees, vendors, etc. Other SAMs contain information on underwriting, claims, and accounting operations. The rest of this post will show you what those SAMs look like – the images are crowded and contain quite a bit of information, so it’s best to click on them to see them in full resolution. If you want more details, the PCDM document is available on the object management group website.

Party

As stated before, the Party SAM contains information about households, firms, and staff:

Account and Agreement

The Account and Agreement SAM contains information on legal agreements, such as policies, reinsurance contracts, etc.

Policy

The Policy SAM contains information on…policies. Policy number, effective date, expiration date, limits, deductibles, coverage, etc.

Claim

The Claim SAM contains information on claims, relevant dates, adjusters, lawyers, damage amounts, etc.

Assessment

The Assessment SAM contains information on how the insurer goes about gathering information, such as credit scores, appraisals, and investigations carried out during the claim adjustment and underwriting processes.

Agreement

The Agreement Role SAM contains information on the different types of parties that might be involved in insurance – mostly an expansion of the Party Role superclass found in the Party SAM.

Claim Role

The Claim Role SAM contains information on the parties involved in the adjustment process, such as adjusters, claimants, lawyers, etc.

Staffing Role

The Staffing Role SAM contains information on insurance company staff and contractors.

Party Subtype

The Party Subtype SAM contains information on company subdivisions.

Insurable Object

The Insurable Object SAM contains information on things that can be insured, like cars and buildings.

Money

The Money SAM contains information on transactions, like premium, loss payments, and case reserves.

Event

The Event SAM contains information on policy and claim events, like policy inception, cancelation, and claim occurrence.

Product Coverage

The Product Coverage SAM contains inforamtion on product types and coverages.

Python/SQLAlchemy Implementation

I figured if I want to claim credit for anything besides just copying and pasting the diagrams above from the specification, I should actually make some kind of contribution. The good news is I haven’t found any kind of implementation on GitHub – what I mean by that is the PDF is nice to have and all, but you can’t deploy a datawarehouse with the PDF, it needs to be translated into code which people can then use to deploy the warehouse. Therefore, I’ve written my own implemntation of PCDM in Python using the SQLAlchemy ORM.

Below is an example of how I translated the Party SAM into code. I did this for the 12 other SAMs as well, and then wrote another module to combine them all together into a single deployable data warehouse:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
from sqlalchemy import Column, Integer, Date, String
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
 
from pcdm.base import Base
 
 
class Person(Base):
    __tablename__ = 'person'
 
    person_id = Column(
        Integer,
        primary_key=True
    )
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    prefix_name = Column(String)
 
    first_name = Column(String)
 
    middle_name = Column(String)
 
    last_name = Column(String)
 
    suffix_name = Column(String)
 
    full_legal_name = Column(String)
 
    nickname = Column(String)
 
    birth_date = Column(Date)
 
    birth_place_name = Column(String)
 
    gender_code = Column(String)
 
    person_profession = relationship(
        'PersonProfession',
        primaryjoin='Person.person_id == PersonProfession.person_id',
        back_populates='person'
    )
 
    staff_work_assignment = relationship(
        'Person',
        primaryjoin='Person.person_id == StaffWorkAssignment.person_id',
        back_populates='person'
    )
 
    household_person = relationship(
        'Person',
        primaryjoin='Person.person_id == HouseholdPerson.person_id',
        back_populates='person'
    )
 
    party = relationship(
        'Person',
        primaryjoin='Person.party_id == Party.party_id',
        back_populates='person'
    )
 
    household_person_role = relationship(
        'HouseholdPersonRole',
        primaryjoin='Person.person_id == HouseholdPersonRole.person_id',
        back_populates='person'
    )
 
    party_assessment = relationship(
        'PartyAssessment',
        primaryjoin='Person.person_id == PartyAssessment.person_id',
        back_populates='person'
    )
 
    staff_position_assignment = relationship(
        'StaffPositionAssignment',
        primaryjoin='Person.person_id == StaffPositionAssignment.person_id',
        back_populates='person'
    )
 
    def __repr__(self):
        return "<Person(" \
               "prefix_name='%s', " \
               "first_name='%s', " \
               "middle_name='%s', "\
               "last_name='%s', " \
               "suffix_name='%s', " \
               "full_legal_name='%s', " \
               "nickname='%s', " \
               "birth_date='%s', " \
               "birth_place_name='%s', " \
               "gender_code='%s', "\
               ")>" % (
                   self.prefix_name,
                   self.first_name,
                   self.middle_name,
                   self.last_name,
                   self.suffix_name,
                   self.full_legal_name,
                   self.nickname,
                   self.birth_date,
                   self.birth_place_name,
                   self.gender_code
                )
 
 
class PersonProfession(Base):
    __tablename__ = 'person_profession'
 
    person_profession_id = Column(
        Integer,
        primary_key=True
    )
 
    person_id = Column(
        Integer,
        ForeignKey('person.person_id')
    )
 
    profession_name = Column(String)
 
    person = relationship(
        'Person',
        primaryjoin='PersonProfession.person_id == Person.person_id',
        back_populates='person_profession'
    )
 
    def __repr__(self):
        return "<PersonProfession(" \
            "person_id='%s', " \
            "profession_name='%s', " \
            ")>" % (
                self.person_id,
                self.profession_name
            )
 
 
class Organization(Base):
    __tablename__ = 'organization'
 
    organization_id = Column(
        Integer,
        primary_key=True
    )
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    organization_type_code = Column(Integer)
 
    organization_name = Column(String)
 
    alternate_name = Column(String)
 
    acronym_name = Column(String)
 
    industry_type_code = Column(String)
 
    industry_code = Column(String)
 
    dun_and_bradstreet_id = Column(String)
 
    organization_description = Column(String)
 
    staff_work_assignment = relationship(
        'StaffWorkAssignment',
        primaryjoin='Organization.organization_id == StaffWorkAssignment.organization_id',
        back_populates='organization'
    )
 
    party = relationship(
        'Party',
        primaryjoin='Organization.party_id == Party.party_id',
        back_populates='organization'
    )
 
    staff_position_assignment = relationship(
        'StaffPositionAssignment',
        primaryjoin='Organization.organization_id == StaffPositionAssignment.organization_id',
        back_populates='organization'
    )
 
    organization_unit = relationship(
        'OrganizationUnit',
        primaryjoin='Organization.organization_id == OrganizationUnit.organization_id',
        back_populates='organization'
    )
 
    for_profit_organization = relationship(
        'ForProfitOrganization',
        primaryjoin='Organization.organization_id == ForProfitOrganization.organization_id',
        back_populates='organization'
    )
 
    government_organization = relationship(
        'GovernmentOrganization',
        primaryjoin='Organization.organization_id == GovernmentOrganization.organization_id',
        back_populates='organization'
    )
 
    not_for_profit_organization = relationship(
        'NotForProfitOrganization',
        primaryjoin='Organization.organization_id == NotForProfitOrganization.organization_id',
        back_populates='organization'
    )
 
    def __repr__(self):
        return "<Organization(" \
               "party_id='%s', " \
               "organization_type_code='%s', " \
               "organization_name='%s', " \
               "alternate_name='%s', "\
               "acronym_name='%s', " \
               "industry_type_code='%s', " \
               "industry_code='%s', " \
               "dun_and_bradstreet_id='%s', " \
               "organization_description='%s', " \
               ")>" % (
                   self.party_id,
                   self.organization_type_code,
                   self.organization_name,
                   self.alternate_name,
                   self.acronym_name,
                   self.industry_type_code,
                   self.industry_code,
                   self.dun_and_bradstreet_id,
                   self.organization_description
                )
 
 
class HouseholdPerson(Base):
    __tablename__ = 'household_person' \
                    ''
    household_person_id = Column(
        Integer,
        primary_key=True
    )
 
    household_id = Column(
        Integer,
        ForeignKey('household.household_id')
    )
 
    person_id = Column(
        Integer,
        ForeignKey('person.person_id')
    )
 
    household = relationship(
        'Household',
        primaryjoin='HouseholdPerson.household_id == Household.household_id',
        back_populates='household_person'
    )
 
    person = relationship(
        'Household',
        primaryjoin='HouseholdPerson.person_id == Person.person_id',
        back_populates='household_person'
    )
 
    def __repr__(self):
        return "<HouseholdPerson(" \
               "household_id='%s', " \
               "person_id='%s', " \
               ")>" % (
                   self.household_id,
                   self.person_id,
                )
 
 
class HouseholdPersonRole(Base):
    __tablename__ = 'household_person_role'
 
    household_person_role_id = Column(
        Integer,
        primary_key=True
    )
 
    household_id = Column(
        Integer,
        ForeignKey('household.household_id')
    )
 
    party_role_code = Column(
        String,
        ForeignKey('party_role.party_role_code')
    )
 
    begin_date = Column(Date)
 
    person_id = Column(
        Integer,
        ForeignKey('person.person_id')
    )
 
    end_date = Column(Date)
 
    household = relationship(
        'Household',
        primaryjoin='HouseholdPersonRole.household_id == Household.household_id',
        back_populates='household_person_role'
    )
 
    party_role = relationship(
        'PartyRole',
        primaryjoin='HouseholdPersonRole.party_role_code == PartyRole.party_role_code',
        back_populates='household_person_role'
    )
 
    person = relationship(
        'Person',
        primaryjoin='HouseholdPersonRole.person_id == Person.person_id',
        back_populates='household_person_role'
    )
 
    def __repr__(self):
        return "<HouseholdPersonRole(" \
               "household_id='%s', " \
               "party_role_code='%s', " \
               "begin_date='%s', "\
               "person_id='%s', " \
               "end_date='%s', " \
               ")>" % (
                   self.household_id,
                   self.party_role_code,
                   self.begin_date,
                   self.person_id,
                   self.end_date
                )
 
 
class Household(Base):
    __tablename__ = 'household'
 
    household_id = Column(
        Integer,
        primary_key=True
    )
 
    grouping_id = Column(
        Integer,
        ForeignKey('grouping.grouping_id')
    )
 
    household_person = relationship(
        'HouseholdPerson',
        primaryjoin='Household.household_id == HouseholdPerson.household_id',
        back_populates='household'
    )
 
    grouping = relationship(
        'Grouping',
        primaryjoin='Household.grouping_id == Grouping.grouping_id',
        back_populates='household'
    )
 
    household_person_role = relationship(
        'HouseholdPersonRole',
        primaryjoin='Household.household_id == HouseholdPersonRole.household_id',
        back_populates='household'
    )
 
    household_content = relationship(
        'HouseholdContent',
        primaryjoin='Household.household_id == HouseholdContent.household_id',
        back_populates='household'
    )
 
    def __repr__(self):
        return "<Household(" \
               "grouping_id='%s', " \
               ")>" % (
                   self.grouping_id
                )
 
 
class StaffWorkAssignment(Base):
    __tablename__ = 'staff_work_assignment'
 
    staff_work_assignment_id = Column(
        Integer,
        primary_key=True
    )
 
    person_id = Column(
        Integer,
        ForeignKey('person.person_id')
    )
 
    organization_id = Column(
        Integer,
        ForeignKey('organization.organization_id')
    )
 
    grouping_id = Column(
        Integer,
        ForeignKey('grouping.grouping_id')
    )
 
    begin_date = Column(Date)
    party_role_code = Column(
        Integer,
        ForeignKey('party_role.party_role_code')
    )
    end_date = Column(Date)
 
    person = relationship(
        'Person',
        primaryjoin='StaffWorkAssignment.person_id == Person.person_id',
        back_populates='staff_work_assignment'
    )
 
    organization = relationship(
        'Organization',
        primaryjoin='StaffWorkAssignment.organization_id == Organization.organization_id',
        back_populates='staff_work_assignment'
    )
 
    grouping = relationship(
        'Grouping',
        primaryjoin='StaffWorkAssignment.grouping_id == Grouping.grouping_id',
        back_populates='staff_work_assignment'
    )
 
    party_role = relationship(
        'PartyRole',
        primaryjoin='StaffWorkAssignment.party_role_code == PartyRole.party_role_code',
        back_populates='staff_work_assignment'
    )
 
    def __repr__(self):
        return "<StaffWorkAssignment(" \
               "person_id='%s', " \
               "organization_id='%s', " \
               "grouping_id='%s', "\
               "begin_date='%s', " \
               "party_role_code='%s', " \
               "end_date='%s', " \
               ")>" % (
                   self.person_id,
                   self.organization_id,
                   self.grouping_id,
                   self.begin_date,
                   self.party_role_code,
                   self.end_date
                )
 
 
class Grouping(Base):
    __tablename__ = 'grouping'
 
    grouping_id = Column(
        Integer,
        primary_key=True
    )
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    grouping_name = Column(String)
 
    staff_work_assignment = relationship(
        'StaffWorkAssignment',
        primaryjoin='Grouping.grouping_id == StaffWorkAssignment.grouping_id',
        back_populates='grouping'
    )
 
    party = relationship(
        'Party',
        primaryjoin='Grouping.party_id == party.party_id',
        back_populates='grouping'
    )
 
    household = relationship(
        'Household',
        primaryjoin='Grouping.grouping_id == Household.grouping_id',
        back_populates='grouping'
    )
 
    professional_group = relationship(
        'ProfessionalGroup',
        primaryjoin='Grouping.grouping_id == ProfessionalGroup.grouping_id',
        back_populates='grouping'
    )
 
    project = relationship(
        'Project',
        primaryjoin='Grouping.grouping_id == Project.grouping_id',
        back_populates='grouping'
    )
 
    team = relationship(
        'Team',
        primaryjoin='Grouping.grouping_id == Team.grouping_id',
        back_populates='grouping'
    )
 
    def __repr__(self):
        return "<Grouping(" \
               "party_id='%s', " \
               "grouping_name='%s', " \
               ")>" % (
                   self.party_id,
                   self.grouping_name
                )
 
 
class PartyRole(Base):
    __tablename__ = 'party_role'
 
    party_role_code = Column(
        String,
        primary_key=True
    )
 
    party_role_name = Column(String)
 
    party_role_description = Column(String)
 
    staff_work_assignment = relationship(
        'StaffWorkAssignment',
        primaryjoin='PartyRole.party_role_code == StaffWorkAssignment.party_role_code',
        back_populates='party_role'
    )
 
    party_relationship_role = relationship(
        'PartyRelationshipRole',
        primaryjoin='PartyRole.party_role_code == PartyRelationshipRole.party_role_code',
        back_populates='party_role'
    )
 
    insurable_object_party_role = relationship(
        'InsurableObjectPartyRole',
        primaryjoin='Party.party_role_code == InsurableObjectPartyRole.party_role_code',
        back_populates='party_role'
    )
 
    claim_party_role = relationship(
        'ClaimPartyRole',
        primaryjoin='PartyRole.party_role_code == ClaimPartyRole.party_role_code',
        back_populates='party_role'
    )
 
    agreement_party_role = relationship(
        'AgreementPartyRole',
        primaryjoin='PartyRole.party_role_code == AgreementPartyRole.party_role_code',
        back_populates='party_role'
    )
 
    household_person_role = relationship(
        'HouseholdPersonRole',
        primaryjoin='PartyRole.party_role_code == HouseholdPersonRole.party_role_code',
        back_populates='party_role'
    )
 
    account_party_role = relationship(
        'AccountPartyRole',
        primaryjoin='PartyRole.party_role_code == AccountPartyRole.party_role_code',
        back_populates='party_role'
    )
 
    provider = relationship(
        'Provider',
        primaryjoin='PartyRole.party_role_code == Provider.party_role_code',
        back_populates='party_role'
    )
 
    arbitration_party_role = relationship(
        'ArbitrationPartyRole',
        primaryjoin='PartyRole.party_role_code == ArbitrationPartyRole.party_role_code',
        back_populates='party_role'
    )
 
    litigation_party_role = relationship(
        'LitigationPartyRole',
        primaryjoin='PartyRoleCode.party_role_code == LitigationPartyRole.party_role_code',
        back_populates='party_role'
    )
 
    assessment_party_role = relationship(
        'AssessmentPartyRole',
        primaryjoin='PartyRole.party_role_code == AssessmentPartyRole.party_role_code',
        back_populates='party_role'
    )
 
    claim_role = relationship(
        'ClaimRole',
        primaryjoin='PartyRole.party_role_code == ClaimRole.party_role_code',
        back_populates='party_role'
    )
 
    adjuster = relationship(
        'Adjuster',
        primaryjoin='PartyRole.party_role_code == Adjuster.party_role_code',
        back_populates='party_role'
    )
 
    staffing_organization = relationship(
        'StaffingOrganization',
        primaryjoin='PartyRole.party_role_code == StaffingOrganization.party_role_code',
        back_populates='party_role'
    )
 
    staff = relationship(
        'Staff',
        primaryjoin='PartyRole.party_role_code == Staff.party_role_code',
        back_populates='party_role'
    )
 
    def __repr__(self):
        return "<PartyRole(" \
               "party_role_name='%s', " \
               "party_role_description='%s', " \
               ")>" % (
                   self.party_role_name,
                   self.party_role_description
                )
 
 
class Party(Base):
    __tablename__ = 'party'
 
    party_id = Column(
        Integer,
        primary_key=True
    )
 
    party_name = Column(String)
 
    party_type_code = Column(String)
 
    begin_date = Column(Date)
 
    end_date = Column(Date)
 
    person = relationship(
        'Person',
        primaryjoin='Party.party_id == Person.party_id',
        back_populates='party'
    )
 
    grouping = relationship(
        'Grouping',
        primaryjoin='Party.party_id == Grouping.party_id',
        back_populates='party'
    )
 
    organization = relationship(
        'Organization',
        primaryjoin='Party.party_id == Organization.party_id',
        back_populates='party'
    )
 
    party_relationship = relationship(
        'PartyRelationship',
        primaryjoin='Party.party_id = PartyRelationship.party_id',
        back_populates='party'
    )
 
    related_party_relationship = relationship(
        'PartyRelationship',
        primaryjoin='Party.party_id = PartyRelationship.related_party_id',
        back_populates='related_party'
    )
 
    legal_jurisdiction_party_identity = relationship(
        'LegalJurisdictionPartyIdentity',
        primaryjoin='Party.party_id == LegalJurisdictionPartyIdentity.party_id',
        back_populates='party'
    )
 
    party_communication = relationship(
        'PartyCommunication',
        primaryjoin='Party.party_id == PartyCommunication.party_id',
        back_populates='party'
    )
 
    insurable_object_party_role = relationship(
        'InsurableObjectPartyRole',
        primaryjoin='Party.party_id == InsurableObjectPartyRole.party_id',
        back_populates='party'
    )
 
    party_preference = relationship(
        'PartyPreference',
        primaryjoin='Party.party_id == PartyPreference.party_id',
        back_populates='party'
    )
 
    agreement_party_role = relationship(
        'AgreementPartyRole',
        primaryjoin='Party.party_id == AgreementPartyRole.party_id',
        back_populates='party'
    )
 
    account_party_role = relationship(
        'AccountPartyRole',
        primaryjoin='Party.party_id == AccountPartyRole.party_id',
        back_populates='party'
    )
 
    arbitration_party_role = relationship(
        'ArbitrationPartyRole',
        primaryjoin='Party.party_id == ArbitrationPartyRole.party_id',
        back_populates='party'
    )
 
    litigation_party_role = relationship(
        'LitigationPartyRole',
        primaryjoin='Party.party_id == LitigationPartyRole.party_id',
        back_populates='party'
    )
 
    assessment_party_role = relationship(
        'AssessmentPartyRole',
        primaryjoin='Party.party_id == AssessmentPartyRole.party_id',
        back_populates='party'
    )
 
    party_assessment = relationship(
        'PartyAssessment',
        primaryjoin='Party.party_id == PartyAssessment.party_id',
        back_populates='party'
    )
 
    def __repr__(self):
        return "<Party(" \
               "party_name='%s', " \
               "party_type_code='%s', " \
               "begin_date='%s', " \
               "end_date='%s', " \
               ")>" % (
                   self.party_name,
                   self.party_type_code,
                   self.begin_date,
                   self.end_date
                )
 
 
class PartyRelationship(Base):
    __tablename__ = 'party_relationship'
 
    party_relationship_id = Column(
        Integer,
        primary_key=True
    )
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    related_party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    relationship_type_code = Column(String)
 
    begin_date = Column(Date)
 
    end_date = Column(Date)
 
    party = relationship(
        'Party',
        primaryjoin='PartyRelationship.party_id = Party.party_id',
        back_populates='party_relationship'
    )
 
    related_party = relationship(
        'Party',
        primaryjoin='PartyRelationship.related_party_id = Party.party_id',
        back_populates='related_party_relationship'
    )
 
    party_relationship_role = relationship(
        'PartyRelationshipRole',
        primaryjoin='PartyRelationship.party_id == PartyRelationshipRole.party_id ',
        back_populates='party_relationship'
    )
 
    related_party_relationship_role = relationship(
        'PartyRelationshipRole',
        primaryjoin='PartyRelationship.related_party_id == PartyRelationshipRole.related_party_id',
        back_populates='related_party_relationship'
    )
 
    party_relationship_role_type_code = relationship(
        'PartyRelationshipRole',
        primaryjoin='PartyRelationship.relationship_type_code == PartyRelationshipRole.relationship_type_code',
        back_populates='party_relationship_type_code'
    )
 
    party_relationship_role_begin_date = relationship(
        'PartyRelationship',
        primaryjoin='PartyRelationship.begin_date == PartyRelationshipRole.relationship_begin_date',
        back_populates='party_relationship_begin_date'
    )
 
    def __repr__(self):
        return "<PartyRelationship(" \
               "party_id='%s', " \
               "relationship_type_code='%s', " \
               "begin_date='%s', " \
               "end_date='%s', " \
               ")>" % (
                   self.party_id,
                   self.relationship_type_code,
                   self.begin_date,
                   self.end_date
                )
 
 
class PartyRelationshipRole(Base):
    __tablename__ = 'party_relationship_role'
 
    party_relationship_role_id = Column(
        Integer,
        primary_key=True
    )
 
    party_id = Column(
        Integer,
        ForeignKey('party_relationship.party_id')
    )
 
    related_party_id = Column(
        Integer,
        ForeignKey('party_relationship.related_party_id')
    )
 
    relationship_type_code = Column(
        Integer,
        ForeignKey('party_relationship.relationship_type_code')
    )
 
    relationship_begin_date = Column(
        Date,
        ForeignKey('party_relationship.begin_date')
    )
 
    party_role_code = Column(
        String,
        ForeignKey('party_role.party_role_code')
    )
 
    role_begin_date = Column(Date)
 
    party_relationship = relationship(
        'PartyRelationship',
        primaryjoin='PartyRelationshipRole.party_id == PartyRelationship.party_id',
        back_populates='party_relationship_role'
    )
 
    related_party_relationship = relationship(
        'PartyRelationship',
        primaryjoin='PartyRelationshipRole.related_party_id == PartyRelationship.related_party_id',
        back_populates='related_party_relationship_role'
    )
 
    party_relationship_type_code = relationship(
        'PartyRelationship',
        primaryjoin='PartyRelationshipRole.relationship_type_code == PartyRelationship.relationship_type_code',
        back_populates='party_relationship_role_type_code'
    )
 
    party_relationship_begin_date = relationship(
        'PartyRelationship',
        primaryjoin='PartyRelationshipRole.relationship_begin_date == PartyRelationship.begin_date',
        back_populates='party_relationship_role_begin_date'
    )
 
    party_role = relationship(
        'PartyRole',
        primaryjoin='PartyRelationshipRole.party_role_code == PartyRole.party_role_code',
        back_populates='party_relationship_role'
    )
 
    def __repr__(self):
        return "<PartyRelationshipRole(" \
               "party_id='%s', " \
               "related_party_id='%s', " \
               "relationship_type_code='%s', "\
               "relationship_begin_date='%s', " \
               "party_role_code='%s', " \
               "role_begin_date='%s', " \
               ")>" % (
                   self.party_id,
                   self.related_party_id,
                   self.relationship_type_code,
                   self.relationship_begin_date,
                   self.party_role_code,
                   self.role_begin_date
                )
 
 
class LegalJurisdictionPartyIdentity(Base):
    __tablename__ = 'legal_jurisdiction_party_identity'
 
    legal_jurisdiction_party_id = Column(
        Integer,
        primary_key=True
    )
 
    legal_jurisdiction_id = Column(
        Integer,
        ForeignKey('legal_jurisdiction.legal_jurisdiction_id')
    )
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    legal_identity_type_code = Column(String)
    legal_classification_code = Column(String)
 
    party = relationship(
        'Party',
        primaryjoin='LegalJurisdictionPartyIdentity.party_id == Party.party_id',
        back_populates='legal_jurisdiction_party_identity'
    )
 
    legal_jurisdiction = relationship(
        'LegalJurisdiction',
        primaryjoin='LegalJurisdictionPartyIdentity.legal_jurisdiction_id == LegalJurisdiction.legal_jurisdiction_id',
        back_populates='legal_jurisdiction_party_identity'
    )
 
    def __repr__(self):
        return "<LegalJurisdictionPartyIdentity(" \
               "legal_jurisdiction_id='%s', " \
               "party_id='%s', " \
               "legal_identity_type_code='%s', "\
               "legal_classification_code='%s', " \
               ")>" % (
                   self.legal_jurisdiction_id,
                   self.party_id,
                   self.legal_identity_type_code,
                   self.legal_classification_code
                )
 
 
class LegalJurisdiction(Base):
    __tablename__ = 'legal_jurisdiction'
 
    legal_jurisdiction_id = Column(
        Integer,
        primary_key=True
    )
 
    legal_jurisdiction_name = Column(String)
    legal_jurisdiction_description = Column(String)
    rules_preference_description = Column(String)
 
    legal_jurisdiction_party_identity = relationship(
        'LegalJurisdictionPartyIdentity',
        primaryjoin='LegalJurisdiction.legal_jurisdiction_id == LegalJurisdictionPartyIdentity.legal_jurisdiction_id',
        back_populates='legal_jurisdiction'
    )
 
    def __repr__(self):
        return "<LegalJurisdiction(" \
               "legal_jurisdiction_name='%s', " \
               "legal_jurisdiction_description='%s', " \
               "rules_preference_description='%s', "\
               ")>" % (
                   self.legal_jurisdiction_name,
                   self.legal_jurisdiction_description,
                   self.rules_preference_description
                )
 
 
class PartyCommunication(Base):
    __tablename__ = 'party_communication'
 
    party_communication_id = Column(
        Integer,
        primary_key=True
    )
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    communication_id = Column(
        Integer,
        ForeignKey('communication_identity.communication_id')
    )
 
    party_locality_code = Column(Integer)
 
    begin_date = Column(Date)
 
    end_date = Column(Date)
 
    preference_sequence_number = Column(Integer)
 
    preference_day_and_time_group_code = Column(Integer)
 
    party_routing_description = Column(String)
 
    party = relationship(
        'Party',
        primaryjoin='PartyCommunication.party_id == Party.party_id',
        back_populates='party_communication'
    )
 
    communication = relationship(
        'CommunicationIdentity',
        primaryjoin='PartyCommunication.communication_id == CommunicationIdentity.communication_id',
        back_populates='party_communication'
    )
 
    def __repr__(self):
        return "<PartyCommunication(" \
               "party_id='%s', " \
               "communication_id='%s', " \
               "party_locality_code='%s', " \
               "begin_date='%s', " \
               "end_date='%s', "\
               "preference_sequence_number='%s', " \
               "preference_day_and_time_group_code='%s', " \
               "party_routing_description='%s', " \
               ")>" % (
                   self.party_id,
                   self.communication_id,
                   self.party_locality_code,
                   self.begin_date,
                   self.end_date,
                   self.preference_sequence_number,
                   self.preference_day_and_time_group_code,
                   self.party_routing_description
                )
 
 
class CommunicationIdentity(Base):
    __tablename__ = 'communication_identity'
 
    communication_id = Column(
        Integer,
        primary_key=True
    )
 
    communication_type_code = Column(String)
    communication_value = Column(String)
    communication_qualifier_value = Column(String)
 
    geographic_location_id = Column(
        Integer,
        ForeignKey('geographic_location.geographic_location_id')
    )
 
    party_communication = relationship(
        'PartyCommunication',
        primaryjoin='CommunicationIdentity.communication_id == PartyCommunication.communication_id',
        back_populates='communication'
    )
    geographic_location = relationship(
        'GeographicLocationIdentifier',
        primaryjoin='CommunicationIdentity.geographic_location_id == '
                    'GeographicLocationIdentifier.geographic_location_id',
        back_populates='communication_identity'
    )
 
    def __repr__(self):
        return "<CommunicationIdentity(" \
               "communication_type_code='%s', " \
               "communication_value='%s', " \
               "communication_qualifier_value='%s', " \
               "geographic_location_id='%s', " \
               ")>" % (
                   self.communication_type_code,
                   self.communication_value,
                   self.communication_qualifier_value,
                   self.geographic_location_id
                )
 
 
class GeographicLocation(Base):
    __tablename__ = 'geographic_location'
 
    geographic_location_id = Column(
        Integer,
        primary_key=True
    )
 
    geographic_location_type_code = Column(String)
 
    location_code = Column(String)
 
    location_name = Column(String)
 
    location_number = Column(String)
 
    state_code = Column(
        String,
        ForeignKey('state.state_code')
    )
 
    parent_geographic_location_id = Column(
        Integer,
        ForeignKey('geographic_location.geographic_location_id')
    )
 
    location_address_id = Column(
        Integer,
        ForeignKey('location_address.location_address_id')
    )
 
    physical_location_identifier = Column(
        Integer,
        ForeignKey('physical_location.physical_location_id')
    )
 
    geographic_location_parent = relationship(
        'GeographicLocation',
        primaryjoin='GeographicLocation.parent_geographic_location_id =='
                    ' GeographicLocation.geographic_location_id',
        back_populates='geographic_location_parent_u'
    )
 
    geographic_location_parent_u = relationship(
        'GeographicLocation',
        primaryjoin='GeographicLocation.geographic_location_id =='
                    ' GeographicLocation.parent_geographic_location_id',
        back_populates='geographic_location_parent'
    )
 
    communication_identity = relationship(
        'GeographicLocation',
        primaryjoin='CommunicationIdentity.geographic_location_id == '
                    'GeographicLocation.geographic_location_id',
        back_populates='geographic_location'
    )
 
    insurable_object = relationship(
        'InsurableObject',
        primaryjoin='GeographicLocation.geographic_location_id == InsurableObject.geographic_location_id',
        back_populates='geographic_location'
    )
 
    policy = relationship(
        'Policy',
        primaryjoin='GeographicLocation.geographic_location_id == Policy.geographic_location_id',
        back_populates='geographic_location'
    )
 
    policy_amount = relationship(
        'PolicyAmount',
        primaryjoin='GeographicLocation.geographic_location_id == PolicyAmount.geographic_location_id',
        back_populates='geographic_location'
    )
 
    location_address = relationship(
        'LocationAddress',
        primaryjoin='GeographicLocation.location_address_id == LocationAddress.location_address_id',
        back_populates='geographic_location'
    )
 
    physical_location = relationship(
        'PhysicalLocation',
        primaryjoin='GeographicLocation.physical_location_id == PhysicalLocation.physical_location_id',
        back_populates='geographic_location'
    )
 
    occurrence = relationship(
        'Occurrence',
        primaryjoin='GeographicLocation.geographic_location_id == Occurrence.geographic_location_id',
        back_populates='geographic_location'
    )
 
    rating_territory_geographic_location = relationship(
        'RatingTerritoryGeographicLocation',
        primaryjoin='GeographicLocation.geographic_location_id == '
                    'RatingTerritoryGeographicLocation.geographic_location_id',
        back_populates='geographic_location'
    )
 
    state = relationship(
        'State',
        primaryjoin='GeographicLocation.state_code == State.state_code',
        back_populates='geographic_location'
    )
 
    company_jurisdiction = relationship(
        'CompanyJurisdiction',
        primaryjoin='GeographicLocation.geographic_location_id == CompanyJurisdiction.geographic_location_id',
        back_populates='geographic_location'
    )
 
    def __repr__(self):
        return "<GeographicLocation(" \
               "geographic_location_type_code='%s', " \
               "location_code='%s', " \
               "location_name='%s', "\
               "location_number='%s', " \
               "state_code='%s', " \
               "parent_geographic_location_id='%s', " \
               "location_address_identifier='%s', " \
               "physical_location_identifier='%s', " \
               ")>" % (
                   self.geographic_location_type_code,
                   self.location_code,
                   self.location_name,
                   self.location_number,
                   self.state_code,
                   self.parent_geographic_location_id,
                   self.location_address_identifier,
                   self.physical_location_identifier
                )
 
 
class InsurableObject(Base):
    __tablename__ = 'insurable_object'
 
    insurable_object_id = Column(
        Integer,
        primary_key=True
    )
 
    insurable_object_type_code = Column(Integer)
 
    geographic_location_id = Column(
        Integer,
        ForeignKey('geographic_location.geographic_location_id')
    )
 
    geographic_location = relationship(
        'GeographicLocation',
        primaryjoin='InsurableObject.geographic_location_id == GeographicLocation.geographic_location_id',
        back_populates='insurable_object'
    )
 
    claim = relationship(
        'Claim',
        primaryjoin='InsurableObject.insurable_object_id == Claim.insurable_object_id',
        back_populates='insurable_object'
    )
 
    insurable_object_party_role = relationship(
        'InsurableObjectPartyRole',
        primaryjoin='InsurableObject.insurable_object_id == InsurableObjectPartyRole.insurable_object_id',
        back_populates='insurable_object'
    )
 
    policy_coverage_detail = relationship(
        'PolicyCoverageDetail',
        primaryjoin='InsurableObject.insurable_object_id == PolicyCoverageDetail.insurable_object_id',
        back_populates='insurable_object'
    )
 
    policy_amount = relationship(
        'PolicyAmount',
        primaryjoin='InsurableObject.insurable_object_id == PolicyAmount.insurable_object_id',
        back_populates='insurable_object'
    )
 
    object_assessment = relationship(
        'ObjectAssessment',
        primaryjoin='InsurableObject.insurable_object_id == ObjectAssessment.insurable_object_id',
        back_populates='insurable_object'
    )
 
    vehicle = relationship(
        'Vehicle',
        primaryjoin='InsurableObject.insurable_object_id == Vehicle.insurable_object_id',
        back_populates='insurable_object'
    )
 
    manufactured_object = relationship(
        'ManufacturedObject',
        primaryjoin='InsurableObject.insurable_object_id == ManufacturedObject.insurable_object_id',
        back_populates='insurable_object'
    )
 
    farm_equipment = relationship(
        'FarmEquipment',
        primaryjoin='InsurableObject.insurable_object_id == FarmEquipment.insurable_object_id',
        back_populates='insurable_object'
    )
 
    body_object = relationship(
        'BodyObject',
        primaryjoin='InsurableObject.insurable_object_id == BodyObject.insurable_object_id',
        back_populates='insurable_object'
    )
 
    workers_comp_class = relationship(
        'WorkersCompClass',
        primaryjoin='InsurableObject.insurable_object_id == WorkersCompClass.insurable_object_id',
        back_populates='insurable_object'
    )
 
    structure = relationship(
        'Structure',
        primaryjoin='InsurableObject.insurable_object_id == Structure.insurable_object_id',
        back_populates='insurable_object'
    )
 
    transportation_class = relationship(
        'TransportationClass',
        primaryjoin='InsurableObject.insurable_object_id == TransportationClass.insurable_object_id',
        back_populates='insurable_object'
    )
 
    def __repr__(self):
        return "<InsurableObject(" \
               "insurable_object_type_code='%s', " \
               "geographic_location_id='%s', " \
               ")>" % (
                   self.insurable_object_type_code,
                   self.geographic_location_id
                )
 
 
class Claim(Base):
    __tablename__ = 'claim'
 
    claim_id = Column(
        Integer,
        primary_key=True
    )
 
    occurrence_id = Column(
        Integer,
        ForeignKey('occurrence.occurrence_id')
    )
 
    catastrophe_id = Column(
        Integer,
        ForeignKey('catastrophe.catastrophe_id')
    )
 
    insurable_object_id = Column(
        Integer,
        ForeignKey('insurable_object.insurable_object_id')
    )
 
    company_claim_number = Column(Integer)
 
    company_subclaim_number = Column(Integer)
 
    claim_description = Column(String)
 
    claim_open_date = Column(Date)
 
    claim_close_date = Column(Date)
 
    claim_reopen_date = Column(Date)
 
    claim_status_code = Column(String)
 
    claim_reported_date = Column(Date)
 
    claims_made_date = Column(Date)
 
    entry_in_to_claims_made_program_date = Column(Date)
 
    insurable_object = relationship(
        'InsurableObject',
        primaryjoin='Claim.insurable_object_id == InsurableObject.insurable_object_id',
        back_populates='claim'
    )
 
    occurrence = relationship(
        'Occurrence',
        primaryjoin='Claim.occurrence_id == Occurrence.occurrence_id',
        back_populates='claim'
    )
 
    catastrophe = relationship(
        'Catastrophe',
        primaryjoin='Claim.catastrophe_id == Catastrophe.catastrophe_id',
        back_populates='claim'
    )
 
    claim_coverage = relationship(
        'ClaimCoverage',
        primaryjoin='Claim.claim_id == ClaimCoverage.claim_id',
        back_populates='claim'
    )
 
    claim_amount = relationship(
        'ClaimAmount',
        primaryjoin='Claim.claim_id == ClaimAmount.claim_id',
        back_populates='claim'
    )
 
    claim_folder = relationship(
        'ClaimFolder',
        primaryjoin='Claim.claim_id == ClaimFolder.claim_id',
        back_populates='claim'
    )
 
    arbitration_party_role = relationship(
        'ArbitrationPartyRole',
        primaryjoin='Claim.claim_id == ArbitrationPartyRole.claim_id',
        back_populates='claim'
    )
 
    claim_litigation = relationship(
        'ClaimLitigation',
        primaryjoin='Claim.claim_id == ClaimLitigation.claim_id',
        back_populates='claim'
    )
 
    claim_arbitration = relationship(
        'ClaimArbitration',
        primaryjoin='Claim.claim_id == ClaimArbitration.claim_id',
        back_populates='claim'
    )
 
    litigation_party_role = relationship(
        'LitigationPartyRole',
        primaryjoin='Claim.claim_id == LitigationPartyRole.claim_id',
        back_populates='claim'
    )
 
    claim_assessment = relationship(
        'ClaimAssessment',
        primaryjoin='Claim.claim_id == ClaimAssessment.claim_id',
        back_populates='claim'
    )
 
    def __repr__(self):
        return "<Claim(" \
               "occurrence_id='%s', " \
               "catastrophe_id='%s', " \
               "insurable_object_id='%s', "\
               "company_claim_number='%s', " \
               "company_subclaim_number='%s', " \
               "claim_description='%s', " \
               "claim_open_date='%s', " \
               "claim_close_date='%s', " \
               "claim_reopen_date='%s', " \
               "claim_status_code='%s', " \
               "claim_reported_date='%s', "\
               "claims_made_date='%s', "\
               "entry_in_to_claims_made_program_date='%s', "\
               ")>" % (
                   self.occurrence_id,
                   self.catastrophe_id,
                   self.insurable_object_id,
                   self.company_claim_number,
                   self.company_subclaim_number,
                   self.claim_description,
                   self.claim_open_date,
                   self.claim_close_date,
                   self.claim_reopen_date,
                   self.claim_status_code,
                   self.claim_reported_date,
                   self.claims_made_date,
                   self.entry_in_to_claims_made_program_date
                )
 
 
class InsurableObjectPartyRole(Base):
    __tablename__ = 'insurable_object_party_role'
 
    insurable_object_party_role_id = Column(
        Integer,
        primary_key=True
    )
 
    insurable_object_id = Column(
        Integer,
        ForeignKey('insurable_object.insurable_object_id')
    )
 
    party_role_code = Column(
        String,
        ForeignKey('party_role.party_role_code')
    )
 
    effective_date = Column(Date)
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    expiration_date = Column(Date)
 
    insurable_object = relationship(
        'InsurableObject',
        primaryjoin='InsurableObjectPartyRole.insurable_object_id == InsurableObject.insurable_object_id',
        back_populates='insurable_object_party_role'
    )
 
    party_role = relationship(
        'PartyRole',
        primaryjoin='InsurableObjectPartyRole.party_role_code == PartyRole.party_role_code',
        back_populates='insurable_object_party_role'
    )
 
    party = relationship(
        'Party',
        primaryjoin='InsurableObjectPartyRole.party_id == Party.party_id',
        back_populates='insurable_object_party_role'
    )
 
    def __repr__(self):
        return "<InsurableObjectPartyRole(" \
               "insurable_object_id='%s', " \
               "party_role_code='%s', " \
               "effective_date='%s', "\
               "party_id='%s', " \
               "expiration_date='%s', " \
               ")>" % (
                   self.insurable_object_id,
                   self.party_role_code,
                   self.effective_date,
                   self.party_id,
                   self.expiration_date
                )
 
 
class ClaimPartyRole(Base):
    __tablename__ = 'claim_party_role'
 
    claim_party_role_id = Column(
        Integer,
        primary_key=True
    )
 
    party_role_code = Column(
        String,
        ForeignKey('party_role.party_role_code')
    )
 
    begin_date = Column(Date)
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    end_date = Column(Date)
 
    party_role = relationship(
        'PartyRole',
        primaryjoin='ClaimPartyRole.party_role_code == PartyRole.party_role_code',
        back_populates='claim_party_role'
    )
 
    party = relationship(
        'Party',
        primaryjoin='ClaimPartyRole.party_id == Party.party_id',
        back_populates='claim_party_role'
    )
 
    def __repr__(self):
        return "<ClaimPartyRole(" \
               "party_role_code='%s', " \
               "begin_date='%s', " \
               "party_id='%s', " \
               "end_date='%s', " \
               ")>" % (
                   self.party_role_code,
                   self.begin_date,
                   self.party_id,
                   self.end_date
                )
 
 
class PartyPreference(Base):
    __tablename__ = 'party_preference'
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id'),
        primary_key=True
    )
 
    preferred_language_code = Column(Integer)
 
    party = relationship(
        'Party',
        primaryjoin='PartyPreference.party_id == Party.party_id',
        back_populates='party_preference'
    )
 
    def __repr__(self):
        return "<PartyPreference(" \
               "preferred_language_code='%s', " \
               ")>" % (
                   self.preferred_language_code
                )
 
 
class Agreement(Base):
    __tablename__ = 'agreement'
 
    agreement_id = Column(
        Integer,
        primary_key=True
    )
 
    agreement_type_code = Column(Integer)
 
    agreement_name = Column(String)
 
    agreement_original_inception_date = Column(Date)
 
    product_id = Column(
        Integer,
        ForeignKey('product.product_id')
    )
 
    agreement_party_role = relationship(
        'AgreementPartyRole',
        primaryjoin='Agreement.agreement_id == AgreementPartyRole.agreement_id',
        back_populates='agreement'
    )
 
    account_agreement = relationship(
        'AccountAgreement',
        primaryjoin='Agreement.agreement_id == AccountAgreement.agreement_id',
        back_populates='agreement'
    )
 
    policy = relationship(
        'Policy',
        primaryjoin='Agreement.agreement_id == Policy.agreement_id',
        back_populates='agreement'
    )
 
    agency_contract = relationship(
        'AgencyContract',
        primaryjoin='agreement.agreement_id == AgencyContract.agreement_id',
        back_populates='agreement'
    )
 
    reinsurance_agreement = relationship(
        'ReinsuranceAgreement',
        primaryjoin='Agreement.agreement_id == ReinsuranceAgreement.agreement_id',
        back_populates='agreement'
    )
 
    commercial_agreement = relationship(
        'CommercialAgreement',
        primaryjoin='Agreement.agreement_id == CommercialAgreement.agreement_id',
        back_populates='agreement'
    )
 
    brokerage_contract = relationship(
        'BrokerageContract',
        primaryjoin='Agreement.agreement_id == BrokerageContract.agreement_id',
        back_populates='agreement'
    )
 
    financial_account_agreement = relationship(
        'FinancialAccountAgreement',
        primaryjoin='Agreement.agreement_id == FinancialAccountAgreement.agreement_id',
        back_populates='agreement'
    )
 
    derivative_contract = relationship(
        'DerivativeContract',
        primaryjoin='Agreement.agreement_id == DerivativeContract.agreement_id',
        back_populates='agreement'
    )
 
    intermediary_agreement = relationship(
        'IntermediaryAgreement',
        primaryjoin='Agreement.agreement_id == IntermediaryAgreement.agreement_id',
        back_populates='agreement'
    )
 
    group_agreement = relationship(
        'GroupAgreement',
        primaryjoin='Agreement.agreement_id == GroupAgreement.agreement_id',
        back_populates='agreement'
    )
 
    commutation_agreement = relationship(
        'CommutationAgreement',
        primaryjoin='Agreement.agreement_id == CommutationAgreement.agreement_id',
        back_populates='agreement'
    )
 
    provider_agreement = relationship(
        'ProviderAgreement',
        primaryjoin='Agreement.agreement_id == ProviderAgreement.agreement_id',
        back_populates='agreement'
    )
 
    individual_agreement = relationship(
        'IndividualAgreement',
        primaryjoin='Agreement.agreement_id == IndividualAgreement.agreement_id',
        back_populates='agreement'
    )
 
    auto_repair_shop_contract = relationship(
        'AutoRepairShopContract',
        primaryjoin='Agreement.agreement_id == AutoRepairShopContract.agreement_id',
        back_populates='agreement'
    )
 
    staffing_agreement = relationship(
        'StaffingAgreement',
        primaryjoin='Agreement.agreement_id == StaffingAgreement.agreement_id',
        back_populates='staffing_agreement'
    )
 
    product = relationship(
        'Product',
        primaryjoin='Agreement.product_id == Product.product_id',
        back_populates='agreement'
    )
 
    agreement_assessment = relationship(
        'AgreementAssessment',
        primaryjoin='Agreement.agreement_id == AgreementAssessment.agreement_id',
        back_populates='agreement'
    )
 
    def __repr__(self):
        return "<Agreement(" \
               "agreement_type_code='%s', " \
               "agreement_name='%s', " \
               "agreement_original_inception_date='%s', " \
               "product_identifier='%s', " \
               ")>" % (
                   self.agreement_type_code,
                   self.agreement_name,
                   self.agreement_original_inception_date,
                   self.product_identifier
                )
 
 
class AgreementPartyRole(Base):
    __tablename__ = 'agreement_party_role'
 
    agreement_party_role_id = Column(
        Integer,
        primary_key=True
    )
 
    agreement_id = Column(
        Integer,
        ForeignKey('agreement.agreement_id')
    )
 
    party_role_code = Column(
        String,
        ForeignKey('party_role.party_role_code')
    )
 
    effective_date = Column(Date)
 
    party_id = Column(
        Integer,
        ForeignKey('party.party_id')
    )
 
    expiration_date = Column(Date)
 
    agreement = relationship(
        'Agreement',
        primaryjoin='AgreementPartyRole.agreement_id == Agreement.agreement_id',
        back_populates='agreement_party_role'
    )
 
    party_role = relationship(
        'PartyRole',
        primaryjoin='AgreementPartyRole.party_role_code == PartyRole.party_role_code',
        back_populates='agreement_party_role'
    )
 
    party = relationship(
        'Party',
        primaryjoin='AgreementPartyRole.party_id == Party.party_id',
        back_populates='agreement_party_role'
    )
 
    def __repr__(self):
        return "<AgreementPartyRole(" \
               "agreement_id='%s', " \
               "party_role_code='%s', " \
               "effective_date='%s', " \
               "party_id='%s', " \
               "expiration_date='%s', " \
               ")>" % (
                   self.agreement_id,
                   self.party_role_code,
                   self.effective_date,
                   self.party_id,
                   self.expiration_date
                )

I have taken a few liberties in my own implementation, such as creating surrogate keys whenever I came across a composite identifier, which should make joining easier. I’ve also chosen my own data types for ambiguous fields (such as integers for identifiers and strings for descriptions) based on my own interpretation, and chose to represent superclass/subclass relationships by making one table for each superclass and subclass, which can be joined with primary/foreign key relationships.

Installation and Deployment

To use PCDM, you need to install SQLAlchemy if you don’t already have it:

Shell
1
pip3 install sqlalchemy

You can install and deploy PCDM by cloning the repo from my GitHub. The deployment script is displayed below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import sqlalchemy as sa
 
from sqlalchemy.orm import sessionmaker
 
from pcdm.base import Base
 
from pcdm import (
    party,
    account,
    policy,
    claim,
    assessment,
    agreementrole,
    claimrole,
    staffing,
    partyst,
    insurable,
    money,
    event,
    product)
 
engine = sa.create_engine(
            'sqlite:///pcdm.db',
            echo=True
        )
session = sessionmaker(bind=engine)
Base.metadata.create_all(engine)

You can either run this script, or use the terminal to clone and then deploy:

Shell
1
2
3
git clone https://github.com/genedan/PCDM
cd PCDM
python3 deploy_sqlite.py

If the deployment succeeds, you should see a SQLite database appear with 256 tables in it:

Although SQLite is the default, you can use this repo to make your own deployments for other RDBMSs (Postgres, SQL Sever, etc.). I have not made these ports yet, but I’m assumming if you have read this far, you’re a technically savvy person who can help me out by writing your own.

Documentation

I am working on making my own documentation, which is not yet available. But for now you can refer to the official OMG PCDM document.

Bugs

Warning – this repo is open source, and hence contains no warranty and may contain bugs. You can help contribute to the effort by making an issue or pull request should you encounter a bug.

Posted in: Actuarial / Tagged: database, insurance, object management group, PCDM, property casualty data model

Post Navigation

« Previous 1 2 3 4 Next »

Archives

  • September 2023
  • February 2023
  • January 2023
  • October 2022
  • March 2022
  • February 2022
  • December 2021
  • July 2020
  • June 2020
  • May 2020
  • May 2019
  • April 2019
  • November 2018
  • September 2018
  • August 2018
  • December 2017
  • July 2017
  • March 2017
  • November 2016
  • December 2014
  • November 2014
  • October 2014
  • August 2014
  • July 2014
  • June 2014
  • February 2014
  • December 2013
  • October 2013
  • August 2013
  • July 2013
  • June 2013
  • March 2013
  • January 2013
  • November 2012
  • October 2012
  • September 2012
  • August 2012
  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • January 2011
  • December 2010
  • October 2010
  • September 2010
  • August 2010
  • June 2010
  • May 2010
  • April 2010
  • March 2010
  • September 2009
  • August 2009
  • May 2009
  • December 2008

Categories

  • Actuarial
  • Cycling
  • Logs
  • Mathematics
  • MIES
  • Music
  • Uncategorized

Links

Cyclingnews
Jason Lee
Knitted Together
Megan Turley
Shama Cycles
Shama Cycles Blog
South Central Collegiate Cycling Conference
Texas Bicycle Racing Association
Texbiker.net
Tiffany Chan
USA Cycling
VeloNews

Texas Cycling

Cameron Lindsay
Jacob Dodson
Ken Day
Texas Cycling
Texas Cycling Blog
Whitney Schultz
© Copyright 2025 - Gene Dan's Blog
Infinity Theme by DesignCoral / WordPress