A Simple CVA Example

In my blog post two weeks ago I posted some figures with paths and exposures. Today I want to give a short example how Monte Carlo simulation can be used for the calculation of the CVA of an option. To keep things simple we will assume that only the counterparty can default (we will calculate the unilateral CVA).

The formula for unilateral CVA is given by


where LGD is the loss given default, i.e. one minus the recovery rate, DF is the discount factor (we assume a deterministic yield) and PD is the default probability of our counterparty. The term EE(t) stands for the expected exposure at time t. Exposure describes the amount of money that the counterparty owes us if it defaults at time t. As we only want to calculate a single instrument CVA we do not need to take into account netting. Furthermore we assume that o collateral agreements are in place. We can then calculate the positive exposure


where V(t) is the mark to market value of the

instrument a time t. As we model the underlying risk factor of the instrument by a stochastic process, V(t) and therefore also E(t) are random variables.

Equity paths: Black Scholes model with constant volatility.


We can calculate the expected exposure EE(t) by calculating the expectation value over all realisations of our random variable E(t). For an option the value of a trade at time t is simply given by


where K is the strike price. 

E(t) for the call option with strike K=100


EE(t)


Having calculated the exposure we put everything together with a discretised version of formula one

.





How Long Can Faster, Thinner, Smaller, Bigger than Bigger, … Be Innovative?

Yesterday, I experienced the Apple keynote 2014 on my iMac. It is amazing, how perfect its was staged again.

Apple wants to make things for those, who see things differently. Again and again and again …

In search of perfection?

And this made me brooding. Industrial work does what it did yesterday tomorrow, but faster, preciser, thinner, smaller, bigger, ... cheaper. Only at the lab we are striving to find a breakthrough, new ways to solve new problems, and do new things.

The "iPhone 6" is bigger and thinner? Is this important for those who see things differently? To be honest, although expecting it, I was bit disappointed (at the beginning).

A Watch is not a tool

"Apple Watch". I don't wear a watch, because there are watches all around.

I own the WATCH by Femming Bo Hansen. It's minimalist. It's represented at the Museum of Modern Art, NY. And, what a shame, I have put it into a drawer (and nearly forgot it).

A watch is not a tool - it clocks our life.

A computer is not a tool either

Hold on, Apple Watch is a computer on a wrist, and a computer is not a tool either - it is a universal machine to build tools for many usages.

I started my professional work at the stone age of IT. Since then people said subsequently:

"Only a mainframe is a computer" - and then the mini computers entered the market
"Only a mini computer is a computer" - and then the micro computers entered the market
"Only a micro computer is a computer" - and then the workstations entered the market
"Only a workstation is a computer" - and then the PC entered the market
"Only a PC is a computer" - and then the tablet computers entered the market
"Only a tablet computer  is a computer - and then ….?

My first professional work challenge was the migration of an mainframe based system for offline CNC machine programming ("APT") to the first mini computer ("General Automation"). But I quickly realized: this is crazy - and I built a completely new system instead. Exploiting the capabilities of a mini computer. Like the first computer graphics tools … I built a new CNC programming language and all the algorithms to implement it.

And this kind of reinvention's happened again and again and again.

When things became smaller, connectivity became more important. "Sun" said: the network is the computer. And now we have entered the "cloudy" days.

But still front-end devices become smaller and more intelligent. In a not so far future we may have beer glasses, ... that are computers?

However, one of the challenges for a "wrist computer" is the interaction paradigm … that at the other hand - if solved adequately - enable

New uses

It seams Apple wants to take the watch to occupy new market segments, like Health and Fitness. By making things computational - transforming information into knowledge - they can provide better real time advice. If you are running, bicycling, climbing, … you don't want to wear a tablet computer (a bigger than bigger  smartphone), in a race you want to optimize your risk: go to the limit but not across.

Summarizing, I think, this Apple announcement has been underestimated. It may be the begin of making massive information computational - first on a smaller scale.

Maybe, it was not a keynote that shook the tech industry, like those with the announcements of  iMac, iPod, iPhone, iPad, …

What has this all to do with quant finance?

IMO, the quant finance platform and system providers have developed powerful technologies that all are tied together to more or less comprehensive valuation-, portfolio- and risk management solutions or development systems. From professionals for professionals. Following the regulatory framework that reduces the optionality and introduces immense complexity to the valuation and data management  space.

Less effort is applied to explain, say, complex financial concepts to non experts. Using new description and visualization techniques explaining when (and why) an investment will become unhealthy. In an offline (or semi-online) simulator to get more insight into the possible optimization of risk and in the real investment and capital management cycles.

It's not so much about the innovativeness of the smart devices, but their paradigms of interaction …

I confess, this is also challenge for us UnRiskers. Health and Fitness of the financial system … Nothing for the wrist, but for a tablet compute and a bigger than bigger smart phone. We have implemented quite complex mathematical schemes on them … and we have clients and partner who use them for tailored solutions, but ….

p.s. I did not take in account the marketing here: is Apple Watch placed as a form of identity? I would not do it that way. It was producing too less volume and no change. However, the reaction on the announcement was quite surprising ….

Some heavy math in local vol calibratrion

Last week, I plotted the results we obtained for local vol by UnRisk's calibration engine.

To obtain such results, you need some serious mathematics. And this is exactly what we did.

In an abstract setting, we want to solve a nonlinear equation F (x) = y between Hilbert spaces X and Y. (Here: x is the parameter function of local volatility acting on two-dimenstional space (S,t). F is the operator that maps any local volatility function to the two-dimensional surface of call prices (K,T). The right hand side y itself (the call price function for the true local vol) cannot be measured but it is noisy (with noise level delta), and available only for certain points.

Instead of solving F(x) = y_delta, Tikhonov regularization solves

  
In the 1990's Engl, Kunisch, and Neubauer proved that, in this abstract setting, nonlinear Tikhonov regularization converges if
(a) the operator F is continuous,
(b) the operator F is weakly sequentially closed, and
(c) alpha > 0 and delta^2 / alpha -> 0.

Condition (b) might look unfamiliar. The reason for which we have to use the weak topology is that in infinite-dimensional settings, bounded sets in the strong topology need not have convergent subsequences.

For any parameter identification problem, where the solution is theoretically inifinite-dimensional, we have to analyse if the above conditions on the operator are satisfied. For local volaitility, this was carried out by Egger and Engl (Tikhonov Regularization Applied to the Inverse Problem of Option Pricing: Convergence Analysis and Rates, Inverse Problems, 2005).

At UnRisk, we do the math and the numerical implementation. This makes us deliver robust solutions. Can you say this for your system as well?

Pygmalion At Work

The myth of Pygmalion  is about the Greek sculptor who fell in love with a statue he has carved.

The Pygmalion Effect

is about expectations that drive performance. In a workplace it should lead to a kind of co-evolution: leader expectations of team members may alter leader behavior. Like, the more a team member is engaged in learning the more the leader expects. In turn, the team member participates in more learning activities … and leader set learning goals and allow for more learning opportunities.

Placebo?

This effect may help leaders leading, teachers teaching, learners learning … But it's difficult to measure.

However, I am interested in the original myth:

Flip motivation

Instead of doing-what-we-love, we-love-what-we-do. Yes, we want to do things we are good at, but this is not enough. It's all about the results. Create values, solve problems, leverage skills, … do things that matter for and with those who care.

(In the ancient Greek mythology the sculpture came to life - Aphrodite had granted Pygmalion's wish)

What drives us

Years ago, we have unleashed the programming power of UnRisk enabling quants to love what they do, without needing to do all the plumbing. With UnRisk, quants can programmatically manipulate deal types with hybrid contract features, models and data and intelligently aggregate the massive risk data the UnRisk FACTORY calculates.

In 2001, when we looked at the available quant finance technologies, we found products that were too black-box, too rigid to introduce new features, too service dependent to build our ideas atop.

Because we saw a need for a more flexible technology, we developed UnRisk. We wanted to provide solutions that are development systems in one. To make them bank-proof, we provided solutions first and then offered the technology behind.

We've much more ideas than we can build

This is one reason why we love partnering. We believe in quant-powered innovation on a higher level. An we offer all type of programs that make partnerships profitable to our partners - and us.

How good is the description of term structure movements using PCA?

The movements of the term structure of interest rates can be explained quite well using only a few basic factors, like a parallel movement of the curve (shift), a flattening or steepening or of the curve (twist) and a reshaping of the curve (butterfly). The factors, which can be calculated as the eigenvectors of the Gramian matrix of interest rate movements, provide a very powerful framework, since they accelerate the calculation of the historical VaR for interest rate derivatives (which is a very time consuming task, if a full valuation approach is used) significantly.
The following questions occur:

  • How good is the explaination of interest rate movements using only a few factors?
  • How many factors do we have to use to get a good approximation?
  • How stable are the principal components over time?
  • Does the shape of the principal components depend on the currency?
  • How large is the approximation error of a historical VaR calculation using PCA compared to a full valuation approach?
Performing a principal component analysis (PCA) on the weekly changes of historical EUR yield curve data (between 2000 and 2007) given on 16 curve points (1W,3M,6M,9M,1Y,2Y,3Y,4Y, 5Y,7Y,10Y,15Y, 20Y,25Y, 30Y,50Y), the principal components have the following form
 

As expected, the first three factors describe a shift, twist and butterfly movement of the curve. 
In my next blog(s), I will try to find the answers to the questions above....

Do I Need A Cloud To Let My Business Shine?

In the current technology climate computer infrastructure is cloudy and lightning-fast. Ideal to mine big data and transform them into big insight ….?

Recently, I found this article in RBS Insight hub: How the cloud will reshape transaction banking. I have no doubt, this makes perfect sense for many transaction-oriented systems.

Then I read

What is cloud computing?

Cloud computing lets people use the internet to tap into hardware, software and a range of
related services on demand from powerful computers usually based in remote locations. 
 
Successfully enabling the widespread adoption of cloud computing could add EUR 250 billion to European GDP by 2020, thanks to greater innovation and productivity, according to research conducted by International Data Corporation on behalf of the EC. Nearly four million new jobs could be created as a result.
This would amount to more than 3.8 million new jobs, although this number does not include jobs lost to cloud-related business reorganisations and productivity gains.
How can one make such a forecast?

Is the cloud what risk managers should be thankful for?

Over the years regulatory and business requirements have driven financial institutions to take leading positions in technology, implementing new sophisticated features and automated analytics solutions that are widely accessible.

UnRisk has all technologies to run at a cloud - for development we offer webUnRisk, and the UnRisk FACTORY has a web front-end. Both can be seamlessly combined. But, which clouds run our advanced technologies to make our business shining?

But also due to the data and security issues, I rather believe advanced risk management systems will run on "on-site of financial institutions clouds", providing access via the intranet and selected clients, business partners, … There we take care that our technologies run.

However, Quant jobs will not end in a cloud. Nor will ours.

Local Volatility by Regularization

Two weaks ago, I applied some data smoothing techniques to improve the results of Dupire's formula when the data are noisy. The quality of the results improved slightly, but not completely satisfying.

What would we like to obtain?
On the one hand, the model prices for the forward local volatility problem (e.g. by finite elements) should fit the (noisy) market prices reasonably, on the other hand, the local volatility surface should not exhibit severe oscilations. It should be as smooth as possible and as unsmooth as necessary to fit the data.

Identifying local volatility is, at least in infinite dimensional setting (you would know the call price for any (K, T)-combination (K is strike, T is expiry)) an ill-posed problem. This means that arbitrarily small noise (remark; if of sufficient high frequency) can lead to arbitrarily large errors in the solution.  And it is a nonliner problem, which makes it more complicated than, e.g. curvefitting in a Hull-White-setting.

The technique to overcome these stability prblems (or: one of the techniques) is Tikhonov regularisation. The following plot shows the result we obtain by regularization on the same data as we used in the presmoothing example.
 
 
Next week, I will have a closer look on the theory behind this improvement.

Switzerland - The Antifragile

Feb-2008 I reviewed an innovation project under the sixth framework program of the European Commission. Three days at the  Research Institute of Martigny, CH.

It's a beautiful high-alpine region, so I decided to pack my cross country skis into the car and stayed at a nice small Swiss Lodge hotel in Champex-Lac.

The views into the highest part of the Alps are stunning, the cross country ski tracks go through the natural beauty and are well diversified for all risk levels, ...

As usual, when selecting a hotel, I went through the menus and wine lists of the restaurants. At the selected I found some outstanding entries of wines from the Valais region. But I knew, there are this rare wines from Visperterminen. The highest vineyards in Europe. So high that only a 300-days-sun-a-year microclimate makes it possible to grow wine. I find Chanton the top makers. Their rarities include Heida, Lafnetscha, Himbertscha, … whites of autochthonous grapes. They are not only rare, but outstanding.

I called the restaurant owner and asked, whether she could help me getting those Chanton specialities. "Let's see". At the first evening when I took place at the large window of the restaurant with the most stunning view ... "this is our special wine list for you", she said smiling. It contained all the Chanton rarities … Consequently, I sat there every evening of my stay …. and I packed a selection of the remaining bottles into my car for take away (to Austria).

This is Switzerland - they like to do business, serve clients (who care) and do it with understatement.

Here is a great blog post: Daniel Davies about Switzerland. It's a "foreign view" - he got to know the Swiss when working for Credit Suisse for five years. The sum of all my visits were less long (fortunately, quite a lot UnRisk related), but I agree.

In Switzerland law is changeable and it has a long direct democratic tradition to do that by relying on the wisdom of the crowds. But, Switzerland has also a long tradition of hospitality to original thinkers. To NN Taleb "long in history" means (most probably) "long in the future". An important sign that a political or socio-economic system belongs to the "Anifragile".

p.s. Shhh, now I can order Chanton's rarities online … and get info about more Swiss wine specialities from Chandra Kurt ….

Best Poster Award for Adaptive Optics

Last week, at the IPTA 2014 conference in Bristol (where I tried to speak about math without formulas), there was additional mathematical meat put on the bones by colleagues from the Industrial Mathematics Institute.

Daniela Saxenhuber won a best poster award for her conference poster "A fast reconstruction method for complex adaptive optics systems". Congratulations to her!

The Best of Both Worlds, Part II

In the first part of this blog episode, we gave an overview of the two interfacing technologies that the Wolfram Language provides for calling C++ programs, MathLink and LibraryLink. MathLink’s main advantage is its robustness, whereas LibraryLink offers high-speed and memory efficient execution. Providing support for both technologies at the same time, which is desirable from a software engineering perspective, requires considerable work from developers.

And now the conclusion

It turns out there is a way to have the best of both worlds with little effort. The idea is to replace the two separate wrapper functions that are needed for MathLink and LibraryLink with a single universal wrapper function, which can be easily adapted to both interfacing technologies. In this blog post we’ll rewrite the add_scalar_to_vector integration example from the first part using such a universal wrapper function.

First let’s recap the LibraryLink based wrapper function from the first part:

EXTERN_C DLLEXPORT int AddScalarToVectorLL(
    WolframLibraryData libData, 
    mint Argc, MArgument* Args, 
    MArgument Res)
{
    ...
}

The wrapper function conforms the MArgument signature required by LibraryLink. The dynamic library generated from that wrapper function was loaded into the Mathematica kernel session with LibraryFunctionLoad:

AddScalarToVectorLL = LibraryFunctionLoad["AddScalarToVector",
    "AddScalarToVectorLL", {{Real, 1}, Real}, {Real, 1}]

Your culture will adapt to service ours

LibraryLink also supports an alternate signature for wrapper functions that is based on the data type MLINK. This type represents a MathLink connection that lets you send any Wolfram Language expression to your library and get back any Wolfram Language expression as a result. Let us rewrite AddScalarToVectorLL with the MLINK signature:

EXTERN_C DLLEXPORT int AddScalarToVectorLL(
    WolframLibraryData libData,
    MLINK mlp)
{
    return AddScalarToVector(mlp);
}

We have moved the body of AddScalarToVectorLL to a new function AddScalarToVector which represents our universal wrapper function:

int AddScalarToVector(MLINK link) {
    int argCount;
    if (!MLTestHead(link, "List", &argCount) || argCount != 2)
        return LIBRARY_FUNCTION_ERROR;

    double* list; int length;
    if (!MLGetReal64List(link, &list, &length)) return LIBRARY_FUNCTION_ERROR;
    typedef std::unique_ptr<double, std::function<void(double*)>> Real64ListHolder;
    Real64ListHolder list_holder(list, [=](double* ptr) {
        MLReleaseReal64List(link, ptr, length);
    });

    double scalar;
    if (!MLGetReal64(link, &scalar)) return LIBRARY_FUNCTION_ERROR;

    add_scalar_to_vector(list, length, scalar);

    if (!MLNewPacket(link)) return LIBRARY_FUNCTION_ERROR;
    if (!MLPutReal64List(link, list, length)) return LIBRARY_FUNCTION_ERROR;

    return LIBRARY_NO_ERROR;
}

The implementation of the universal wrapper function is straight forward. It uses the MathLink API to read the a vector and a scalar from the underlying link and also writes back the result on the link. A std::unique_ptr with a user-supplied deleter lambda function ensures that the vector read with MLGetReal64List is cleaned up automatically with MLReleaseReal64List when the function returns.

The LibraryLink MLINK signature wrapper function must be loaded into the Mathematica kernel session with a slightly different command:

With[{func=LibraryFunctionLoad["AddScalarToVector",
    "AddScalarToVectorLL", LinkObject, LinkObject]},
    AddScalarToVectorLL[vector: {_Real ...}, scalar_Real] := func[vector, scalar]
]

LibraryFunctionLoad now uses the Mathematica expression LinkObject as a data type, which corresponds to MLINK on the C++ side. To ensure that the native function is invoked with the correct arguments (a vector and a scalar), we setup a regular Mathematica function pattern which calls the native function loaded from the dynamic library.

To use the universal wrapper function from the MathLink executable, we have to make some changes to the MathLink template file we presented in the first part:

:Begin:
:Function:       AddScalarToVectorML
:Pattern:        AddScalarToVectorML[vector: {_Real ...}, scalar_Real]
:Arguments:      { vector, scalar }
:ArgumentTypes:  Manual
:ReturnType:     Manual
:End:

void AddScalarToVectorML(void) {
    if (AddScalarToVector(stdlink) != 0) {
        MLNewPacket(stdlink);
        MLPutSymbol(stdlink, "$Failed");
    }
}

In the data type mapping we now declare the :ArgumentTypes: as Manual, because the universal wrapper function takes care of reading all the arguments from the link. The MathLink wrapper function AddScalarToVectorML simply invokes the universal wrapper with the underlying MathLink connection stdlink. To make MathLink error handling work correctly, we have to return a $Failed symbol if the universal wrapper returns an error.

We wish to improve ourselves

When a new C++ function needs to be integrated into the Wolfram Language, the LibraryLink and MathLink wrapper functions can be copied almost verbatim. Development effort only goes into writing a new universal wrapper function.

What concerns the amount of code we had to write, for the simple function add_scalar_to_vector it does make much of a difference. However, if you have to integrate dozens of C++ functions with long parameter lists, as is the case with UnRisk-Q, a great deal of tedious work can be saved with a universal wrapper function.

Show me the code

You can download a self-contained CMake project which demonstrates how to build a MathLink executable and a LibraryLink dynamic library using a universal wrapper function. You need the following third-party software packages:

  • Mathematica ≥ 8
  • CMake ≥ 2.8.9
  • Clang ≥ 3.1 or GCC ≥ 4.6 or Visual Studio C++ ≥ 2010

The file CMakeLists.txt in the zip archive contains instructions on how to build and run the tests for Windows, Linux and OS X.

Performance

We’ll now evaluate the performance of the different linking technologies presented in this blog episode:

  • MathLink using the universal wrapper function
  • MLINK based LibraryLink using the universal wrapper function
  • MArgument based LibraryLink with the custom wrapper function from part one

We’ll be using the following pseudo test code:

Load external function
Call add_scalar_to_vector 100 times with a list of 10^6 random double values
Unload external function

The actual test code for the different linking technologies can be seen in the file CMakeLists.txt file in the zip archive.

The following chart shows the execution times of the different linking technologies. The results were obtained with Mathematica 10 on a MacBook Pro Mid 2010 running OS X 10.9. The code was compiled with Clang 3.4. The results for Linux and Windows are similar.

Summing up, we can draw the following conclusions, what concerns the communication overhead for integrating a native C++ function into the Wolfram Language:

  • Using a universal wrapper function, you a get a speedup of about 50 percent by moving from MathLink to LibraryLink with almost no additional development effort.
  • An additional speedup of about 50 percent is possible, if you go to the extra effort of writing an MArgument based wrapper function.