# Rating Engine

## Basic Concept

The logic behind insurance calculations can be highly complex. Therefore, it is essential to configure the calculation in a fast and flexible manner to keep the system up to date to meet changing business requirements.

The rating engine can configure not only the logic behind product premium calculations but also other common logics such as tax and fee calculations.

## User Scenario

For anyone who wants to use our platform to configure the calculation logic.  

## Important Notes[](https://docs.insuremo.com/common/doc_00000053#basic-rating-component-and-ui-operation "Link for Important Notes")

- **Master Configuration (MC) Environment**: All rating configuration (Topics, Nodes, Versions) must be performed in the MC portal. Direct changes in runtime environments are prohibited except for extreme troubleshooting.
- **Permissions**: Ensure your role has both "Read" and "Write" authority for the Rating module.

-   **Environment Discipline**: All operations mentioned in documentation should be performed in the **Master Configuration (MC) environment**. Do not attempt to configure logic in other environments as it will be overwritten during the next deployment.
-   **No Circular References**: It is forbidden to set rules that circularly call themselves or create infinite dependency loops in the calculation sequence.
-   **Performance Considerations**: 
    - Disabling **Rating Tracking** in production can significantly improve API response times.
    - Large rate tables should be partitioned or managed as V2 iTables for optimal performance.
-   **Versioning Accuracy**: Always double-check the "Version Date Field" (e.g., `Policy().EffectiveDate.val`) as this determines which version of the rating logic is executed for a given policy transaction.

## Calculation Structure Analysis

Understanding a basic calculation formula is easy. However, it is not enough to grasp the complexity of insurance calculations as a whole.

Before delving into the use of the rating engine, we must understand some basic concepts about the structure of complex calculations.

#### Comparison between Rule and Rating

The configuration of premium calculations is similar to rule configuration. They both adopt the same script configuration specifications and technical mechanisms. 

One characteristic of business rules is that they are executed one by one. For example, if the rule engine has 100 rules, these 100 rules are executed separately. 

In some special cases, these rules can also have defined execution sequences, but only on a small scale between certain rules, not all of them.

The calculation sequence of rating execution is more complex compared to rule execution. After the first step is completed, the second step can be started. The calculation sequence plays an important role in the rating analysis process.

So, to understand the rating engine, we must first understand these sequences. The rating engine is an enhanced offering compared to the rule engine because it pays special attention to the computation sequence. 

#### Calculation Type

If we divide the types of calculations, especially from a General Insurance (GI) business perspective, there would be two types of rating:

1. Product Rating

Calculation logic that varies from product to product:

* Product Premium Calculation
* Sum Insured Calculation

Such rating configurations are usually scalable, meaning multiple people can configure them at the same time, and the impact will be limited to a specific product only.


2. Common Rating

Calculation logic that is standard across multiple products and common for one tenant:

* POI Rate/Short Rate Calculation
* Installment Calculation
* Tax Calculation
* Fee Calculation
* Commission Calculation
* Endorsement Type Calculation

We would suggest that only limited and senior people touch the common rating part for one tenant implementation because any change to this part will impact all the products. Additionally, many system functions are related to common rating, such as BCP fee integration and regulatory reports.


#### Calculation Fields

Based on the calculation logic and business statistical needs of different companies, different stages of premiums have different structural relationships.

Taking into account the needs for different business statistics and actuarial models of insurers, we divided the entire premium calculation into several key rating fields based on our previous experience. 

In essence, when calculating premiums, the calculation fields or terms are not limited to the final premiums that the customer is going to pay but also include a large number of intermediate premiums in the entire calculation process. The premium calculation will calculate all the intermediate premiums to obtain the final premium. 

Some of the most important premium fields are predefined by the system, as shown in the diagram below. 

The most common premium calculation models include the basic premium rate, annual premium, gross premium (premium with short-term rate adjustments), and adjusted premium (premium with discounts or manual adjustments). The final data provided to the client for the premium calculation is the due premium.

In addition, if an endorsement is involved, delta gross premium and delta due premium are calculated, in addition to the basic fields applicable to new business.

| Category | Field Name | Remark |Other Possible Naming|
| ------ | ------ | ------ | ------ |
| New Business | SumInsured | Sum insured. |-|
| New Business | PremiumRate | Summary of basic rate for premium. |-|
| New Business | AnnualPremium | Pure formula premium on annual basis.|Technical Premium, Standard Premium.|
| New Business | GrossPremium | Annual premium after policy term adjustment. |-|
| New Business | AdjustedPremium | Premium after manual adjustment. |-|
| New Business | DuePremium | Premium payable to policyholders. |Final Premium, Payable Premium.|
| Endorsement | GrossPremiumDelta | Gross premium delta between this endorsement version and the previous version. |-|
| Endorsement | DuePremiumDelta | Due premium delta between this endorsement version and the previous version. |-|

#### Calculation Structure and Sequence

A complex calculation might involve multiple steps, which are calculated under a series of predefined sequences. The calculation sequence can also be visualized as a calculation structure in a tree format.

The main structure of the premium calculation is a vertical structure, which needs to consider the case of group insurance, namely, an insurance policy with the insured and multiple coverages. Once we have this situation, the premium calculation must be set in a hierarchical way for each item.

Coverage/Benefit is always the smallest unit of the calculation structure we recommend. (Of course, the rating engine itself can also support calculations that do not start with coverage, e.g., from clauses, depending on the nature of the specific business requirements.)

We need to gradually accumulate the rise in premiums from coverage to risk, then to product, and finally to policy. 

In some special cases, if there is a manual adjustment at the upper level, such as manually assigning one fixed policy-level premium, then the difference between the manual adjustment and the system calculation needs to be allocated back to the bottom level.

With this structural arrangement where each level has its own calculation results, it is not only possible to cope with the most complex actuarial models but also highly beneficial for follow-up business statistics. For example, understanding the breakdown of sales volume for each coverage and risk.

![Calculation Structure](./image/rating/rating_premium_structure.png) 

#### Calculation Field and Calculation Structure

Premium fields exist at the level of most premium structures. Starting from the bottom level, certain calculation methods are used to complete the bottom premium calculation, and their final and intermediate results can be accumulated under the same field names at the upper level.

![Calculation Field and Structure](./image/rating/rating_structure_and_field.png) 

#### Calculation Structure and Policy Structure

In general, the premium structure and policy structure are closely intertwined. In fact, the policy structure is primarily designed by taking inspiration from two sources: the information input and the premium structure, which is very important in determining the policy structure.

In terms of system design, each business model in the policy structure is reserved with premium-related fields to store the split and accumulated premium values.

![Calculation and Policy Structure](./image/rating/rating_premium_policy_structure.png) 

#### Sample Calculation Scenario for the Study

Suppose there is a quotation request for a personal accident product. In the request, the accidental death coverage needs to be calculated. 

Quotation for Personal Accident Product (insurance period: 2019/1/1 to 2019/12/31)

* Sum Insured at Coverage = 100,000
* Premium Rate at Coverage = 0.01
* Annual Premium at Coverage = 1000
* Gross Premium at Coverage/Risk/Policy = 1000
* Adjusted Premium at Policy = 1000
* Due Premium at Coverage/Risk/Policy = 1000

To analyze the calculation, we need to assess the following aspects:

* Determine Which Level to Start with 

Typically, we would recommend starting with the level of coverage. There may be special cases where the client has a more complex rating that involves a more detailed level of calculation.

* Detailed Calculation Algorithm 

The algorithm always has field terms as representatives. There will be standard formulas to calculate each term and return the premium value for all terms.

* How to Interact with Other Levels

This is a somewhat difficult issue. In some clients’ requirements, the breakdown of the calculation for all levels may not be specified. So we need to think more and analyze more deeply. It is possible to have a simple and straightforward cumulative rise. Sometimes there may be more complex situations, for example, involving minimum premiums, manual adjustments, etc.

## Composition of Rating Engine

The rating engine is highly configurable and scriptable to provide flexibility in implementing diverse business calculation logic.

### Rating Engine Concept

To understand the construction of the rating engine, it is necessary to grasp several key concepts:

* Calculation Group 

Calculation groups allow for better management and searching of different types of calculations. For instance, each product calculations can be defined in separate groups, or some common calculations can be defined in another group. Calculation groups are typically defined at the domain level.

* Calculation Topic

A calculation topic is a group of rating nodes that collectively define a calculation domain. It serves as a high-level interface that encompasses multiple calculations within a specific category.

* Calculation Node and Script

Within each calculation group, there are multiple calculation nodes, each containing a formula that executes detailed calculation logic. Calculation node is the unit that contains scripts for executing ratings. Each calculation node involves one calculation script, which is written in the Groovy + DSL format, similar to the rule configuration.

For more detailed information on the script, see [DSL Guide](https://docs.insuremo.com/common/doc_00000019)

Once the calculation is completed, the result can be returned to the corresponding premium field and set to cumulatively increase based on the configuration.

* Calculation Sequence 

A calculation sequence is defined between different calculation groups or calculation nodes. The sequence is maintained in the form of a tree structure, which represents the calculation order. The calculations are performed step by step, starting from the lowest level of the tree structure and moving up to the highest level. The lowest-level formulas are calculated first, followed by the higher-level formulas.

Essentially, the entire rating logic is organized, starting from the system entry point. First, the product premiums are calculated, followed by the public premiums and sum insured. This logic is applied to all products.

Having a strong understanding of how these sequences are maintained is crucial for rating configuration itself. As the calculation sequence might become too complex to manage through the user interface alone, the system also allows defining the sequence in a mindmap and importing it into the system.

### Rate Table

In certain calculation formulas, it is necessary to query pre-defined rate tables to obtain premium rates.

The system currently incorporates a configuration table engine, which offers the freedom to set up various configuration tables in a flexible manner, tailored to different businesses. 

Rate table is one of the most typical tables. In property insurance, rate tables relate to product actuarial models, including short-term rate tables, occupational class coefficient tables, or regional coefficient tables.

For more detailed information on rate tables, see [Configuration Table Guide](https://docs.insuremo.com/common/doc_00000045).

### Rating Debugging and Rating Tracking

After the rating is configured, it is crucial to call relevant APIs to test and debug the calculations. 

Specific calculation-related APIs exist within each business domain to perform the entire business calculations for all linked groups, or partial calculations for a specific group. 

Upon successful calculation, the API’s return body will reflect the calculation results, including premiums and sum insured, through the premium fields associated with each policy level. In case of a failed call, the system will return an error message in the response body.

Additionally, a rating tracking tool is provided to facilitate quick locating the root cause in case of incorrect calculation results. All calculation executions are recorded, which aids in the debugging process.



## Basic Rating Component and UI Operation

<div class="docs-caution"><span class="docs-admonitions-text">caution</span>

*  All operations mentioned in this article should be performed in the portal master configuration environment (MC env). They are not allowed in other environments unless for troubleshooting purposes.
*  Ensure that you have the necessary read and write authority before proceeding with the operations.

</div> 


### UI Operation

The online UI provides a convenient way to perform all rating configurations. Simply navigate to the **Rule & Rating > Rating Formula** menu.

#### Calculation Topic

  ![Add Calculation](./image/rating/add_context_001.png)
  
#### Calculation Topic Version

Multiple versions of a calculation topic can be created.

![Calculation Node Definition](./image/rating/add_rating_node.png)  
  

#### Calculation Node and Script

  ![Calculation Node & Script](./image/rating/mm_node_formula_001.png) 

Calculation Node:

* Represents all calculation steps for a specific rating field.
* Each calculation step is treated as a node.

Calculation Node Script:

 * A calculation can be divided into multiple steps.
 * Each step must return a value to a specific rating field.

 ![Calculation Node Definition](./image/rating/add_rating_node.png)  

* **Name** and **Description**: self-defined.
* **Model Level**: Policy/PolicyLob/PolicyRisk/PolicyCoverage/PolicyBenefit.
  If the model is a schedule, just check the model in DD, such as Person, PersonStructure, and PolicyDriver.
* **Model Code**: ProductElementCode of the Object. If null, all the objects will execute the node.
  If there are more than one object, please separate them with a comma (,). Example: **Code1, Code2**.
* **Term**: Field in the Model used to store the value returned by the formula.
  The **Term** must be a field defined in DD under the model. 
* **Filter Condition**: The condition for the node to run. 
* **Dependency**:
  * **Call Calculation Group**: Depends on the selected group. All rating formulas with the same **Group** condition will be executed.
    * Claim Common
    * Coinsurance
    * Commission
    * Endorsement Rating
    * Endorsement Transaction Rating
    * Fee
    * New Business Transaction Rating
    * Others
    * Period of Insurance (POI) Rate
    * Product Premium Calculation
    * Product Transaction Rating
    * RI Allocation
    * Sum Insured
    * Tax
    * Trial Calculation
  * **Call Calculation**: Depends on Calculation Codes.
  * **Call Formula Script**: Depends on Steps (calculation nodes) within the current calculation code. 
  * **Called By**: Depends on, automatically updated if it is set as **Call Formula Script** in other nodes.
* **Accumulative** (Currently, only shows up when editing): If checked, the **Term** field’s value will be accumulated from the current level to the Policy level. Ensure that the field is correctly mapped to the relevant Model.

If any **Call Calculation Group** or **Call Calculation** is set for the current calculation formula, all linked groups or calculation formulas will be executed first before the nodes in the current calculation formula.


##### Example 1 - Calculation Return

* All coverages will execute the formula under this node.
* The returned value will be stored to the field-SumInsured of the PolicyCoverage.

![Example1](./image/rating/sample1.png)

##### Example 2 - Calculation Filter by Script

* Only coverage with ProductElementCode C101197 will execute the formula under this node.
* No term of the returned value is stored.
* Example 3 demonstrates the same effect.

![Example2](./image/rating/sample2.png)

##### Example 3 - Calculation Filter by Model

![Example2](./image/rating/sample3.png)

##### Example 4 - Separate If Else to Different Nodes

Here is the script we always use, especially in common rating. The ProductCode is used as assertion, and then the script line count will increase as more products are added.

```dsl
def prd = Policy().ProductCode.val
if(prd == "A"){
 //5 lines code for A
}
else if(prd == "B"){
 //15 lines code for B
}
else if(prd == "C"){
 //10 lines code for C
}
else if(prd == "xxx"){
 //.....
}
else {
 //10 lines code
}
```

A lengthy script can become difficult to maintain, so it is advisable to separate it into different nodes based on the If conditions.

![separate If Else to Different Nodes](./image/rating/rating_seperate_nodes.png)

You can find the mindmap for reference [PdRating_seperate_nodes](./image/rating/PdRating_seperate_nodes.mm).

In other cases, the script may look like the following:

```dsl
def prd = Policy().ProductCode.val
def exPrdList = ["A","B","C"]
if(prd in exPrdList){
  return
}else{
//common logic
}
```


#### Calculation Sequence 

##### Example 1 - Overall Sequence

In most cases, the calculation will start with the entrance (usually a new business transaction rating), where the product premium is calculated first, followed by the common premium calculation.

![Calculation Sequence Overall](./image/rating/rating_sequence_overall.png) 

##### Example 2 - Calculation Node Sequence (From Child Node to Top Node)

![Example2](./image/rating/mm_node_formula_example_004.png)

* SI ACC, which is the final node of its own node.
* PA and Vehicle, which are the final nodes of the VAT (VAT > Accumulation > PA / Vehicle).

In the rating logic execution sequence, the final nodes will be executed first, followed by the parent code.

Therefore, although both SI ACC and VAT are under the root node, the executed time will be different. The ideal execution sequence is: SI ACC, PA, and Vehicle. All of them are final nodes, so they will be executed first, followed by Accumulation > VAT.

The ideal true execute sequence is: from Child Node to Top Node.
1. Product Rating (PA, Vehicle) & SI ACC
2. ACC Premium
3. VAT

In the actual business scenarios, SI ACC must be executed after Product Rating, and we need to add dependencies to it so that it is executed after the execution of product rating.

##### Example 3 - Calculation Node Sequence (Depended on other Nodes)

![Example2](./image/rating/mm_node_formula_example_005.png)

Currently, it is IMD Discount.
* Executed after VehicleAge.
* Executed before OD_BaseRate.

The sequence is:
1. VehicleAge
2. IMD Discount
3. OD_BaseRate

#### Calculation Script

* One calculation can be divided into multiple steps.
* Each step is required to return to one rating field.
 
![Calculation Script](./image/rating/rating_script_typical.png) 


### MindMap Usage

For some complex rating logic, we also support uploading and downloading mindmaps for a large number of configuration updates if the user finds the UI operations too time-consuming.

![Calculation Mindmap](./image/rating/rating_mindmap_overall.png) 



### Rate Table

Related Formula DSL:

* lookupByName("ThirdPartyBasicPremium",["IsElectricVeh":iselec,"EngineCapacity":param.toLong()])
* lookup("PMCAR001_RateTable_103",["IsElectricVeh":iselec,"EngineCapacity":param.toLong()])

For more details, see [DSL](https://docs.insuremo.com/common/doc_00000019#rate-table--configuration-table).

For rate table definition, see [Parameter/Rate Table](https://docs.insuremo.com/common/doc_00000045).


### Rating DSL Helper

The system provides Rule Helper to quickly get commonly used information when creating/editing a rating formula. For detailed guidance, see [rule helper](https://docs.insuremo.com/common/doc_00000056#rule-helper1).

## Rating Versioning

Currently, we support multiple physical versions for the same rating calculation. Each calculation will have its own version and effective/expiry date. Also, all the rate tables invoked in the calculation will follow the same versioning logic as the rating script. 

The following are the steps on how to achieve such versioning:

1. Set "**Version Date Field**" or "**Release Date Field**" for the rating formula.
2. Set "**Start Date**""**End Date**" and "**Release Date**" for the version of the formula.

As shown in the image below, the system will use the policy’s EffectiveDate field for the rule active duration check.

* If the policy’s EffectiveDate field is between 1970-01-01 and 2022-01-11, the rating version 1 will be executed.
* If the policy’s EffectiveDate field is after 2022-01-11, the rating version 2 will not be executed.
* If we remove the "**Release Date Field**" from rating and the "**Release Date**" from the version, the rating version can be executed by comparing with the system time.

![rule group Eff Field](./image/rating/rating_formula_eff_field.png)


![rule POI](./image/rating/rating_version_poi.png)


## Rating Debugging and Rating Tracking
After the rating logic has been set up, we need to check whether it works as expected or not.

### Call API

We can call the API to validate it:
* API: `{{server}}/pa/v1/invokeRating?calculationCode=New Business Trans Rating`
* Request Data:

Example:

```json
{
    "BeforeVatPremium": 121.5,
    "BusinessCateCode": "1",
    "Commission": 6.075,
    "DuePremium": 130,
    "EffectiveDate": "2019-04-22",
    "ExpiryDate": "2019-04-24T23:59:59",
    "IsPremiumCalcSuccess": "Y",
    "PolicyCustomerList": [
        {
            "CustomerName": "Customer",
            "DateOfBirth": "1988-10-01",
            "IdNo": "IdNo",
            "IdType": "1",
            "IsInsured": "N",
            "IsOrgParty": "N",
            "IsPolicyHolder": "Y",
            "VersionSeq": 1
        }
    ],
    "PolicyLobList": [
        {
            "PolicyRiskList": [
                {
                    "CustomerName": "Customer",
                    "DateOfBirth": "1988-10-01",
                    "IdNo": "IdNo",
                    "IdType": "1",
                    "PolicyCoverageList": [
                        {
                            "DuePremium": 100,
                            "ProductElementCode": "C100416",
                            "SumInsured": 300000,
                            "VersionSeq": 1
                        },
                        {
                            "DuePremium": 10,
                            "ProductElementCode": "C100692",
                            "SumInsured": 300000,
                            "VersionSeq": 1
                        },
                        {
                            "DuePremium": 20,
                            "ProductElementCode": "C100715",
                            "SumInsured": 300000,
                            "VersionSeq": 1
                        }
                    ],
                    "ProductElementCode": "R10007",
                    "RiskName": "InsuredName",
                    "VersionSeq": 1
                }
            ],
            "ProductCode": "TBTI",
            "ProductElementCode": "TBTI",
            "ProductId": 351925022,
            "ProductLobId": 351925023,
            "TechProductCode": "TR_POC",
            "TechProductId": 3516410623456,
            "TotalInsuredCount": 1,
            "VersionSeq": 1
        }
    ],
    "PolicyType": "1",
    "ProductCode": "TBTI",
    "ProductId": 351925022,
    "ProductVersion": "1.0",
    "ProposalDate": "2019-04-22",
    "TechProductCode": "TR_POC",
    "TechProductId": 3516410623456,
    "Vat": 8.5,
    "VersionSeq": 1
}

```

### View Rating Tracking

1. Obtain the Trace ID in the Response Header.
 
    ![Traced](./image/rating/rating_debug_001.png)

2. Search by Trace ID in Rating Tracking.
  
 The tracking records are:
 
  a.  The top node is the first executed node.<br/>
  b.  The bottom node is the last executed node.
  
  ![rating tracking](./image/rating/rating_debug_002.png)

  ![rating tracking](./image/rating/rating_debug_003.png)

The different colors of the formula represent the following:
* Grey: Not Executed.
* Green: Successfully executed.
* Red: Failed.


### Tracking Log Performance and Housekeeping

Currently, our tracking log is enabled by default in all environments, including production, to facilitate the development team in the troubleshooting process. To balance the performance of the production system, line numbers are not displayed, and tracking is captured asynchronously.

Since the tracking log is comprehensive and includes every aspect of rating execution, the log table (`t_rt_tracking`) can become very large if too many rating calculations are triggered. Therefore, regular cleanup is required.

As part of the platform's default settings, we have implemented a “ratingTrackingDeleteExpiredDataJob” batch that runs every night to clean up logs that were created more than 90 days ago. If the number of records increases too quickly, users can go to the batch module and manually run cleanup with a closer date range.

Please pay special attention that if your client is very performance demanding, you can ask insureMO support team to disable the tracking entirely.


![rating tracking clear](./image/rating/rating_tracking_clear.png)



### Rating Tracking Configcenter Parameter (Private Cloud Only)

By default, in all environments, when debugging rating logic, it is necessary to check the rating logic details, and then use the rating tracking function.

However, in certain environments, such as private clouds, it may be desirable to disable tracking for better performance.

Users can go to the config-server on the platform and check the following configuration items (if the configuration items do not exist, they will take the default values):

1. Rating.tracking.flag
* True-enable (default)
* False-disable
       
2. Dsl.tracking.flag
* True-enable (default)
* False-disable 
       
3. Rating.tracking.async
* True-async (default for production)
* False-sync (default for non-production)
       
4. Dsl.tracking.lineNumber.flag
* True-display (default for non-production)
* False-not display (default for production)


### Rating Performance Analysis

The performance of the rating API is influenced by multiple factors, including:

* Complexity of the rating logic -> less complex rating will lead to better performance.
* Size of the testing script -> less number of insureds will lead to better performance.
* Allocation of system resources -> better infra setup will have better performance.
* Utilization of system resources at the time -> less system load will have better performance e.g. any performance testing or system restart.
* Frequency of API calls -> more frequent API calls will result in better performance, while activities like troubleshooting will lead to regular cache clean-up, and lower daily usage will result in poorer performance due to the daily expiration time of our cache.
* Status of rating tracking, synchronous write, and line number display -> disabling these features will significantly improve speed.

To improve rating performance, you can take the following steps:

1.	Call the API more frequently, avoiding reach the load testing levels, and not perform during the system maintenance window.
2.	Contact the platform team to disable rating tracking line number display.
3.	Contact the platform team to disable rating tracking.
4.	Contact the platform team to set up a tenant in the runtime environment, ensuring isolated usage and an expanded infrastructure capacity.
5.	Optimize the API testing script to reduce the number of risks/coverages and run each risk as a separate thread.
6.	Optimize the rating logic to minimize iterations or large rate table loading.

If you have a high-performance scenario, please don’t hesitate to contact the insureMO support team for assistance.


## Standalone Rating Engine Mode

Normally, if users choose insureMO, there will be rating API exposed from respective business domains e.g. `/quotation/v1/quotation` or `/proposal/v1/calculate`. 
This again means the data model must follow existing insureMO GI business model and users can only extend the model but cannot make fundamental model changes. Additionally, it is mandatory to configure products in the product factory before calling these business APIs.

However, there are cases where clients have existing systems with data models different from the insureMO default business model, but they want to use our rating engine for premium calculation. This mode is called standalone rating mode and is separate from the proposal or quotation business service that contains the rating capabilities.

In standalone rating mode, unlike business service rating that must start from product configuration, the development team needs to:

*  Create new configuration groups for DD, code table, data table, rate table, and rating formula.

*  Register new DD as per requirements (DD only and does not involve product configuration).

*  Create rating formulas and bind them to the common context.

*  Configure filter conditions in the rating formulas to match different scenarios.

And in rating API call (`{{server}}/platform-busi-config/rating/runtime/v1/calculate?ratingCode=2001`), the ratingCode parameter drives the rating formula entrance.




## Appendix A: Recommended Calculation Topic and Calculation Classification (GI Business)

Here are some examples of the most common rating topics that we can support by using the rating engine. 

### NB Transaction Rating

New business transaction rating serves as the super node for all new business-related calculations. It acts as a comprehensive interface for the new business calculation API, encompassing all other calculation nodes.

![NB Trans](./image/rating/nb_trans.png)

As more products are added, there may be cases where the common rating logic is not applicable to certain products. In such scenarios, the filter condition becomes longer and longer. For example,**"Policy().Product.cal in ["AAAA1","AAAA2","AAAA2","AAAA...","AAAAn"]"**. In some tenants, the filter condition exceeds the limit of **256** alpha characters.

To address this, we recommend moving the common logic to each product rating. For more details, see [product rating example 3](#example-3).

![NB Trans Rating Structure Example](./image/rating/nb_trans_001_simple.png)


### Endorsement Transaction Rating 

Endorsement transaction rating serves as the super node for all endorsement-related calculations. It acts as a comprehensive interface for the endorsement calculation API, encompassing all other calculation nodes.

![Endo Trans](./image/rating/endo_trans.png)

### Premium Structure

The premium structure is defined as a series of sequences and terms that determine the rating calculation. It helps determine the final premium payable in a logical manner and includes various breakdowns of premium fields that aid in generating business statistics and reports.

#### Key SumInsured and Premium Terms

| Field Name | Description | Remark |
| ------ | ------ | ------ |
| SumInsured | Sum Insured. | - |
| PremiumRate | Premium Rate. | - |
| AnnualPremium | Annual Premium. | - |
| GrossPremium | Gross Premium. | - |
| BeforeVatPremium | Premium before tax. | - |
| Vat | VAT or Total Tax Amount. | - |
| DuePremium | Real Premium or total payable premium.| - |
| AdjustedPremium | Adjusted Premium after manual adjustment. | - |
| EndoAdjustedPremium |Endorsement Adjusted Premium after manual adjustment. | - |
| SumInsuredDelta | Delta SumInsured. | Temporary Field, Stored in Policy then EndoDiff. |
| AnnualPremiumDelta | Delta AnnualPremium. | Temporary Field, Stored in Policy then EndoDiff. |
| GrossPremiumDelta | Delta GrossPremium. | Temporary Field, Stored in Policy then EndoDiff. |
| BeforeVatPremiumDelta | Delta BeforeVatPremium. | Temporary Field, Stored in Policy then EndoDiff. |
| VatDelta | Delta VAT. | Temporary Field, Stored in Policy then EndoDiff. |
| DuePremiumDelta. | Delta DuePremium. | Temporary Field, Stored in Policy then EndoDiff. |
| AdjustedPremiumDelta | Delta AdjustedPremium. | Temporary Field, Stored in Policy then EndoDiff. |

The system will keep the default precision of 2 digits.

#### Sample New Business Rating Logic Analysis

Different companies and countries will have different methods for determining premiums. The following example explains how premiums are calculated for an insurer at each level.

##### Product Rating Logic 

<div class="docs-note"><span class="docs-admonitions-text">note</span>

 This section of the algorithm will vary depending on the product.

</div>
* AnnualPremium -- This is pure actuarial premium regardless of the policy POI. 
  * `AnnualPremium = SumInsured * PremiumRate` -- Usually Annual Premium will be determined by Sum Insured with a series of Premium Rate multiplier.

* GrossPremium -- This is the premium with POI rate either by standard POI rate or short rate.
  * `GrossPremium = AnnualPremium * ShortPeriodRate` -- Period Rate can have different algorithm depending on the length of time.

##### Common Rating Logic -- Coverage Level

<div class="docs-note"><span class="docs-admonitions-text">note</span>

This section of the algorithm is generally consistent across all product lines.

</div>

* AdjustedPremium -- This is the premium either input by underwriter for manual adjustment or due to some common adjustment factor.

* BeforeVatPremium -- This is to take either adjusted premium or gross premium with some automatic adjustment factor like discount or loading.
  * `AdjustedPremium or GrossPremium * DiscountRate * LoadingRate`

* Vat -- Tax is an important part to get the final premium. VAT is the most common tax type across the world and thus the term is being used to represent the tax.
  * `Vat = BeforeVatPremium * VatRate` - Usually, tax will have a percentage applied to the premium itself.

* DuePremium -- This is super important to represent the final premium customer is going to pay. 
  * `DuePremium = BeforeVatPremium + Vat (Tax/GST,etc)` -- Usually, payable premium will involve premium and tax two parts.

* Commission -- This is to represent the commission amount which needs to be paid to intermediaries. 
  * `Commission = BeforeVatPremium * CommissionRate` -- Usually, commission will be calculated on a non-tax basis.


#### Sample Endorsement Rating Logic Analysis

##### Cancellation and POI Change
1. Calculate the ShortRate(EndoShortRate)
2. Endo Delta Premium
   - ` ΔGrossPremium = GrossPremium(OldPolicy)* EndoShortRate`

##### Basic Information Endorsement (BIE)
1. Call NB Transaction to calculate the NewPolicy premiums.
    - `AnnualPremium(NewPolicy)=SumInsured(NewPolicy)* PremiumRate(NewPolicy)`
    - `GrossPremium(NewPolicy)= AnnualPremium(NewPolicy)* ShortPeriodRate(NewPolicy)`

2. Calculate the ShortRate(EndoShortRate)
3. Endo Delta Premium
   - `ΔGrossPremium = (GrossPremium(NewPolicy)- GrossPremium(OldPolicy))* EndoShortRate`

##### Common Rating Logic

* Endo Delta SumInsured
   - `ΔSumInsured=SumInsured(NewPolicy)- SumInsured(OldPolicy)`

* EndoAdjustedPremium
   - `EndoAdjustedPremium=ΔGrossPremium`
    EndoAdjustedPremium can be manually adjusted. If adjusted, the following premiums need to be re-calculated.

* VatDelta
   - `ΔVat= ΔEndoAdjustedPremium *VatRate`

* BeforeVatPremiumDelta
   - `ΔBeforeVatPremium= EndoAdjustedPremium -ΔVat`

* DuePremiumDelta
  - `ΔDuePremium=ΔVat+ ΔBeforeVatPremium`

### Accumulation and Allocation

Since our policies are in a layered tree structure, it is fundamental to compute the policy amount for the upper layers based on the amount of coverage in the bottom layer.

A basic principle is that all premiums for a Policy/PolicyLob/PolicyRisk/PolicyClause/Form need be computed from the bottom up and that the premiums for the top tier should equal the sum of the premiums for the bottom tier in order to have a statistical result at all levels.

Typically, the calculation starts from the bottom level, and the appropriate fields are selected to accumulate upwards.

In some cases, if any top-level calculation is manually adjusted, the adjusted value also needs to be assigned back to the bottom layer. For example, if the policy-level premium is adjusted, the following steps should be followed:

*	Store the adjusted premium amountAdjustedPremium in policy level.
*	Proportionally update the AdjustedPremium for each level under the target level, e.g. lob, risk, coverage level.
*	If there are rounding issues after the proportional divide, put the difference in the 1st coverage to keep the sum of the updated AdjustedPremium correct.
*	Recalculate Vat/DuePremium/BeforeVat after the AdjustedPremium is updated at the bottom level.
*	Reaccumulate the sum of Vat/DuePremium/BeforeVat after the AdjustedPremium is updated.
*	The same set of logic also applies to endorsement calculation.

### Multi-Currency

When dealing with multiple currencies, in addition to the basic calculation, we need to define the following:

* Currency-related information, such as PremiumCurrencyCode, SiCurrencyCode, BookCurrencyCode, and LocalCurrencyCode.
* Calculation results in local and foreign currency, such as DuePremium/DuePremiumLocal, GrossPremium/GrossPremiumLocal and SumInsured/SumInsuredLocal.

### Rounding Accuracy

* Each field of premiums or rates or middle values is always required to a specific accuracy. Then we need round in the rating logic.
* Without rounding, values may vary in different environments.
* It is recommended to increase the accuracy of intermediate values to ensure accurate rounding.

