Data Warehousing, BI and Data Science

11 September 2020

Copy Paste Anchor Links (Page Jumps) from Microsoft Word to WordPress

Filed under: Data Warehousing — Vincent Rainardi @ 6:57 am

Problem: when copy-pasting a Word document to WordPress, hyperlinks are preserved but bookmarks are gone.


  1. In Microsoft Word create them as hyperlinks
  2. Paste it to WordPress
  3. Change the hyperlinks to anchor links using Notepad
  4. Paste back to WordPress

Step by step:

Step 1. In Microsoft Word, create them as hyperlinks

  • In a blank Microsoft Word document, create this:

Both of the “Section 1” are normal hypelinks, with text = “Section1” (no space), address = “#section1” (no space with # prefix) like this:

  • Highlight it, control-K (Insert Hyperlink), type Address = #Section 1 (notice the hash in the front).
  • Create Section 2 and Section 3 the same way.

Step 2. Copy to WordPress

  • Control-A (select all)
  • Copy paste to WordPress visual editor.

Step 3. Replace the hyperlinks to anchor links in Notepad

  • Control-Shift-Alt-M (switch to Code Editor)
  • Control-A (select all)
  • Paste to Notepad (Notepad++ is better)
  • Control-H (replace), replace href with name, and remove the # as follows:
    find what: <a href=”#, replace with: <a name=”

Step 4. Paste back to WordPress

  • Control-A and paste back to WordPress code editor.
  • Click Update on the top right corner
  • View the page and test the hyperlink

10 September 2020


Filed under: Data Warehousing — Vincent Rainardi @ 5:07 am

My son asked me to show graphics in programming and I thought it would be a good idea to show Turtle. In Python of course, as it is the most popular programming language, serving all kinds of communities not just AI. Turtle is a simple way to draw lines and circles. And it’s already built in Python, i.e. you don’t need to install anything.

To start with just type “import turtle”. This is to import the turtle library into python environment.

Then type “t = turtle.Turtle()”. This is to create a variable t so that we don’t have to type turtle.Turtle many many times. It opens a window like this with an arrow facing to the right. That arrow is the cursor. That window is our canvas, where we make our drawing.

To draw a line, type “t.forward(50)”. This is to move the arrow 50 pixel forward (to the right).

To change the same of the cursor, type “t.shape(“turtle”)”:

To draw a circle, type “”:

To turn the turtle to the right 90 degrees, type “t.right(90)”:

And you can do “t.forward(50)” to draw a line again:

To lift the pen up so it won’t make any line, type “t.penup()”. Now we can move the turtle without drawing anything, for example: “t.setposition(0,-50)” like this:

(0,0) is where we began. It’s x,y so 0,-50 means the x is 0 and the y is -50 (50 down).

50,0 means x = 50 and y = 0, like below:

Remember that our pen is still up at the moment. To start drawing again, let’s put the pen down by typing “t.pendown()”. We can draw a circle again: “”, like below left:

To undo what we did last, type “t.undo()”, like above right.

To fill with colour, type this:

  • t.fillcolor(“green”)
  • t.begin_fill()
  • t.end_fill()

And finally, to clear the screen, type: “t.clear()”.

As an example, to make a square, it is like below. We use a “for” loop.

for _ in range(4): {shift-enter}
  t.forward(25) {shift-enter}
  t.right(90) {enter 2x}

Another example: a filled hexagon.

t.fillcolor("green") {enter}
for _ in range(6): {shift-enter}
   t.forward(25) {shift-enter}
   t.right(60) {enter 2x}

Have fun!

6 September 2020

Dynamic Difference in Power BI

Filed under: Data Warehousing — Vincent Rainardi @ 3:30 pm

If you are looking for how to do dynamic difference (dynamic delta) in Power BI, you’ve come to the right place. This article is about showing how to calculate the difference (say between actual and budget) dynamically or on-the-fly as you switch from product to product. This is done using the SelectedValue function.

Business Scenario

Here is the business scenario: you work in product development in a manufacturing company. You have many products developed in your product development pipeline, each have different costs for each component like this:

Report Layout

The Power BI report should look like this:

You need to be able to select a product (Product A in the above example) and the actual spend vs budget are displayed in a table, along with the difference.

So you are comparing the cost breakdown of a product to the budget. Another business scenario which is similar to this is comparing the performance attribution of a mutual fund to the benchmark. In this case instead of components, we have industry sectors.

Dynamic Difference

The point here is that the differences are calculated on-the-fly, depending on the user selection. That is the key Power BI functionality that I’d like to show you.

There is a function in Power BI called SELECTEDVALUE, which we need to use for this. We use it to find out which product is being selected.

How To Do It

So let’s create the Power BI report.

Step 1. First, in Excel, type this table, and load it in Power BI as Cost table:

Step 2. Create a calculated table to select distinct values from the Product column:

   Product = distinct(‘Cost'[Product])

Step 3. Use it for a slicer so we can select Product A, B and C (filter the Budget out):

Step 4. Create 3 measures: Cost_Budget, Cost_Actual and Cost_Differene as follows:

1. Cost for the budget:
Cost_Budget =
( SUM(‘Cost'[Cost]),
  FILTER(‘Cost’, ‘Cost'[Product] = “Budget”)

2. Cost for the selected product:
Cost_Actual =
( SUM(‘Cost'[Cost]),
  FILTER(‘Cost’, ‘Cost'[Product] = SELECTEDVALUE(Product[Product]))

3. The difference between the budget and actual:
Cost_Difference = [Cost_Budget] – [Cost_Actual]

Step 4. On the report create a table with Component, Budget, Product and Difference in the Values.

Now when we select Product A it will display the cost of Product A and calculate the difference on-the-fly.
And when we select Product B it will display the cost of Product B and calculate the difference on-the-fly.

26 September 2019

Development Operations (DevOps)

Filed under: Data Warehousing — Vincent Rainardi @ 5:45 pm

Whether you are building a data warehouse, a client reporting system, a MDM system or a trade booking system you need to run a development team. Development Operations are things that you need to run a software development team. What do you need to run a development team? They are:
1. Release pipeline
2. Change control
3. Sprint planning
4. Automated testing
5. Code repository
6. Server build

In writing this article I will try to combine all my experiences from about 10 companies in the last 12 years. Some of them do best practices, some do bad practices. I will only write about the good ones here.

1. Release Pipeline

The first thing that you need as a development team is a release pipeline. A release pipeline is a process to automatically build, deploy and test the code to a series of environments, i.e. development, test, UAT, production and support. A release is a collection of code such as stored procedures, SSIS packages, .Net code, views, tables, etc. bundled into 1 package to be deployed together as 1 unit.

Can’t you deploy it manually by copying the code? Of course you can. But it will take more effort. And it is prone to error. What if you want to rollback to previous version? Well you have to do it manually right, by copying the previous version of each component. Who is keeping track of the version for each component? What if you missed 1 component? You could be deploying 50 components in test but only 49 in production. It’s a headache right? With a release pipeline, you can deploy all components into many environments consistently and effortlessly. You deploy into Test environment, and test it here. You deploy into UAT environment, and test it here. And you deploy the same thing into Production. And then you deploy the same thing into Support environment. The environments are guaranteed to be consistent.

If you have 100 stored procedures, 100 tables, 100 views, 100 SSIS packages, a view SSAS cubes, 50 SSRS reports and hundreds of .Net codes, then you will appreciate the benefit of having an automated release pipeline. It is a huge time saver. And it improves your quality.

Deployment into an environment requires approvals. A deployment into the test environment for example, may require the test manager approval. Whereas to deploy a release into production requires an approval from the production support manager.

2. Change Control

The second thing that you need to run a development team is change control. Change control is a process of approving every single change going into production environment. It can be a code change (like a release). It can be a data change (like an UPDATE or DELETE statement). It can be a configuration change (like moving the data folder from C drive to E drive). It can be an infrastructure change (like setting up a new SQL server).

Change control is very important because:
– It shows that the change has been tested properly in Test environment, before it is deployed to production.
– It shows that the development manager and the production support manager are aware about the change.
– When the company is audited you have evidence that every single change in production is approved and tested.
– You can choose which change will be deployed at the same time in production, and which ones are not at the same time to minimise the risk
– It shows the sign off from the business, agreeing to the change.
– When the production deployment failed, it is recorded properly including the reason and the solution.
– It shows that every change in production is controlled, so the production systems are stable and reliable.

A change request is an electronic form which specifies:
– The reason for the change (usually a business reason but can be a technical reason)
– The list of components and data to be changed
– The evidence that the change has been deployed to Test/UAT environment the same way it will be deployed into production
– Link to the design specification or requirement which forms the basis of the change
– The evidence that the change satisfies the design specification or requirement (or if it is a bug fix, the evidence that the change fixes the bug)
– The impact of this change to the business users
– The approval from the business, from the development manager, and from the production support
– The updated documentation for the production support
– How the change will be deployed to production and to the DR system
– How the change will be tested that it works in production
– How the change will be rolled back if it doesn’t work in production
– The date the change is intended to be deployed to production
– The developer who did the change
– Who from the development team will be on support on the day the change is deployed to production
– Which teams are required to deploy the change
– The applications which are impacted, including downstream applications
– The severity of impact of the change, i.e. high, medium, low (the risk)
– The scale of the change, i.e. major change, minor change or medium (how many components)
– Whether it is an emergency change or not

The change request form is not just for application changes, but also for infrastructure changes such as servers and networks. It is for any changes impacting any production system, including codes, files, databases, servers, configurations, firewall, connections, permissions, scheduling.

Major change requests are discussed in a weekly meeting between the developers and the production support team to understand:
– What changes are going in this week
– Whether there are any conflicts between the changes which are going in this week
– Where those changes are in terms of their positions in the daily batch
– If things do go wrong, how long it will take to recover (or to fix)
– Who is required to standby to fix if anything goes wrong (DBA, infrastructure, developer)
– When those changes should be done from production point of view (to minimise the impact).
– To scrutinise the test evidence, not whether the change satisfies the requirements, but whether the change has been deployed in the Test system the same way as it would be deployed in production. In particular, whether the condition of the Test environment is the same as production. Also, whether the impacted application has been tested in Test environment.
– To check that the rollback script really covers the whole change, not just part of it. And whether it has been tested.
– Whether you need to communicate the change to the users or not, and whether the help desk should be prepared to field calls from the users on the deployment day.

The changes are then either approved or rejected. If it is approved, it is given a date and time when it will be deployed. Naturally, the business and the development team want the change to be deployed as soon as possible, but it is the responsibility of the production support team to decide the timing, to minimise the risk. Changes with major impact (or high risk) are usually deployed on Saturday when the business users are not working so they are not impacted and you have Sunday to recover or fix any issues. Changes with medium impact (and medium risk) can be deployed on Friday, so you have Saturday for fixing. Changes with low impact and low risk can be deployed earlier in the week (Wed or Thu but not Mon or Tue).

If there are major changes going in this week end, it is wise to defer deploying other major changes to next week end. Similarly if the required support resources is not available this week end (if it goes wrong) then the change should be postpone to next week.

Some changes requires coordination with an external vendor. So the timing of production deployment must be mutually agreed. Some changes are time-bound, i.e. they have to be done before certain date otherwise the company will get a penalty from the regulator.

Some changes need to be done immediately, for example because of security risk, or risk of losing a great deal of money. This is classified as an emergency change and it is usually a bug which needs to be fixed immediately. The procedure for emergency change request is different to a normal change request. It still requires approval, it still needs to be tested, but a lot more streamlined. In most cases the principle of applying emergency changes is “fix after”, meaning if things go wrong you do not roll the change back, but you fix it. This requires more people to standby compared to a normal change. This “fix after” principle allows the testing to be light weight.

3. Sprint Planning

The third thing that you need to run a development team is sprint planning. A sprint is a unit of two weeks. In theory it is possible to define a sprint as 1 or 3 weeks, but I’ve been working at 4 companies which do sprint, and every single one does 2 weeks.

Yes Sprint is a way of running Agile. No one does Waterfall any more these days. Funny how things moved, 5 years ago people still debating Agile vs Waterfall. But not now. No more debate on that. The debate is more around CI/CD atau automated testing.

Azure DevOps is probably the best tool in the market, followed by Jenkins, Travis. Many are not a complete DevOps tool. GitHub, Grade, JIRA, Bamboo, AWS CodePipeline, Trello for example. They just doing build and source code control but without CI/CD, or vice versa. Or doing both but not sprint planning (Trello do sprint planning but no release pipeline, whereas AWS CodePipeline is the opposite). Even Azure DevOps is not complete (it doesn’t do change control), but it does sprint planning, source code control, release pipeline CI/CD and automated testing.

Every two weeks you plan the works that you need to do in the next sprint. These pieces of work are called user stories. First you define the team capacity, i.e the number of working days minus the holidays. You then allocate how many days is required for each story, who will be doing it, and the acceptance criteria (the definition of done), i.e. just doing the development and test, or until production. Then you check if anyone is under or over allocated. If someone is over capacity, distribute or reduce the work.

After planning, during the 2 weeks sprint run you track the progress of each story. For each story you create a few tasks with an estimate and the person doing it. As each task gets done, you mark the actual hours against the estimate. The status of each task changes from new to in-progress to completed. This will create a burndown chart, which tracks the whole team’s actual hours against estimate.

It’s all very well and good doing planning and tracking as above, but how do you determine what needs to be done in the first place? This is where the product owner comes in. The list of work in each sprint should be driven largely from the prioritised list of projects + product increment. If the team is a dedicated project team, then the list of work comes from just 1 project + the BAU of that project. Some teams serve multiple projects (size of 3 months to 1 year) plus hundreds enhancement requests (size of 2 to 10 days) throughout the year.

4. Automated Testing

The fourth thing that you need to run a development team is automated testing. Many people leave this to the back of the queue, but the reality is that this thing saves a lot of time (and money), and increases the quality of the code enormously. Automated testing means two things:
a) Ensuring that deployment to production does not break anything
b) The code satisfies all the intended functionalities, and none of the unintended ones

Point a) is achieved by copying the production system into the test environment. The lot, i.e. thousands of components, code, settings, databases and files from production is restored into the test environment overnight. Then you apply the latest code and data changes from the release pipeline into this test environment. Then you run the whole system, and check the expected results. The key thing is: all of these are conducted programmatically, every day, without any human intervention.

Point b) is achieved by having a test environment which is completely empty, i.e. no data. You have the databases, but there are no rows in any tables. You have the data folders but there are no data files in them. Then you test 1 piece of code, e.g. a .Net web service or a stored procedure. You do this by setting up test data, e.g. you insert a few rows into the input tables. Each row reflect one specific test scenario. Then you run the code and check the result. Then you repeat it for all pieces of code in the system, thousands of them. For 1 piece of code you need to run some positive tests and some negative tests. The key thing is: all of these are conducted programmatically, every day, without any human intervention.

If you have to do all that manually, it would requires thousands of hours. Actually it would be impossible to do because for every release you will have to repeat both tests. If you don’t have automated testing, you can’t deploy to production 3x a week. The best you can do is once a quarter, because of the amount of testing involved. It does not make sense to do 10 hours of development and then spend 2000 hours of testing right? But once your hours of testing is down to zero, then you can do a 10 hours development, test it and deploy to production. And then you can do another 10 hours of development, and so on.

Because for every single change you run “the whole lot of testing” twice (the a and the b above), you can release very often, and you increase the quality of the code. You do positive testing and negative testing on every component, and also integration testing. The a) above is called “system testing”, and the b) above is called “unit testing”. Both are automated.

Does it mean you do not need to do manual testing? No, you still need to. When a major feature is developed, you need to do manually test the functionalities across the whole piece. Suppose you are adding a new feature in an order processing system which enable the system to combine orders from different customers and process them together. There are 9 places in the system which need code changes. Each of these 9 pieces has been unit tested individually using the b) above, which proves that each piece works individually (using minimal amount of data, i.e. a few rows). The whole system has been system tested using the a) above, which proves that there is no negative impact to the system as a whole.

But how do you know that the ability to combine orders really works end-to-end, using a normal production data volume? The automated unit test only uses a few rows, and they are made up data. It does not prove that end to end the new feature is working. To prove that the new feature is working we need to run thousands of real orders from last month across the system, combining hundreds of them, process them and check the output. Are all order processed correctly? Are there any issues? If it passes this test we can say hand on heart that the system now has capability of combining orders.

5. Code Repository

This is a must in any development team. You can use GitHub, TFS, SVN, PVCS, BitBucket, or others, but you need to have the capability of storing code, versioning, master and feature branches, committing changes, packaging and releasing code, merging, collaborating, restoring to previous version, doing code reviews and pull requests.

Whether it is Java code, Python, databases, ETL tool, cubes or reports, they are code. And they ALL need to be in ONE code repository. And the code repository MUST be integrated with the release pipeline. You need to be able to push a release candidate to the release pipeline, test it and deploy it automatically into various environment including test, support and production.

6. Server Build

Like automated testing, this one is frequently put at the back of the queue, but it really is a time saver and money saver. So we need to do it. Server Build is the ability to create a server programmatically. A release pipeline consists of a series of environments such as Dev, Test, UAT, Prod and Support. Each environment consist of several servers, like SQL Server, application server, SSIS server, SSAS server, Python server, etc.

These servers need to be built. If you build them manually, it would take a lot of hours. Not just once, but they will need to be configured, patched and maintained. And when they don’t work, you need to troubleshoot it and fix it.

A better way to create servers in Azure is using PowerShell DSC. For each environment you need to create a DSC configuration which tells PowerShell DSC the server name, resource group, folder paths, Windows features and any other characteristics which are specific to each environment and each server. The PowerShell DSC then reads this DSC configuration and create each server in each environment according to the settings written in this file.

The best practice is to recreate these servers on a weekly basis (except the production environment), to avoid having to upgrade and patch them.

7. BAU/support/bug fixes
8. Business requirement & design
9. Architecture

The traditional understanding of “DevOps” as a system normally includes point 1 to 6, but not 7 to 9. But 7 to 9 are certainly required to run a development team for any system (I do mean software, not civil engineering).

3 August 2019

Memory for SSIS

Filed under: Data Warehousing — Vincent Rainardi @ 6:56 am

SQL Server has an upper memory limit in the Server Properties. This is the maximum amount of memory that SQL Server database engine can use. Just the database engine. It does not include SSRS, SSIS or SSAS. This maximum amount of memory is constantly used by SQL Server database engine. If we set the upper limit to 90 GB, SQL Server DB engine will use all 90 GB, all the time. Not some of the time, but all of the time. SQL Server DB engine will use 90 GB every minute of the day.

Many people put SSIS into the same box as the SQL Server databases. This is fine, provided that SSIS is given enough amount of memory. If there the box has 96 GB, and the maximum amount made available to SQL Server is 90 GB, then only 6 GB is available for all other things, including Windows processes, antivirus, SSIS, SSRS and SSAS. In this case SSIS would be running very slowly, like 100 times slower that how it should be. Because effectively only a few MB is available to SSIS (depending on what other applications/processes are doing).

If the SQL Server box has 96 GB and the max amount is already set to 90 GB, and we put SSIS on the box, that 90 GB should be lowered to around 70 GB, so that there are 26 GB available for SSIS, Windows and other processes. We then look at the amount of memory used by SSIS engine (in the task manager, or use the Profiler). Generally speaking, SSIS would be happy if it has 16 GB available to it. Very big packages could require 32 GB, for example packages which move billion of rows.

Take 5 GB or so for Windows processes, antivirus and other operating system. Assuming there is no SSRS or SSAS on the box, then we can calculate that out of that 26 GB, 21 GB is available for SSIS to use. If there is SSRS on the box, take 5 to 10 GB for SSRS. If there is SSAS on the box, it is a different story, as SSAS tends to grab all remaining available memory. For this reason we should be putting SSAS in its own box/VM.

With 21 GB SSIS should be able to perform near its peak performance. If the package processes up to 1 million rows, there will be no problem. If 5 packages running simultaneously processing up to 1m rows, the should be no problem. Unless the package is written in a very efficient way of course. Because SSIS will automatically batch it in chunks of 10,000 rows. So “normal size” packages should be running ok in SSIS with near peak performance with 16-21 GB memory (based on my experience).

What if you only have 64 GB on the box? Then allocate 43 for SQL Server (which should be enough for most queries or SQL operations, for most database sizes), giving 21 GB free memory for all other processes. Taking 5 GB for Windows, leaving 16 GB for SSIS (assuming there is no SSRS on the box).

What if you only have 32 GB on the box and you want SQL Server and SSIS running parallel? Give 16 GB to SQL Server, leaving 16 GB for others. Minus 5 GB for Windows and other O/S related, this gives 11 GB to SSIS. Not ideal, but that’s the best we can set for both SSIS and SQL Server, without knowing the details of the SSIS packages. Once we know the detail work flow and tasks then we can be more precise.

I’m worry if there is less than 4 GB for SSIS (after taking out 5 GB for Windows process, antivirus and other applications, and after taking out 5 GB for SSRS). 8 GB is the bare minimum I would recommend as memory for the SSIS, for most packages.  But my default recommendation for most packages would be 16 GB (that’s free memory just for SSIS, after taking out Windows and SSRS).

You can of course measure it on your dev box using profiler and check the peak memory requirements, when the packages are being run in SQL server. But this takes time (1-2 weeks), in order to properly measure up the collective requirements of all packages running in parallel.

30 May 2019

Entropy and Information Gain in Decision Tree

Filed under: Data Warehousing — Vincent Rainardi @ 7:28 pm

Decision Tree is one of the most popular algorithms in machine learning. It is relatively simple, yet able to produce good accuracy. But the main reason it is widely used is the interpretability. We can see how it works quite clearly. We can understand how it works.

Decision Tree is a supervised machine learning algorithm. So we train the model using a dataset, in order for it to learn. Then we can use it to predict the output. It can be used for both regression and classification. Regression is when the output is a number. Classification is when the output is a category.

In this article I would like to focus on Entropy and Information Gain, using investment funds as an example. Entropy is the level of disorder in the data.


In thermodynamics, Entropy is the level of disorder or randomness in the system. Similary in data analytics, entropy is the level of disorder or randomness in the data. If we have 100 numbers and all of them is 5, then the data is in very good order. The level of disorder is zero. The randomness is zero. There is no randomness in the data. Everywhere you look you get 5. The entropy is zero.

If these 100 numbers contain different numbers, then the data is in a disorder state. The level or randomness is high. When you get a number, you might get number 4, or you might get number 7, or any other number. You don’t know what you are going to get. The data is “completely” random. The level of randomness in the data is very high. The entropy in data is very high.

The distribution of these different numbers in the data determine the entropy. If there are 4 possible numbers and they are distributed 25% each, then the entropy is very high. But if they are distributed 99%, 1%, 1%, 1% then the entropy is very low. And if it’s 70%, 10%, 10%, 10% the entropy is somewhere in between (medium).

The maximum value for entrophy is 1. The minimum value for entrophy is 0.

Information Gain

Now that we have a rough idea of what entropy is, let’s try to understand Information Gain.

A Decision Tree consists of many levels. In the picture below it consists of 2 levels. Level 1 consists of node A. Level 2 consists of node B and node C.

1. Two Branches of Entropy

Information Gain is the decrease in entropy from one level to the next. Node B has entrophy = 0.85, a decrease of 0.1 from Node A’s entrophy which is 0.95. So Node B has information gain of 0.1. Similarly, Node C has information gain of 0.95 – 0.75 = 0.2.

When the entropy goes down from 0.95 to 0.75, why do we say that the amount of information is more (gaining)? Higher entrophy means the data is more uniform, lower entropy means the data is more distributed or varied. That’s why there is more information in the data, because the data is more varied. That’s why when the entropy decreases the amount of information is higher. We have “additonal” information. That is Information Gain.

Calculating Entropy

Now we know what Entropy is, and what Information Gain is. Let us now calculate the entropy.

First let’s find the formula for entropy. In thermodynamics, entropy is the logarithmic measure of the number of states

Entropy is the average of information content (link). The information content of an event E1 is the log of 1/(the probability of E1). The information content is called I. So I1 = log of (1/p(E1)).

If we have another event (E2), the information content is: I2 = log of (1/p(E2)).

The average of the information content I1 and I2 (or the entropy) is:
the sum of (information content for each event x the probability that event occuring)
= I1 x p(E1) + I2 x p(E2)
= log of (1/p(E1)) x p(E1) + log of (1/p(E2)) x p(E2)
= –log of p(E1) x p(E1) –log of p(E2) x p(E2)

If we have i events, the entropy is:
= -sum of (p(Ei) x log of p(Ei))

Fund Price

Now that we know how to caculate entropy, let us try to calculate the entropy of probability of the price of a fund going up in the next 1 year.

2a. Fund price table (top).PNG
2b. Fund price table (bottom)

In the above table, the last column is the price of a fund 1 year from now, which can be higher or lower than today. This is denoted with “Up” or “Down”. This price is determined from 4 factors or features:

  1. The performance of the fund in the last 3 years (annualised, gross of fees).
    This past performance is divided into 3 buckets: Down (less than zero, “Up between 0 and 2%”, and “Up more than 2%”.
  2. The interest rate, for example LIBOR GBP 1 Year today.
    This today interest rate is compared with the interest 1 year go, and divided into 3 buckets: today it’s higher than 1 year ago, lower than 1 year ago, or the same (constant).
  3. The value of the companies that the fund invest in, by comparing the book value to the share price of the company today. Also the earning (the income) the companies make compared to the share price (cyclically adjusted). This company value factor is divided into 3 buckets: overvalued, undervalued and fair value.
  4. The ESG factors, i.e. Environment, Social and Governance factors such as polution, remuneration, the board of directors, employee rights, etc. This is also divided into 3 buckets, i.e. high (good), medium, and low (bad).

The Four Factors

1. Past performance

Funds which have been going up a lot, generally speaking, has the tendency to reverse back to the mean. Meaning that it’s going to go down. But another theory says that if the fund price has been going up, then it has the tendency to keep going up, because of the momentum. Who is right is up for a debate. In my opinion the momentum principle has stronger effect compared to the “reveral to the mean” principle.

2. Interest rate

Because the value/price of the fund is not only affected by the companies or shares in the fund, but also affected by external factors. The interest rate represent these external factors. When the interest rate is high, share prices growth is usually constraint because more investors money is invested in cash. On the contrary, when the interest rate is low, people don’t invest in cash and invest in shares instead (or bonds).

But the factor we are considering here is the change of interest rate. But the impact is generally the same. Generally speaking if the interest rate is going up then the investment in equity is decreasing, thus putting pressure on the share price, resulting lower share price.

3. Value

If the company valuation is too high, the investors become concerned psychologically, afraid of the price would go down. This concern creates pressure on the share price, and the share price will eventually goes down.

On the contrary, if the the company valuation is lower compared to similar companies in the same industry sector and in the same country (and similar size), then the investors would feel that this stock is cheap and would be more inclined to buy. And this naturally would put the price up.

4. ESG

Factors like climate change, energy management, health & safety, compensation, product quality and employee relation can affect the company value. Good ESG scores usually increase the value of companies in the fund, and therefore collectively increases the value of the fund.

On the contrary, concerns such as accidents, controversies, pollutions, excessive CEO compensation and issues with auditability/control on the board of directors are real risks to the company futures and therefore affect the their share price.

Entropy at Top Level

Now that we know the factors, let us calculate the Information Gain for each factor (feature). This Information Gain is the Entropy at the Top Level minus the Entropy at the branch level.

Of the total of 30 events, there are 12 “Price is down” events and 18 “Price is up” events.

The probability of the price of a fund going “down” event is 12/30 = 0.4 and the probability of an “up” event is 18/30 = 0.6.

The entropy at the top level is therefore:
-U*Log(U,2) -D*Log(D,2) where U is the probably of Up and D is the probability of Down
= -0.6*Log(0.6,2) -0.4*Log(0.4,2)
= 0.97

Information Gain of the Performance branch

The Information Gain of the Performance branch is calculated as follows:

3a. Information Gain for Performance branch

First we calculate the entropy of the performance branch for “Less than 0”, which is:
-U*Log(U,2) -D*Log(D,2) where U is the probably of the price is going up when the performance is less than zero, and D is the probability of the price is going down when the performance is less than zero.
= -0.5 * Log(0.5,2) -0.5 * Log(0.5,2)
= 1

Then we calculate the entropy of the performance branch for “0 to 5%”, which is:
= -0.56 * Log(0.56,2) -0.44 * Log(0.44,2)
= 0.99

Then we calculate the entropy of the performance branch for “More than 5%”, which is:
= -0.69 * Log(0.69,2) -0.31 * Log(0.31,2)
= 0.89

Then we calculate the probability of the “Less than 0”, “0 to 5%” and “More than 5%” which are:
8/30 = 0.27, 9/30 = 0.3 and 13/30 = 0.43

So if Performance was the first branch, it would look like this:

2c. Performance as the first branch

Then we sum the weighted entropy for “Less than 0”, “0 to 5%” and “More than 5%”, to get the total entropy for the Performance branch:
1 * 0.27 + 0.99 * 0.3 + 0.89 * 0.43 = 0.95

So the Information Gain for the Performance branch is 0.97 – 0.95 = 0.02

Information Gain for the Interest Rate, Value and ESG branches

We can calculate the Information Gain for the Interest Rate branch, the Value branch and the ESG branch the same way:

3b. Information Gain for Interest Rate branch

3c. Information Gain for Value branch

3d. Information Gain for ESG branch

Why do we calculate the entropy? Because we need entropy to know the Information Gain.

But why do we need to know the Information Gain? Because the decision tree would be more efficient if we put the factor with the largest Information Gain as the first branch (the highest level).

In this case, the factor with the largest Information Gain is Value, which has the Information Gain of 0.31. So Value should be the first branch, followed by ESG, Interest Rate and the last one is Performance.

10 May 2019

Analysis Services Tabular Model

Filed under: Data Warehousing — Vincent Rainardi @ 6:03 pm

What is it?
It is an in-memory database, managed by the Analysis Services Vertipaq engine.

Who uses it?
Power BI and Excel Power Pivot.

Why use it?
To provide fast and simple access to relational data.

When was it introduced?
2012 by Microsoft

How to create it?
Using SQL Server Data Tool.

Where is it stored?
in SQL Server Analysis Services server or Azure Analysis Services.
The data is compressed when stored.

What are the components?
– Tables
– Relationships
– Measures
– Hierarchies
– KPIs
– Partitions

22 March 2019

Bridge table

Filed under: Data Warehousing — Vincent Rainardi @ 8:22 am

In dimensional modelling, a bridge table is a table which connects a fact table to a dimension, in order to bring the grain of the fact table down to the grain of the dimension.

The best way to learn the complexity of this bridge table is using an example, so let’s get down to it.

Driver Bridge Table

An example of a bridge table is the insurance claim fact table in the car insurance industry. The grain of this fact table is one row for each claim (this is different to claim payment fact table where the grain is one row for each claim payment). One of the dimension keys in this claim fact table is the policy_key. Another dimension key is the insured_driver_key.

In car insurance there is only one policy per claim so there is no problem with the policy key. There is usually one driver per claim, but there could be two drivers per claim. It is rare but occasionally there is third driver. I mean drivers covered by our policy, not the third party drivers. The second driver on the policy is called the named driver (ditto the third driver). In other company there could be a fourth driver, but for this company/case let us set that the maximum number of driver to three.

The function of the bridge table is to connect the claim fact table to the driver dimension. Because there could be more than one driver per claim, the surrogate key column is not called driver_key, but driver_group_key. The bridge table is called Bridge_Driver_Group, which has only two columns:

  • driver_group_key: connects to the Insured_Driver_Group_Key column on the claim fact table
  • driver_key: connects to the driver_key column on the driver dimension table

A Sample Claim

Now consider a claim where the claim fact table is like this:

Fact_Claim table:


188|Chloe Dunn|1980-08-08|3824920
302|Peter Keller|1971-06-05|4503532
304|Samantha Keller|1970-12-07|4507651

The key question in car insurance claim is how much claim has a driver made, across all policy, across call insurer (insurers share claim data). This figure is used to determine the premium discount for the following year. The more recent a claim is the more weight it has to the next year premium. Chloe Dunn has 2 claims totalling £42800 (before excess). The first one was on 18th May 2010 and the second one was on 25th July 2018.

Type and Weight Columns on the Bridge Table

But Peter Keller shares a policy with his wife, Samantha Keller. We know that both of them has claimed £48000 but how much each is what we need to know.

To do this we add a weight column and driver_type on the bridge table. There is a business rule to determine the weight, for example: the main driver get 2/3 and the second driver get 1/3. If there are 3 drivers, the main get 50%, the second and third get 25%. The rule depends on the company. Each company has a different rule.

88|188|single driver|1.000000
89|302|main driver|0.666666
89|304|second driver|0.333333
90|405|main driver|0.500000
90|406|second driver|0.250000
90|407|third driver|0.250000

Now we know how much claim is attributed to Peter Keller. It is 2/3 of £48,000 = £32,000.

The Group Dimension

Note that the bridge table above has many-to-many relationship with the fact table. Analysis Services doesn’t like many-to-many relationships. In Analysis Services modelling, a fact table can’t be linked to a bridge table like above. Instead, a fact table must be linked to a dimension table in a one-to-many relationship. This dimension table is called a Group dimension, like this:

Fact_Claim table: (same as before)

Dim_Driver_Group: (this is the Group dimension)

Bridge_Driver_Group: (same as before)
88|188|single driver|1.000000
89|302|main driver|0.666666
89|304|second driver|0.333333

Dim_Driver: (same as before)
188|Chloe Dunn|1980-08-08|3824920
302|Peter Keller|1971-06-05|4503532
304|Samantha Keller|1970-12-07|4507651

Account and Diagnosis Bridge Tables

Another classic example of a bridge table is in retail banking. It is the bridge table from the account to customer. Another famous example by Ralph Kimball and Margy Ross is the multi value diagnosis. For this please read Kimball Data Warehouse toolkit chapter 13. For the account to customer bridge table it is in chapter 9 of the same book. I don’t want to repeat them here as they have done an excellent job in explaining it there. Note the book I quote above is the second edition. For other editions please look at the index for “bridge tables”.

Policy Dimension

I just realised that the Kimball Data Warehouse toolkit book also mentions the bridge table for insured driver (in chapter 15). But the difference is that the driver dimension is linked to the policy dimension, not driver group dimension. Also that the insurance example in Kimball book is about a premium fact table, not claim fact table.

The reason it is possible to use a policy dimension instead of driver group dimension is: in the car insurance the driver is attached to the policy. So I think Kimball’s approach is better, because it eliminates the need to create the driver group dimension, which in reality such thing didn’t exist. But the alternative of not using any dimension at all is also possible, I mean we attach the bridge table directly to the fact table, like the first example I mentioned above.

If we replace the driver group dimension with a policy dimension, what we get is something like this:

Fact_Claim table: (same as before)

Dim_Policy: (previously this was Dim_Driver_Group)
48523|NK98402|2015-08-12|2018-08-12|2019-08-11|Chloe Dunn|comprehensive|Y|2015-08-07 00:00:00|9999-12-31 23:59:59|Y
63291|NK84826|2014-11-01|2018-11-01|2019-10-31|Peter Keller|third party|N|2014-10-26 00:00:00|9999-12-31 23:59:59|Y

Bridge_Driver_Group: (replace the first column with policy_key)
48523|188|single driver|1.000000
63291|302|main driver|0.666666
63291|304|second driver|0.333333

Dim_Driver: (same as before)
188|Chloe Dunn|1980-08-08|3824920
302|Peter Keller|1971-06-05|4503532
304|Samantha Keller|1970-12-07|4507651

We need to bear in mind that in car insurance, the policy dimension is the biggest dimension. It has a lot of columns and a lot of rows. And it is a type 2 dimension. The last renewal date and the expiry date change every year, and therefore the policy_key column in the bridge table will need to be updated. This is really not suitable for the purpose of the bridge table (which is to link the fact table to the driver dimension).

Group Dimension Created from Policy Dimension

The best solution I found is to create a group dimension as a type 0 dimension, based on the policy dimension. We cut away all the attributes, leaving just the policy number, like this:

Fact_Claim table: (same as before)

88|NK98402|2015-08-07 04:12:05
89|NK84826|2014-10-26 04:14:09

Bridge_Driver_Group: (same as before)
88|188|single driver|1.000000
89|302|main driver|0.666666
89|304|second driver|0.333333

Dim_Driver: (same as before)
188|Chloe Dunn|1980-08-08|3824920
302|Peter Keller|1971-06-05|4503532
304|Samantha Keller|1970-12-07|4507651

Note that Dim_Driver_Group is type 1 so it doesn’t have effective_date, expiry_date or active_flag columns. Instead it only has inserted_date column because it is type 0. Type 0 means that it is fixed. Once a row is inserted it will never get changed or updated.

Tracking Changes in the Bridge Table

What if Peter and Samantha Keller add their 18 year old daugther (Karina) to the policy, and now the number of insured driver in their policy becomes three?

Fact_Claim table: (same as before)

Dim_Driver_Group: (same as before)
88|NK98402|2015-08-07 04:12:05
89|NK84826|2014-10-26 04:14:09

88|188|single driver|1.000000|1900-01-01|9999-12-31|Y
89|302|main driver|0.666666|1900-01-01|2019-03-22|N
89|304|second driver|0.333333|1900-01-01|2019-03-22|N
89|302|main driver|0.500000|2019-03-22|9999-12-31|Y
89|304|second driver|0.250000|2019-03-22|9999-12-31|Y
89|375|third driver|0.250000|2019-03-22|9999-12-31|Y

Dim_Driver: (same as before)
188|Chloe Dunn|1980-08-08|3824920
302|Peter Keller|1971-06-05|4503532
304|Samantha Keller|1970-12-07|4507651
375|Karina Keller|2001-04-15|9302583

Notice that Karina does not contribute to her parents’ claim on 18th Nov 2018, because she was put on the policy today (22nd March 2019). But Karina is responsible for any claim happen after today. It is quite complex to calculate the claim amount attributed to each driver, so I would recommend calculating it overnight and putting the output in a separate fact table, or an output table. If the business needs to browse this data (drilling up and down, slicing and dicing) then put it in a fact table. If this “claim per driver” data is required for producing a report, then put it in an output table.

21 February 2019

Data Files – Delimiter and Qualifier

Filed under: Data Warehousing — Vincent Rainardi @ 8:06 am

Suppose you got to specify a file spec for your data supplier to send their data via FTP. Would you request them to send you Excel files or CSV files? Do you prefer a tab delimited text file or pipe delimited? Do you ask them to qualify their string with double quotes?

Excel or CSV

I would prefer CSV files than Excel files, because the number of columns in Excel which can be read by SSIS is limited to 255 columns (see link). Whereas in CSV files there are no limitation regarding the number of columns.

To overcome this limitation we need to import it twice (or three times) using two data source components and then join them. But in order to join them we will need to have an identity column, which will become the join criteria (see link). We also need to be careful with the performance when joining because merge join can be slow.

The second issue with Excel file is the OLE DB Provider installed in the server where SSIS is running, otherwise we could get an error message saying that “OLE DB provider Microsoft.ACE.OLEDB.12.0 is not registered” (see link). The “Use 32 bit runtime” in the SQL Agent job step and Run64BitRunTime in the project property are also affecting this.

The other disadvantage of importing an Excel file is dealing with zero in the front of a string, such as “007”, which automatically becomes number 7.

Also numbers which are in scientific notation, such as 1.23E21, which will then be imported as a string rather a number, causing a failure. If it is in CSV it written as 1230000000000000000000 in the file and imported as a number.

The other limitation of Excel is about cells containing long strings, such as 2000 characters, being cut to 256 characters. This issue only happens before 2007 edition.


What delimiter do you prefer: comma, pipe or tab?

The problem with CSV or a comma delimited file is that we have comma in the data. This causes misalignment when the file is imported. For example, if there are 10 columns, and one of them has a comma, this row will become 11 columns. This problem is known in the IT world as “delimiter collision”, see here: link.

Comma in the data is very common when dealing with numeric fields, such as “123,000”. Or, in countries like Indonesia which uses comma as a decimal point, it is like this: “100,23”.

We can enclose it with double quotes, but why not eliminate the problem in the first place? That’s why for text files people prefer pipe delimiter or tab delimiter. Text file with tab delimiter is known as tab-separated values, or TSV (link), but pipe delimited files are not known as PSV. We do have DSV though, which stands for Delimiter Separated Values (link).

Pipe is generally preferable because of the perception that it is rarer than tab. Some strings may contains tab, for example in a commentary field.


Qualifier means enclosing the data with something, such as double quote. Double quote is the most common delimiter. Other delimiters (but far less common) are single quote and brackets. There are 3 different types of bracket, i.e. [ ], < > and { }.

The issue with double quote delimiter is that the data may contain double quote, such as in commentary fields. This applies to other delimiters too. That’s why it is ideal to use pipe delimiter, without qualifier.

So that’s my preferred choice for the format of a data file, if I can choose it: pipe delimited text file without qualifiers. But unfortunately, in reality, we very rarely get the opportunity to choose the format. Usually the vendor dictates the format because the same file goes to many customers.

20 February 2019

Transactional Fact Tables

Filed under: Data Warehousing — Vincent Rainardi @ 9:11 pm

Transactional fact tables are not as popular as periodic snapshot fact table. In this article I would like to compare transactional and periodic snapshot fact tables, list their advantages and disadvantages, and give two cases from my own experience where I needed to decide between the two. But first let me explain what these two types of fact tables are.

What is a transactional fact table?

In dimensional data modelling we have 3 types of fact tables: transactional, periodic snapshot and accumulation snapshot. I’m going to explain the first two below.

1. Transactional Fact Table

A transactional fact table is a fact table where:

  • Each event is stored in the fact table only once.
  • It has a date column indicating when the event occurred.
  • It has an identifier column which identifies each event.
  • The number of rows is the same as the source table.

A classic example is when in the source system we have a sales table containing customer orders (for example, in a shop, a restaurant, or a factory). Say Monday we had 80 orders, Tuesday 70 orders, Wednesday 90, and so on. So on Monday night we load the 80 rows for Monday into the data warehouse. On Tuesday night we load the 70 rows for Tuesday, and on Wednesday night we load the 90 rows for Wednesday.

Transactional Fact Tables
Figure 1
. A transactional fact table loading 3 days data

In the data warehouse we store the customer orders in the Sales Fact Table, which is a transactional fact table.

  • In this Sales Fact Table, every order is stored only once. The 70 orders on Tuesday are different to the 80 orders on Monday. And they are also different to the 90 Wednesday orders.
  • For this we use the order date column. In the above example the Monday, Tuesday and Wednesday are the order date. This order date column indicates when the event occurred, when the order happened.
  • In this sales table we also have a sales identifier, such as order number if it is a shop, or ticket number if it is a restaurant.
  • On Wednesday night, after the warehouse load finishes, we have 80+70+90 = 240 rows, the same as in the source system.

In addition to insert, we also have update in the source table. In the example above, in addition to 70 new orders on Tuesday, we also have updates to some of the 80 Monday orders. This is they key difference to the Periodic Snapshot fact table: a Transactional fact table updates existing rows, and therefore lost some history.

Other ideal examples of a transactional fact table is the journal table in an accounting system, a trade table in an investment banking system, a premium table in an insurance system, a payment table in a payment system, a transaction table in a retail banking system, and a call table in a telecommunication system.

2. Periodic Snapshot Fact Table

A periodic snapshot fact table is a fact table where:

  • The whole source system is copied into the fact table regularly.
  • The same event is stored multiple times.
  • It has a snapshot date column indicating when a copy of the source table was created.

An ideal example of a periodic snapshot fact table is the bank account balance. At the end of each day, the balances of every customer account in the bank is stored in this account balance table. Say there were 20,000 customers on Monday; 22,000 customers on Tuesday and 24,000 customers on Wednesday.

Periodic Snapshot Fact Tables
Figure 2. Periodic Snapshot Fact Table

  • Every day we copy the whole content of the account balance table into the periodic snapshot fact table.
  • So on Monday night we stored 20,000 rows in the account balances periodic snapshot fact table, on Tuesday night 22,000 rows and on Wednesday night 24,000 rows. So an account is copied every day to the fact table, each day with potentially a different balance amount.
  • In the fact table we have a column called snapshot date. For all the rows created on Monday night, we set the snapshot date column to (for example) 11th Feb 2018. For the rows created on Tuesday night we set the snapshot date to 12th Feb 2018 and for the Wednesday rows we set the snapshot date to 13th Feb 2018.

Of course there are accounts which were closed on Tuesday and no longer in the account balance table in the source system. In the fact table, the Monday data set contains these accounts, but the Tuesday data set doesn’t contain these accounts, and neither does the Wednesday data set.

And there are accounts which were updated on Tuesday. These changes will be reflected on the Tuesday snapshot in the fact table, different to their Monday rows.

Another example is inventory table in manufacturing, holdings table in fund management, billing balance table in telecommunication, and daily temperature table in a weather system.

Advantages and Disadvantages

The advantages of a transactional fact table are:

  • It mimics the source table
  • It is simpler as we only have once version of each event

The disadvantages of a transactional fact table are:

  • We don’t have the previous values
  • Update is slow if the fact table is large, potentially performance issue

Now let’s get on with the two cases of transactional fact table implementations.

Case1: Retail Association

Let’s suppose we are running a Retail Association. Every shop in the country reports their annual sales data on our website, within one month of their financial year end. In January 2019 there were 8,000 shops reporting their sales data on our website, and in Feb 2019 there were 9000 shops reporting their sales data. There are about 100,000 shops in total.

Every month we get a CSV file containing the previous month data. The file is called Data_YYYYMM.csv and the file contains a column called Reporting Date. So:

  • The Data_20180131.csv contains the 8000 shops reporting in January 2019, with the Reporting Date column containing dates from 1st to 31st Jan 2019.
  • The Data_20190228.csv contains the 9000 shops reporting in February 2019, with the Reporting Date column containing dates from 1st to 28th Feb 2019.

Case 1
Figure 3. Retail Association monthly data file loaded into a transactional fact table

Because on the February file the January data is not given in full (but only the changed and new rows), we can’t make it as a periodic snapshot fact table. So in this case a transactional fact table is the only option.

Heart of Transactional Fact Tables

In theory the loading is straight forward. Jan file is loaded, then Feb file, and so on. But in reality this is rarely the case. A few shops who supposed to report in January were late, and they reported in February. So the in the February file we also get a few rows of the January “late reporter” shops.

Some shops made an error in their January submission and corrected it in February. So in February file we also have a few rows containing January corrections.

That is the heart of transactional fact tables: performing updates to the previous months’ data. In this case it goes back only one month, but in real cases it could be a few months.

Case 2: Waste Reporting

Suppose we are working with a government department responsible for implementing the waste regulations in our country. Every company and government agency in the country needs to report the amount and types of their packaging waste, electronic waste, commercial waste and recyclables e.g. plastic, paper, metal. This report is annual (once a year). Every town council also need to report the amount and types of their household waste, also annually.

The timing when they have to submit the report is different for every company, agency and council, depending on their financial year end. But the report contains the same year, which is the previous calendar year. So companies/agencies/councils with financial year ending on 31st March 2018 need to report the waste happened from Jan to Dec 2017. Those with financial year ending on 31st August 2018 also need to report the waste happened from Jan to Dec 2017.

The data we get from this central government department is monthly, i.e. every month we get a file. The file contains the waste produced in the previous calendar year. So the file we get in all 12 months of 2019 contains the waste data for 2018, but growing every month. For example, in Jan 2019 the file contains 17,000 entities (i.e. companies, agencies and councils), in Feb 2019 the file contains 32,000 entities, the March 2019 file contains 49,000 entities, and so on, like below.

Case 2
Figure 4. Waste Regulation monthly data file loaded into a transactional fact table

The February file contains all the 17,000 January entities plus 15,000 entities that report in February. But the February file also contains corrections for January. In other words, in the February file the waste data for some of these 17,000 January entities might have changed. For example, company A which in January reported waste of 11,000 kg of waste for 2018 calendar year, in February might submitted a correction to change this figure to 11,500 kg. This correction may happen up to 6 months after the submission deadline. So the correction for January data can happen in the July file.

Now we need to decide whether transactional fact table is the right approach for this case.

Case 2 Periodic vs Transactional
Figure 5. Comparing Transactional Fact Table and Periodic Snapshot

If we build this fact table as a periodic snapshot fact table, we will have every version of the data. We will have the January version when Entity A was 11,000 kg, and we will also have the February and March version when entity A was 11,500 kg.

If we build it as a transactional fact table, we will only have the latest version.

From my experience many people simply go for the snapshot model because of “just in case”. In case we need the January version.

The other reason, which is more valid, is trace-ability. If we use a transactional fact table, the report we produced in Feb 2019 (based on the Jan data) will have different numbers to the report we produce in Apr 2019 (based on the Mar data). If we use the snapshot model, we can explain the differences, i.e. because in January Entity A was 11000 kg, not 11500 kg.

So in case 1 we are dealing with “incremental” monthly data files, whereas in case 2 we are dealing with “accumulated” monthly data files.


Next Page »

Blog at