Here is a simple way to use Python in Excel which most would like since Python is a very quick and easy way to get things done.
Pre-requisite:
MS Excel
Excel Python
Windows extension for python
There are many tutorial which guides you to how this can be done. Please refer to the link in the reference.
After installation, you may encounter a bunch of issues, please refer to the troubleshooting page, I managed resolve everything from information found in this page.
You will see the Excel Python Tab available in Excel:
There are only 2 buttons:
1) Setup ExcelPython: Gets you started by creating a Python file and link it to your current workbook
2) Import Python UDF: Extract Python functions you created to Excel so you can use them directly without writing any VBA.
Click the first button to setup things. You will find a <worksheetfilename>.py file created in the same folder. What you have to do is to code functions in that Python file. E.g.
Workbook name: //path/Book1.xlsm
Associated Python file: //path/Book1.py
Next,click on the 2nd button to import the functions you have written and you are done!
Now you just need to use the same function name to execute your python functions.
Please find the attached example here.
Reference:
https://github.com/ericremoreynolds/excelpython/blob/master/docs/tutorials/Addin01.md
Saturday, May 26, 2018
Friday, May 26, 2017
FE Trivial Part 1 - Relationship between Caplet and Option on Zero Coupon Bond
Caplet Payoff:
$X_{t_i}= N.\tau_i.Max(0,L(t_{i-1},t_i)-K)$
Given that forward rate:
$\tau_i.L(T_{i-1},T_i) = \frac{1-P(T_{i-1},T_i)}{P(T_{i-1},T_i)}$
Caplet Payoff:
$X_{t_i}$
$= N.\tau_i.Max(0,L(T_{i-1},T_i)-K)$
$=N.Max(0,\tau_i.L(T_{i-1},T_i)-K.\tau_i)$
$=N.Max(0,\frac{1-P(T_{i-1},T_i)}{P(T_{i-1},T_i)}-K.\tau_i)$
Discounting to today:
Caplet Price:
$= P(T_{i-1},T_i).N.Max(0,\frac{1-P(T_{i-1},T_i)}{P(T_{i-1},T_i)}-K.\tau_i)$
$= N.Max(0,1-(P(T_{i-1},T_i))(1+K.\tau_i))$
$= (1+K.\tau_i).N.Max(0,\frac{1}{(1+K.\tau_i)} - P(T_{i-1},T_i))$
$= N_{zero}.Max(0,K_{zero} -S_{zero})$
This the pricing of a put option on a Zero Coupon Bond with
Notional: $= (1+K.\tau_i).N$
Strike:$=\frac{1}{(1+K.\tau_i)}$
This will be important when we compare with Hull White 1 Factor Zero Coupon Bond Put European Option. Under the Hull White 1 Factor model, the close form solution is:
$Put_{zero} (t_0,t_1,t_2,K_{zero}) = K_{zero}P(t_0,t_1)\phi(-h+\sigma_{zero})-P(t_0,t_2)\phi(-h)$
Where
$\sigma_{zero}= \sigma_{black}\sqrt{\frac{1-e^{-2a(t_1-t_0)}}{2a}}B(t_1,t_2)$
$h=\frac{1}{\sigma_{zero}}ln{\frac{P(t-0,t_2)}{P(t_0,t_2)K_{zero}}+\frac{\sigma_{zero}}{2}}$
source
Given that forward rate:
$\tau_i.L(T_{i-1},T_i) = \frac{1-P(T_{i-1},T_i)}{P(T_{i-1},T_i)}$
Caplet Payoff:
$X_{t_i}$
$= N.\tau_i.Max(0,L(T_{i-1},T_i)-K)$
$=N.Max(0,\tau_i.L(T_{i-1},T_i)-K.\tau_i)$
$=N.Max(0,\frac{1-P(T_{i-1},T_i)}{P(T_{i-1},T_i)}-K.\tau_i)$
Discounting to today:
Caplet Price:
$= P(T_{i-1},T_i).N.Max(0,\frac{1-P(T_{i-1},T_i)}{P(T_{i-1},T_i)}-K.\tau_i)$
$= N.Max(0,1-(P(T_{i-1},T_i))(1+K.\tau_i))$
$= (1+K.\tau_i).N.Max(0,\frac{1}{(1+K.\tau_i)} - P(T_{i-1},T_i))$
$= N_{zero}.Max(0,K_{zero} -S_{zero})$
This the pricing of a put option on a Zero Coupon Bond with
Notional: $= (1+K.\tau_i).N$
Strike:$=\frac{1}{(1+K.\tau_i)}$
This will be important when we compare with Hull White 1 Factor Zero Coupon Bond Put European Option. Under the Hull White 1 Factor model, the close form solution is:
$Put_{zero} (t_0,t_1,t_2,K_{zero}) = K_{zero}P(t_0,t_1)\phi(-h+\sigma_{zero})-P(t_0,t_2)\phi(-h)$
Where
$\sigma_{zero}= \sigma_{black}\sqrt{\frac{1-e^{-2a(t_1-t_0)}}{2a}}B(t_1,t_2)$
$h=\frac{1}{\sigma_{zero}}ln{\frac{P(t-0,t_2)}{P(t_0,t_2)K_{zero}}+\frac{\sigma_{zero}}{2}}$
source
Wednesday, February 22, 2017
xVA
This article is to document what I have learned about XVA. I will first layout a few idea and continue to improve this as I find out more. Source of these information are from books such as
1 ) The XVA Challenge
...
For an introduction, the point of calculating XVA is to find out the various cost of transaction in banks, from inception to maturity. Various stakeholders are involved in this process:
1) Dealers
a. Traders
There are different kind of traders in a bank, some are just doing flow business, others are doing proprietary trading. Typically, the head of desk will treat the desk trading business as any other business. He/She will consider the cost of operating this desk. XVA will form part of the operation cost.
b. Structurers
The trades done by structures are huge chunky trades as compared to traders. These are typically longer term as well. The counterparties involved are typically entities such as fund house, security firms and corporates. These counterparties have significant credit risk compared to interbanks trades. Therefore, XVA will form an important cost to the desk.
2) CVA Desk
This desk is responsible for hedging the CVA (one part of XVA) which is directly linked to the credit risk of counterparties. Hedges are typically done using CDS or proxy trades which is correlated to counterparties. Traders and Structurer will pay CVA cost to this desk and as such the credit risk associated with the trade is taken to be hedged out with this desk. This desk will be interested in the CVA Greeks as they are required to managed the CVA according to the movement in the market.
3) Risk Managers
This function is involved in computing, monitoring and reporting the exposure of the bank to management and regulators.
XVA Components
CVA
Simpliest among these, just go Google
Simpliest among these, just go Google
DVA
The flip side of CVA.
The flip side of CVA.
FVA
KVA
For every trade done in bank, there is a capital charge associate with it. These charges are amount which banks are required to set aside for mitigating counterparty credit risk. In the past, banks ignore this cost and uses quick and dirty way such as using minimum charges to transactions. Today, banks have became more sophisticated and implements KVA is to properly price the cost of setting aside such Capital for regulatory purposes.
3 factors to Capital Requirement for OTC Derivatives
- Default risk capital charge
Potential default charge of counterparty i.e. CCR
- CVA capital Charge
CVA sensitivity due to movement in Credit Spread
- Market Risk Capital Charge (insignificant since regulator has implement rule to reduce this)
These are capital charges arises from doing hedges.
- Capital Charge on exposure to CCP is very little.
Formula
KVA =-$\sum_{i=1}^{m} $EC(t_i)xCC(t_i)X(t_i-t_(i-1))XS(t_i)
For every trade done in bank, there is a capital charge associate with it. These charges are amount which banks are required to set aside for mitigating counterparty credit risk. In the past, banks ignore this cost and uses quick and dirty way such as using minimum charges to transactions. Today, banks have became more sophisticated and implements KVA is to properly price the cost of setting aside such Capital for regulatory purposes.
3 factors to Capital Requirement for OTC Derivatives
- Default risk capital charge
Potential default charge of counterparty i.e. CCR
- CVA capital Charge
CVA sensitivity due to movement in Credit Spread
- Market Risk Capital Charge (insignificant since regulator has implement rule to reduce this)
These are capital charges arises from doing hedges.
- Capital Charge on exposure to CCP is very little.
Formula
KVA =-$\sum_{i=1}^{m} $EC(t_i)xCC(t_i)X(t_i-t_(i-1))XS(t_i)
Margin Valuation Adjustment (MVA)
As the name suggest, this adjustment is related to margin associated with trades. Margin are charged to protect against default, so it is expensive and not re-hypothecated; it is regarded as a separate amount.
It consist of:
1) Initial Margin (and other financial resources required by Central Counterparty (CCP)
When a bank (Clearing Member) deal with counterparty via CCP, they are required to post an Initial Margin (IM) so that if they default, this margin can help buffer against the lost suffered by CCP.
These are cost to banks as the interest paid by CCP are less than the funding cost required.
Questions:
What benchmark is used by CCP to pay clearing members for IM?
2) Bilateral IM
This is required when both parties are required to post initial margin to each other.
3) Contingent IM
How are IM calculated?
IM calculation are determined by using VAR or expected shortfall. This means they need to specify % confidence interval and time horizon.
MVA =-$\sum_{i=1}^{m} $EIM(t_i)x(FC(t_i)-S_im)X(t_i-t_(i-1))XS(t_i)
Where $EIM = discounted expected IM, $FC is funding cost and $S_IM is the remuneration from posting IM.
EIM are calculated using simulation over 99% confidence interval with 10 days horizon.
Comparison with FCA
- MVA is the funding cost associated with worst-case movement of portfolio during a 10 day horizon. This is due to the fact that the trade is collateralized and the 10 days is to cover the situation where there is a default discovered only after 10 days, by which the market would have moved.
-FCA is the funding requirement over the life of the trade.
Where $EIM = discounted expected IM, $FC is funding cost and $S_IM is the remuneration from posting IM.
EIM are calculated using simulation over 99% confidence interval with 10 days horizon.
Comparison with FCA
- MVA is the funding cost associated with worst-case movement of portfolio during a 10 day horizon. This is due to the fact that the trade is collateralized and the 10 days is to cover the situation where there is a default discovered only after 10 days, by which the market would have moved.
-FCA is the funding requirement over the life of the trade.
Questions:
What is the flow of calculating MVA?XVA consists of a few components summarized in the table below:
Obtained from the book: The XVA Challenge
Sunday, May 29, 2016
Using C# in Excel Part I
In the typical work environment, it is very common for non-programmer to try to use VBA to create process automation. And it is no doubt a fast way to implement automation with the least computing knowledge. However, when the complexity is high and coupled with high volume, this will significantly slow down the PC and creates bad user experience. Especially when we are doing it for another user, we might wonder if there is a better solution?
In this post, I explore how I can use C# to code automation functions and to implement it onto VBA. This is nothing new so all the information required was obtained from other experts online. Specifically, I got most of the information here.
Step 1:
Using Visual Studio Community 2015, create a class library:

Step 2:
Communication with VBA require the code to be in "COM Library", so to do this
a) You have to check "Make Assembly COM-Visible" checkbox under
Project -> Properties -> Assembly Information


b) Next, we will need to register it so that VBA will be able to recognize this when we start coding in VBA. But you also won't want to register all the library you developed on the developing machine as it will make your PC very messy. So I will come back to this setting again later to explain how to remove it.
Under the same property window, go to the build tab, Project -> Properties -> Build.
Check the ‘Register for COM interop’ checkbox.

Step 3:
The setup is completed and you can start writing your code. The following is a simple code to output a string:
Step 4:using System;using System.Collections.Generic;using System.Text;namespace DotNetLibrary{public class DotNetClass{public string DotNetMethod(string input){return "Hello " + input;}}}
Compile and start using in VBA! For example, we now try to use Excel to call the above method.
In Excel, enter the VBA programming window by pressing ALT+F11. You will find that library you created under Tools -> Reference. In this case, the library is called blog.

To access the DotNetMethod, you can invoke by using the following VBA Code:
Sub test()Dim clest As New DotNetClassDim test As VariantMsgBox (clest.DotNetMethod("ABC"))
End Sub
Run the macro ("F5") and you will see the msgbox:

Step 5:
Up till now, what you have seen how to get to use functions in VBA in your own PC. But suppose you want to develop it on your own PC and implement it onto another PC, how can you do it?
So starting from Step 2b, we don't really need to check the "Register for COM Interop" because what we really need is just the DLL file. But now that we checked it, how can we remove it? This is simple, we just need to uncheck and compile your project again and it will be unregistered.
So once you unregistered, whatever you compile will not appear on VBA Reference. You will need to take the DLL and copy to the target PC and start the registration manually.
Register:
To register you will need to use "regasm" function from Visual Basic Command Prompt. You can easily access this by typing "Dev" after pressing the "Window" key:

Navigate to your project directory containing the DLL file and now you are ready to use the "regasm" function (assuming the name of your dll is "dllname"). Type the following to create the ".tlb" required for VBA to recognize your DLL file.
regasm /tlb dllname.dll
After typing the above command, you will see that the library will appear in the same place mentioned in Step 4,
If you want to unregister, you can type the following command:
regasm /u dllname.dll
As you can see, all these registering are not very transparent to the developer on what exactly is happening. So there will be times where you are not able to unregistering. And when that happens, a quick way is to open your project and repeat what is mentioned at the beginning for Step 5, i.e. check option -> compile, uncheck option -> compile. This will let Visual Studio do the unregistering for you.
If you want a quick start, you can use the sample project here. Enjoy coding!
Saturday, September 26, 2015
Charting in R - Part I
The toughest step to doing things like quantitative analysis for trading and backtesting is to understand how to use the tools available in the market. The choices available are as follows:
Excel allows you to see and manipulate data easily but you cannot see trend properly. For example, if you wish to chart data in Excel, this is what you will get:
This graph looks acceptable for simple presentation. But if you want to do analysis, you would want to be able to add a complex indicator easily. In Excel, you can only do that by manipulate all the data in excel and plot another graph on it. To do complex analysis of data it will be much better to do it with scripting API available in the market. If you know your stuff, you can do things pretty fast. But it takes a hell lot of effort to even get started. To illustrate the advantage of using API, the following is created using GOOGLE prices and R.
As someone who had tried both Python and R, my opinion is that the later is a better tool to do charting. So I documented some tips to get you started on R.
What you need to install
R(Here you will find the latest version but I am using version 2.15)
Quantmod (To quickly install, follow instruction here to download and install all that you need)
Once you are done, you can quickly load data with the following sample code (modified from code taken from here) and data.
Code:
library(quantmod)
require (zoo)
dataFile_strip2 <- "testinput.csv"
dataDir <- "C:/Users/Ken/Documents/R/CSV Data"
file2 <- paste(dataDir,"/",dataFile_strip2,sep="")
zz <- read.zoo(file2,header = TRUE,sep=",",index.column=1, format = "%d/%m/%Y %H:%M")
xx<- as.xts(zz)
chartSeries(xx)
testinput.csv:
DateTime,Close,High,Low,Open,Volume
12/08/2015 21:30:00,112.53,112.61,112.5,112.5,877727
Other Reference:
https://cran.r-project.org/web/packages/zoo/vignettes/zoo-read.pdf
- Excel
- R
- Python
- C/C++
Excel allows you to see and manipulate data easily but you cannot see trend properly. For example, if you wish to chart data in Excel, this is what you will get:
This graph looks acceptable for simple presentation. But if you want to do analysis, you would want to be able to add a complex indicator easily. In Excel, you can only do that by manipulate all the data in excel and plot another graph on it. To do complex analysis of data it will be much better to do it with scripting API available in the market. If you know your stuff, you can do things pretty fast. But it takes a hell lot of effort to even get started. To illustrate the advantage of using API, the following is created using GOOGLE prices and R.
As someone who had tried both Python and R, my opinion is that the later is a better tool to do charting. So I documented some tips to get you started on R.
What you need to install
R(Here you will find the latest version but I am using version 2.15)
Quantmod (To quickly install, follow instruction here to download and install all that you need)
Once you are done, you can quickly load data with the following sample code (modified from code taken from here) and data.
Code:
library(quantmod)
require (zoo)
dataFile_strip2 <- "testinput.csv"
dataDir <- "C:/Users/Ken/Documents/R/CSV Data"
file2 <- paste(dataDir,"/",dataFile_strip2,sep="")
zz <- read.zoo(file2,header = TRUE,sep=",",index.column=1, format = "%d/%m/%Y %H:%M")
xx<- as.xts(zz)
chartSeries(xx)
testinput.csv:
DateTime,Close,High,Low,Open,Volume
12/08/2015 21:30:00,112.53,112.61,112.5,112.5,877727
Other Reference:
https://cran.r-project.org/web/packages/zoo/vignettes/zoo-read.pdf
Friday, April 3, 2015
Using C++ and VBA in Excel - Part II
One way of doing this is as stated in my previous post. But many beginner in C++ would be daunted by the amount of basics in Computing required to understand why it work. To simplify this process, we can use XLW to implement wrapper easily. The only requirement is to know basic C++ and a simple 3 step process.
Step 1
First, you will need Microsoft Visual Studio and install XLW onto your PC. Use Template Extractor:
Choose the Visual Studio version correctly. Note that if you are using Visual Studio 2012 you will need to choose VC10 instead of VC12.
Step 2
The template you just created is a skeleton VS project which allow you to develop XLL. Once you fire up template.sln, you will notice that the project is setup nicely for you to start development.
As an example, I did a test function that return the square of a number:
As usual, for every function you create in C++ you will need to declare it in the header. But this time, you will need to declare it onto cppinterface.h. This is the most important step you need to do in C++ and you are ready to compile the project.
Step 3
The compilation will create the XLL file and you will be able to find it in the output folder. In this case, I am using debug mode and "Template.xll" will therefore appear in the debug folder. Launch "Template.xll" and you should not encounter any error, if so then there must be an error in the compilation process. If there are no error then you can create a new worksheet and start using the "helloworld" function you just created.
Step 1
First, you will need Microsoft Visual Studio and install XLW onto your PC. Use Template Extractor:
Choose the Visual Studio version correctly. Note that if you are using Visual Studio 2012 you will need to choose VC10 instead of VC12.
Step 2
The template you just created is a skeleton VS project which allow you to develop XLL. Once you fire up template.sln, you will notice that the project is setup nicely for you to start development.
As an example, I did a test function that return the square of a number:
As usual, for every function you create in C++ you will need to declare it in the header. But this time, you will need to declare it onto cppinterface.h. This is the most important step you need to do in C++ and you are ready to compile the project.
Step 3
The compilation will create the XLL file and you will be able to find it in the output folder. In this case, I am using debug mode and "Template.xll" will therefore appear in the debug folder. Launch "Template.xll" and you should not encounter any error, if so then there must be an error in the compilation process. If there are no error then you can create a new worksheet and start using the "helloworld" function you just created.
Tuesday, October 7, 2014
Executing an executable from VBA
For people in the software industries such as consultants, developers and even managers, they will very often need to handle different versions of software. Many a times, these versions are stored in different places. This means we will need to memorize these directories and every time we need to access them, we will need to navigate to these directories. The best way to overcome these is to tabulate the versions in Excel. But it is insufficient as it we are not able to start the software from the tables in excel natively.
By using VBA you can do this with the "Shell" command. The problem is with this is that you can only execute files that has no dependency on the folder you are executing it from. This means the environment paths and parameters needs to be setup correctly in Windows.
To overcome this limitation, I combined what I posted previously to build a table having the ability to execute a software from Excel. Instead of building your own DLL, what you need is to use the existing DLL (Refer to here for more details on how this is done in VBA):
Public Declare Function ShellExecute Lib "Shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
By declaring this you are effectively using the "ShellExecute" library from Shell32.dll to execute lpFile from lpDirectory.This will allow user to have more flexibility in building UI that will execute files upon clicking in VBA. An example of using the above is as follows:
RetVal = ShellExecute(0, "open", "C:\folder\client.cmd", "<arguments>", _
"C:\folder\", SW_SHOWMAXIMIZED)
By using VBA you can do this with the "Shell" command. The problem is with this is that you can only execute files that has no dependency on the folder you are executing it from. This means the environment paths and parameters needs to be setup correctly in Windows.
To overcome this limitation, I combined what I posted previously to build a table having the ability to execute a software from Excel. Instead of building your own DLL, what you need is to use the existing DLL (Refer to here for more details on how this is done in VBA):
Public Declare Function ShellExecute Lib "Shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
By declaring this you are effectively using the "ShellExecute" library from Shell32.dll to execute lpFile from lpDirectory.This will allow user to have more flexibility in building UI that will execute files upon clicking in VBA. An example of using the above is as follows:
RetVal = ShellExecute(0, "open", "C:\folder\client.cmd", "<arguments>", _
"C:\folder\", SW_SHOWMAXIMIZED)
Subscribe to:
Posts (Atom)