SERVING THE QUANTITATIVE FINANCE COMMUNITY

• 1
• 2
• 3
• 4
• 5
• 13

Polter
Posts: 2526
Joined: April 29th, 2008, 4:55 pm

### Using Quantlib

pcaspers, you can use KKT, although note that the solution is at the _saddle_ point of the Lagrangian function (_not_ at its optimum):http://eaton.math.rpi.edu/faculty/Mitch ... l.htmlThus, I wouldn't expect the "just give the Lagrangian to an optimizer" approach to work in general.Perhaps you can consider the augmented Lagrangian method:http://ab-initio.mit.edu/wiki/index.php ... _algorithm

pcaspers
Posts: 695
Joined: June 6th, 2005, 9:49 am

### Using Quantlib

thanks for these references, Polter.for at least part of the problems occuring in quantitative finance (like a parameter being positive or bounded) it seems that often ad hoc transformations can be (and are ?) successfully used to rewrite the respective problem in unconstrained form.
Last edited by pcaspers on March 29th, 2014, 11:00 pm, edited 1 time in total.

Cuchulainn
Topic Author
Posts: 61184
Joined: July 16th, 2004, 7:38 am
Location: Amsterdam
Contact:

### Using Quantlib

QuoteOriginally posted by: pcaspersQuoteOriginally posted by: CuchulainnCould we we write the problem in Lagrange multiplier form to get an unconstrained and then apply DE? Then we can accomodate more general constraints as well? When you say "the problem" are you referring to a specific one or speaking generally ?afaik Lagrange multiplier apply to constraints F( X ) = 0. Does it extend to F( X ) < c ?I am looking at (3) Boundary Constraints in DE at the moment. In this case, instead of a constraint class I initialise the population matrix (NP X ND) with U(L,R) for eachg individual in the population in my C++ code. Since we want a global minimum (multi-modal problems) we use DE with enough mutation etc. A good test is Rosenbrock<N> (when 4 <= N <= 7 we have 1 global and 1 local minimum). I have tested to N = 50 to get (1,1,....,1).RosenbrockThe other constraints are:(1) inequality(2) equality(2) (and indeed (3) is a special case of (1) and the Penalty Method (as in American option PDE) can be used, next. Then I (nor QL) would not need constraint classes and make things a bit easier.For the moment, G2++ (to take a random example) has constraints of type (3) only?(?)A question is : does QL have code for the C++ cost function that I can bind to with my DE code? (it will save me writing it all)The signature is double Cost(const "std::vector-compatible-class"& arr ) ( I use uBLAS). When my code is complete I can send it to QL if you like.
Last edited by Cuchulainn on March 30th, 2014, 10:00 pm, edited 1 time in total.
http://www.datasimfinancial.com
http://www.datasim.nl

Every Time We Teach a Child Something, We Keep Him from Inventing It Himself
Jean Piaget

Cuchulainn
Topic Author
Posts: 61184
Joined: July 16th, 2004, 7:38 am
Location: Amsterdam
Contact:

### Using Quantlib

Luigi,Is the installation of QL on VS2013 easy?grazie
http://www.datasimfinancial.com
http://www.datasim.nl

Every Time We Teach a Child Something, We Keep Him from Inventing It Himself
Jean Piaget

CptanPanic
Posts: 11
Joined: June 23rd, 2010, 8:21 pm

### Using Quantlib

I am on windows and would like to use QuantLib with Python and SWIG, but I would rather not have to install VSC++ and Boost, etc. Is there a prebuilt version of 1.4 available?

tagoma
Posts: 18351
Joined: February 21st, 2010, 12:58 pm

### Using Quantlib

QuoteOriginally posted by: CptanPanicI am on windows and would like to use QuantLib with Python and SWIG, but I would rather not have to install VSC++ and Boost, etc. Is there a prebuilt version of 1.4 available???

Cuchulainn
Topic Author
Posts: 61184
Joined: July 16th, 2004, 7:38 am
Location: Amsterdam
Contact:

### Using Quantlib

The Visual Studio VS2015 installation with QL 1.8 installed without problems. Not even a compiler warning.Now I am trying to gather the code, data sets and background to QL code for Longstaff-Schwartz LeastSquares for Bermudan option, CVA and CCR. I have found some slide shows but am more interested in the algorithms.In the short term we wish to reproduce the results and see how it goes from there.Any pointers? thanks
http://www.datasimfinancial.com
http://www.datasim.nl

Every Time We Teach a Child Something, We Keep Him from Inventing It Himself
Jean Piaget

pcaspers
Posts: 695
Joined: June 6th, 2005, 9:49 am

### Using Quantlib

here is one pointer

Cuchulainn
Topic Author
Posts: 61184
Joined: July 16th, 2004, 7:38 am
Location: Amsterdam
Contact:

### Using Quantlib

QuoteOriginally posted by: pcaspershere is one pointerThanks.I have compiled this into QL. I now need to create an instance of LSPP class with a path evolver and a yield term structure. Are there 101 test data/programs for this?
Last edited by Cuchulainn on June 20th, 2016, 10:00 pm, edited 1 time in total.
http://www.datasimfinancial.com
http://www.datasim.nl

Every Time We Teach a Child Something, We Keep Him from Inventing It Himself
Jean Piaget

pcaspers
Posts: 695
Joined: June 6th, 2005, 9:49 am

### Using Quantlib

look in the test suite for american option pricing, there is an (equity) example; there are also lots of examples in the market model tests (but they are actually using different classes for LS); and there will be more, I am sure, maybe just grep McLongstaffSchwartzEngine or LongstaffSchwartzPathPricer.

Cuchulainn
Topic Author
Posts: 61184
Joined: July 16th, 2004, 7:38 am
Location: Amsterdam
Contact:

### Re: Using Quantlib

Are there any plans at any time for QL under C++11?
The current design uses many of the GOF patterns from the 1990s as I discussed once (you may remember)  at one QL meeting.

It will be difficult for GOF to adapt, so IMO something should be done. In fact, they are not the main metaphor any more.
A number of GOF patterns (e.g. Observer, Command) are basically just wrong. And you don't need class hierarchies.
(For the record, the GOF patterns I have migrated/made redundant to a next gen style. So, It's not a brainstorming post here!)

The functional programming metaphor is closer to algorithmic thinking than OOP. And it has a natural 1:1 mapping to multitasking with std::future.
http://www.datasimfinancial.com
http://www.datasim.nl

Every Time We Teach a Child Something, We Keep Him from Inventing It Himself
Jean Piaget

Cuchulainn
Topic Author
Posts: 61184
Joined: July 16th, 2004, 7:38 am
Location: Amsterdam
Contact:

### Re: Using Quantlib

An example to show delegates and super-easy interface. We don't need to use SWIG and GOF Observer replaced by events .
Another option is put C# code in an assembly and then open the assembly from CLI.
The other way around (wrap C++ to CLI) is also easy.

This could be done with QL quite easily, e.g. wrap C++ Calendar.or BVN etc.Whatever.

// ClockSubscriber.cpp
//
// Usiing .Net delegates instead of GOF Observer and call the .Net code
// from C++/CLI and native C++. Means we don't need SWIG?
//
// Ported from C#. Creata CLR Console and run.
//
// (C) Datasim Education BV  2002-2018

using namespace System;

public ref class TimeChangeEventArgs : EventArgs
{
public:
DateTime dt;

TimeChangeEventArgs(DateTime dt)
{ // Constructor

this->dt = dt;
}
};

public ref class Clock
{
public:
// Define event delegate
delegate void TimeChangeEventHandler(Object^ sender, TimeChangeEventArgs^ e);

// Event variable to store subscribers. Note, it also works without the "event" keyword but with "event" the framework can make a distintion
event TimeChangeEventHandler^ OnTimeChange;

void Run()
{

for (;; Thread::Sleep(1000)) // Infinite loop, sleeps every iteration for 1000 ms
{
// Get the current time
TimeChangeEventArgs^ args = gcnew TimeChangeEventArgs(DateTime::Now);

// Raise event and call event methods
// C# and C++/CLI versions
// if (OnTimeChange != nullptr) OnTimeChange(this, args); // Necessary to check for null
OnTimeChange(this, args); // Not necessary to check for null
}
}
};

public ref class ClockSubscriber
{
public:
static void DisplayTime1(Object^ sender, TimeChangeEventArgs^ args)
{ // TimeChangeEventHandler 1

Console::WriteLine("DisplayTime 1: {0}", args->dt);
}

static void DisplayTime2(Object^ sender, TimeChangeEventArgs^ args)
{ // TimeChangeEventHandler 2

// Display time with an offset
int h = 24; int d = 0; int m = 0;
TimeSpan ts(h, d, m);

Console::WriteLine("Offset, DisplayTime 2: {0}", args->dt + ts);
}
};

int main()
{
// Create clock instance
Clock^ clock = gcnew Clock();

// Subscribe event handlers for Clock.TimeChangeEvent
clock->OnTimeChange += gcnew Clock::TimeChangeEventHandler(ClockSubscriber::DisplayTime1);
clock->OnTimeChange += gcnew Clock::TimeChangeEventHandler(ClockSubscriber::DisplayTime2);

// Start the clock
clock->Run();

return 0;
}
http://www.datasimfinancial.com
http://www.datasim.nl

Every Time We Teach a Child Something, We Keep Him from Inventing It Himself
Jean Piaget

Cuchulainn
Topic Author
Posts: 61184
Joined: July 16th, 2004, 7:38 am
Location: Amsterdam
Contact:

### Re: Using Quantlib

I had a quick look at SWIG; it allows you to call C/C++ code from C# by creating an interface file and compiling it into an unmanaged dll that you can call using PINVOKE. Fair enough But ... why not let the compiler do it for you automagically into a reflective/self-describing .Net assembly? SWIG has a bit 80s feel (IDL etc.)

I have not used SWIG but I suspect maintaining all those interfaces is an issue?

Take an example of the Genz West BVN algo we call from C#. We create an assembly in C++/CLI and call it from C#.  As sanity check, we did a test of the output from here:

viewtopic.php?f=34&t=83376

Just one more thing .. you can write C++ code + QL and call .NET code. Not sure if SWIG can.
// ManagedWrapper.hpp
//
// C++/CLI wrapper class for a native C++ class
//
// (C) Datasim Education BV 2018
//

#pragma once

#include <string>
#include <memory>

#include <ql/quantlib.hpp>
#include <ql/math/distributions/bivariatenormaldistribution.cpp>
using NativeClass = QuantLib::BivariateCumulativeNormalDistributionWe04DP;

using namespace System;

namespace Wrapper
{

// ManagedWrapper has similar interface as the native class that it wraps
public ref class ManagedWrapper
{
private:
NativeClass* m_nativeClass; // The embedded native class
// std::unique_ptr<NativeClass> m_nativeClass; // mixed types not possible!
double _rho;

public:

// Constructor with data
ManagedWrapper(double rho) : _rho(rho)
{
// Create native class instance with data
m_nativeClass =  new NativeClass(_rho);
}

double Compute(double a, double b)
{
return  (*m_nativeClass)(a, b);
}

// Get- and set data as property
property double Correlation
{
double get() { return _rho; }
void set(double value)
{
_rho = value;

delete m_nativeClass;
m_nativeClass = new NativeClass(_rho);
}
}

!ManagedWrapper()
{
delete m_nativeClass;
}

~ManagedWrapper()
{
this->!ManagedWrapper();
}
};
}

// Program

using Wrapper;

class MainClass
{
static void Main(string[] args)
{
/* double x=0.25;
int k=0;

// Uniform distributions
UniformDistribution myUniform=new UniformDistribution(0.0, 1.0);
Console.WriteLine("Lower value: {0}, Upper value: {1}", myUniform.Lower(), myUniform.Upper());

Console.WriteLine("pdf of Uniform: {0}", BoostMath.Pdf(myUniform, x));
Console.WriteLine("cdf of Uniform: {0}", BoostMath.Cdf(myUniform, x));
Console.WriteLine();

// Bernoulli distributions
BernoulliDistribution myBernoulli=new BernoulliDistribution(0.4);
Console.WriteLine("Probability of success: {0}", myBernoulli.SuccessFraction());

Console.WriteLine("pdf of Bernoulli: {0}", BoostMath.Pdf(myBernoulli, k));
Console.WriteLine("cdf of Bernoulli: {0}", BoostMath.Cdf(myBernoulli, k));
Console.WriteLine();

// Chi squared distributions
ChiSquaredDistribution myChiSquared=new ChiSquaredDistribution(0.4);

Console.WriteLine("pdf of ChiSquared: {0}", BoostMath.Pdf(myChiSquared, 2));
Console.WriteLine("cdf of ChiSquared: {0}", BoostMath.Cdf(myChiSquared, 2));
Console.WriteLine();
*/

// Non central chi squared distributions
NonCentralChiSquaredDistribution myNonCentralChiSquared = new NonCentralChiSquaredDistribution(2, 2);

Console.WriteLine("pdf of NonCentralChiSquared: {0}", BoostMath.Pdf(myNonCentralChiSquared, 2));
Console.WriteLine("cdf of NonCentralChiSquared: {0}", BoostMath.Cdf(myNonCentralChiSquared, 2));
Console.WriteLine();

// C# code here: Check output data from chapter 16, section 16.4
ManagedWrapper mw = new ManagedWrapper(0.948175);
Console.WriteLine("rho {0}", mw.Correlation);
Console.WriteLine("value {0}", mw.Compute(-4.7346574, 3.0501621));

mw.Correlation = 0.17220467;
Console.WriteLine("rho {0}", mw.Correlation);
Console.WriteLine("value {0}", mw.Compute(-2.726639, 4.9965896));

mw.Correlation = 0.054292586;
Console.WriteLine("rho {0}", mw.Correlation);
Console.WriteLine("value {0}", mw.Compute(-1.946981, 3.1876528));

}
}
http://www.datasimfinancial.com
http://www.datasim.nl

Every Time We Teach a Child Something, We Keep Him from Inventing It Himself
Jean Piaget

Cuchulainn
Topic Author
Posts: 61184
Joined: July 16th, 2004, 7:38 am
Location: Amsterdam
Contact:

### Re: Using Quantlib

 boost::mt19937 mt;
mt.seed(static_cast<boost::uint32_t> (std::time(0)));
boost::normal_distribution<> distribution;
boost::variate_generator<boost::mt19937&, boost::normal_distribution<>>
normal(mt, distribution);

std::mt19937 dre;
dre.seed(static_cast<boost::uint32_t> (std::time(0)));
std::normal_distribution<double> nor(0.0, 1.0);
I've noticed something interesting with QL and Monte Carlo, QL uses Boost RNG and I move RNG to C++11 (essentially changing the namesapace in  a straightforward way).

1. C++ 11 MT, Knuth are 6 times slower than Boost MT.
2. Boost MT _seems_ to be less accurate than Boost RNG).

Not knowing the details of these algorithms makes it difficult to say why.
http://www.datasimfinancial.com
http://www.datasim.nl

Every Time We Teach a Child Something, We Keep Him from Inventing It Himself
Jean Piaget

outrun
Posts: 4573
Joined: April 29th, 2016, 1:40 pm

### Re: Using Quantlib

What are your compiler settings? 64bit?

Do they generate the same sequence when given the same seed? What you are saying with "less accurate" is that it is biased and you are the first to observe that. That in turn means that it's deviating from the documented MT with has been extensively tested for its statistical properties. That is all a bit unlikely. How did you measure "accuracy" of the boost MT? Is it eg an observed statistical significant deviation from expected sample noise?

variate_generator is an old interface, you can be C++11 compliant by not using it. When the C++11 <random> standard came out it was based in boost, but with differences. Boost implemented the new standard interface and definitions to be compatible with the C++11 standard, and also left things in for backward compatibility.

Wilmott.com has been "Serving the Quantitative Finance Community" since 2001. Continued...

 JOBS BOARD

Looking for a quant job, risk, algo trading,...? Browse jobs here...

GZIP: On