Repository files navigation

CircleCInpm versioninstall size

quantlib-wasm

A wrapper of the quantitative finance library Quantlib. Compiled as a WebAssembly for use in browsers and in Node.JS.

WARNING: This is work in progress and in alpha mode.

A live example of quantlib running in the browser can be seen here https://captorab.github.io/quantlib-wasm-demo/

Install

npm install quantlib-wasm

Usage with React

importwasmUrlfrom"quantlib-wasm/dist/quantlib.wasm?url";importquantlibWasmfrom"quantlib-wasm";constMyReactComponent=()=>{const[quantLibLoaded,setQuantLibLoaded]=useState(false);const[QuantLib,setQuantLib]=useState(null);useEffect(()=>{if(!quantLibLoaded){quantlibWasm({locateFile: ()=>wasmUrl,}).then((loaded)=>{setQuantLib(loaded);setQuantLibLoaded(true);});}});
....

Introduction

Quantlib is a quantitative finance library, used for pricing, hedging and valuation of financial sequrities and derivatives. It's open source and widely used. The library is written in C++ and it has been exported to many languages such as Python, Java and C#.

How about exporting QuantLib to JavaScript? In Node.js there are many ways of importing external libraries, including node-gyp, addons and N-API. None of these techniques work client side in a browser. WebAssembly on the other hand, works both client and server-side.

WebAssembly (Wasm) is a sandboxed environment running inside the JavaScript virtual machine. High-level languages like C/C++ can be compiled into the Wasm. WebAssembly is supported by four major browsers (Chrome, Firefox, Safari and Edge). Therefore, QuantLib as WebAssembly can be used from JavaScript both client (web browser) and server-side (Node.js).

Working with QuantLib in JavaScript

QuantLib is an object oriented library, rather than functional oriented. The QuantLib calculations are done with many objects, such as Date, Calendar, Schedule, PricingEngine, YieldCurve and all kind of instrument objects. These objects can be exported and used in JavaScript. The code in JavaScript will be similar to versions in Python or C++.

Here is a schedule generator example:

const{ Date, TimeUnit, Schedule, Period, BusinessDayConvention, DateGenerationRule }=QuantLib;vareffectiveDate=Date.fromISOString("2019-08-19");varterminationDate=Date.fromISOString("2020-08-19");varperiod=newPeriod(3,TimeUnit.Months);varfirstDate=newDate();varnextToLastDate=newDate();varschedule=newSchedule(effectiveDate,terminationDate,period,QuantLib.TARGET,BusinessDayConvention.ModifiedFollowing,BusinessDayConvention.ModifiedFollowing,DateGenerationRule.Backward,true,firstDate,nextToLastDate);vardates=schedule.dates();for(leti=0;i<dates.size();i++){letd=dates.get(i);console.log(d.toISOString());d.delete();}[effectiveDate,terminationDate,period,firstDate,nextToLastDate,dates,schedule].forEach((d)=>d.delete());

Emscripten

This implementation uses Emscripten to compile QuantLib. Emscripten compiles C++ into low level JavaScript called asm.js, which is highly optimizable and can be executed at close to native speed. A long list of projects are already using Emscripten to port codebases to JavaScript.

Embind is used to bind C++ functions and classes to JavaScript. The bindings are done with a few lines of code. The technique for defining bindings is similar to Boost Python.

The easiest way to run the Emscripten environment is in a prebuild Docker container. trzeci/emscripten is a good container and when running it compilations are done with the emcc compiler via the command prompt. The three projects Emscripten, QuantLib and Boost (which is a dependency of QuantLib) and wrapped together in a container called captorab/emscripten-quantlib. Running in a docker container saves a lot of time. The operating system issues and the configuration are done once and can easily be shared among developers.

Memory management

When using Wasm and Embind, there is one catch though. Memory management must be handled in both the JavaScript and the Wasm environment. In JavaScript, objects are destructed automatically, but before leaving a QuantLib object in JavaScript a delete command needs to be sent to the Wasm, to destruct the C++ object. This must be done explicitly since the JavaScript objects do not have any finalizer. This is something high level programmers assume the environment will do automatically. Unfortunately this is not done automatically between the two memory areas, one in JavaScript and one in the Wasm. In the example above delete is called on the last line in the for loop and on the very last line of code.

Code like the example below cannot be used because it hides the destructor of the Date-object.

console.log(Date.fromISOString("2019-08-19").toString());// This causes a memory leak.

Here is the correct equivalent:

vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();

Memory usage can be measured in the Wasm at any time, and memory leaks can be detected.

const{ Date, mallinfo }=QuantLib;varm0=mallinfo();vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();varm1=mallinfo();console.log(m1.uordblks-m0.uordblks+(m1.hblkhd-m0.hblkhd));// Should print 0

Using the wasm in a React app

React in itself can easily use the Quantlib wasm. See the method above. When the app is build with create-react-app, webpack is used to load and build the source files. By default (version 3.1.1 or earlier of react-scripts), doesn't load wasm files. To bypass this problem Facebook's react-scripts can be forked and modified. How this is done is explained here.

One fork that loads wasm files is @captor/react-scripts. To create a new app that with the modifies script run:

npx create-react-app <app-name> --scripts-version @captor/react-scripts

Or, in an already existing app, change the installed script reference.

npm uninstall react-scripts
npm install @captor/react-scripts

Add quantlib-wasm to the app:

npm install quantlib-wasm

Status

Which objects and functions are exported? There is no documentation written yet. Until this project turns into alpha mode, the only reliable way is to check the code. In this case the binding file is the right place. It's found here.

Versioning

quantlib-wasm does not follow https://semver.org/, but the version from Quantlib with an extra number to version the quantlib-wasm package.

Development

In order to build a new version, when a new Quantlib version is available

git checkout -b $QUANTLIB_VERSION

In:

  • .circleci/config.yml
  • Dockerfile
  • Makefile
  • package.json

update from old version number to "${QUANTLIB_VERSION}"."${version}"

make build_docker_image
make build_bindings_from_unix
npm i
npm test
npm pack
npm publish

About

Build tools for Emscripten QuantLib and Boost

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

CircleCInpm versioninstall size

quantlib-wasm

A wrapper of the quantitative finance library Quantlib. Compiled as a WebAssembly for use in browsers and in Node.JS.

WARNING: This is work in progress and in alpha mode.

A live example of quantlib running in the browser can be seen here https://captorab.github.io/quantlib-wasm-demo/

Install

npm install quantlib-wasm

Usage with React

importwasmUrlfrom"quantlib-wasm/dist/quantlib.wasm?url";importquantlibWasmfrom"quantlib-wasm";constMyReactComponent=()=>{const[quantLibLoaded,setQuantLibLoaded]=useState(false);const[QuantLib,setQuantLib]=useState(null);useEffect(()=>{if(!quantLibLoaded){quantlibWasm({locateFile: ()=>wasmUrl,}).then((loaded)=>{setQuantLib(loaded);setQuantLibLoaded(true);});}});
....

Introduction

Quantlib is a quantitative finance library, used for pricing, hedging and valuation of financial sequrities and derivatives. It's open source and widely used. The library is written in C++ and it has been exported to many languages such as Python, Java and C#.

How about exporting QuantLib to JavaScript? In Node.js there are many ways of importing external libraries, including node-gyp, addons and N-API. None of these techniques work client side in a browser. WebAssembly on the other hand, works both client and server-side.

WebAssembly (Wasm) is a sandboxed environment running inside the JavaScript virtual machine. High-level languages like C/C++ can be compiled into the Wasm. WebAssembly is supported by four major browsers (Chrome, Firefox, Safari and Edge). Therefore, QuantLib as WebAssembly can be used from JavaScript both client (web browser) and server-side (Node.js).

Working with QuantLib in JavaScript

QuantLib is an object oriented library, rather than functional oriented. The QuantLib calculations are done with many objects, such as Date, Calendar, Schedule, PricingEngine, YieldCurve and all kind of instrument objects. These objects can be exported and used in JavaScript. The code in JavaScript will be similar to versions in Python or C++.

Here is a schedule generator example:

const{ Date, TimeUnit, Schedule, Period, BusinessDayConvention, DateGenerationRule }=QuantLib;vareffectiveDate=Date.fromISOString("2019-08-19");varterminationDate=Date.fromISOString("2020-08-19");varperiod=newPeriod(3,TimeUnit.Months);varfirstDate=newDate();varnextToLastDate=newDate();varschedule=newSchedule(effectiveDate,terminationDate,period,QuantLib.TARGET,BusinessDayConvention.ModifiedFollowing,BusinessDayConvention.ModifiedFollowing,DateGenerationRule.Backward,true,firstDate,nextToLastDate);vardates=schedule.dates();for(leti=0;i<dates.size();i++){letd=dates.get(i);console.log(d.toISOString());d.delete();}[effectiveDate,terminationDate,period,firstDate,nextToLastDate,dates,schedule].forEach((d)=>d.delete());

Emscripten

This implementation uses Emscripten to compile QuantLib. Emscripten compiles C++ into low level JavaScript called asm.js, which is highly optimizable and can be executed at close to native speed. A long list of projects are already using Emscripten to port codebases to JavaScript.

Embind is used to bind C++ functions and classes to JavaScript. The bindings are done with a few lines of code. The technique for defining bindings is similar to Boost Python.

The easiest way to run the Emscripten environment is in a prebuild Docker container. trzeci/emscripten is a good container and when running it compilations are done with the emcc compiler via the command prompt. The three projects Emscripten, QuantLib and Boost (which is a dependency of QuantLib) and wrapped together in a container called captorab/emscripten-quantlib. Running in a docker container saves a lot of time. The operating system issues and the configuration are done once and can easily be shared among developers.

Memory management

When using Wasm and Embind, there is one catch though. Memory management must be handled in both the JavaScript and the Wasm environment. In JavaScript, objects are destructed automatically, but before leaving a QuantLib object in JavaScript a delete command needs to be sent to the Wasm, to destruct the C++ object. This must be done explicitly since the JavaScript objects do not have any finalizer. This is something high level programmers assume the environment will do automatically. Unfortunately this is not done automatically between the two memory areas, one in JavaScript and one in the Wasm. In the example above delete is called on the last line in the for loop and on the very last line of code.

Code like the example below cannot be used because it hides the destructor of the Date-object.

console.log(Date.fromISOString("2019-08-19").toString());// This causes a memory leak.

Here is the correct equivalent:

vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();

Memory usage can be measured in the Wasm at any time, and memory leaks can be detected.

const{ Date, mallinfo }=QuantLib;varm0=mallinfo();vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();varm1=mallinfo();console.log(m1.uordblks-m0.uordblks+(m1.hblkhd-m0.hblkhd));// Should print 0

Using the wasm in a React app

React in itself can easily use the Quantlib wasm. See the method above. When the app is build with create-react-app, webpack is used to load and build the source files. By default (version 3.1.1 or earlier of react-scripts), doesn't load wasm files. To bypass this problem Facebook's react-scripts can be forked and modified. How this is done is explained here.

One fork that loads wasm files is @captor/react-scripts. To create a new app that with the modifies script run:

npx create-react-app <app-name> --scripts-version @captor/react-scripts

Or, in an already existing app, change the installed script reference.

npm uninstall react-scripts
npm install @captor/react-scripts

Add quantlib-wasm to the app:

npm install quantlib-wasm

Status

Which objects and functions are exported? There is no documentation written yet. Until this project turns into alpha mode, the only reliable way is to check the code. In this case the binding file is the right place. It's found here.

Versioning

quantlib-wasm does not follow https://semver.org/, but the version from Quantlib with an extra number to version the quantlib-wasm package.

Development

In order to build a new version, when a new Quantlib version is available

git checkout -b $QUANTLIB_VERSION

In:

  • .circleci/config.yml
  • Dockerfile
  • Makefile
  • package.json

update from old version number to "${QUANTLIB_VERSION}"."${version}"

make build_docker_image
make build_bindings_from_unix
npm i
npm test
npm pack
npm publish

About

Build tools for Emscripten QuantLib and Boost

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

CircleCInpm versioninstall size

quantlib-wasm

A wrapper of the quantitative finance library Quantlib. Compiled as a WebAssembly for use in browsers and in Node.JS.

WARNING: This is work in progress and in alpha mode.

A live example of quantlib running in the browser can be seen here https://captorab.github.io/quantlib-wasm-demo/

Install

npm install quantlib-wasm

Usage with React

importwasmUrlfrom"quantlib-wasm/dist/quantlib.wasm?url";importquantlibWasmfrom"quantlib-wasm";constMyReactComponent=()=>{const[quantLibLoaded,setQuantLibLoaded]=useState(false);const[QuantLib,setQuantLib]=useState(null);useEffect(()=>{if(!quantLibLoaded){quantlibWasm({locateFile: ()=>wasmUrl,}).then((loaded)=>{setQuantLib(loaded);setQuantLibLoaded(true);});}});
....

Introduction

Quantlib is a quantitative finance library, used for pricing, hedging and valuation of financial sequrities and derivatives. It's open source and widely used. The library is written in C++ and it has been exported to many languages such as Python, Java and C#.

How about exporting QuantLib to JavaScript? In Node.js there are many ways of importing external libraries, including node-gyp, addons and N-API. None of these techniques work client side in a browser. WebAssembly on the other hand, works both client and server-side.

WebAssembly (Wasm) is a sandboxed environment running inside the JavaScript virtual machine. High-level languages like C/C++ can be compiled into the Wasm. WebAssembly is supported by four major browsers (Chrome, Firefox, Safari and Edge). Therefore, QuantLib as WebAssembly can be used from JavaScript both client (web browser) and server-side (Node.js).

Working with QuantLib in JavaScript

QuantLib is an object oriented library, rather than functional oriented. The QuantLib calculations are done with many objects, such as Date, Calendar, Schedule, PricingEngine, YieldCurve and all kind of instrument objects. These objects can be exported and used in JavaScript. The code in JavaScript will be similar to versions in Python or C++.

Here is a schedule generator example:

const{ Date, TimeUnit, Schedule, Period, BusinessDayConvention, DateGenerationRule }=QuantLib;vareffectiveDate=Date.fromISOString("2019-08-19");varterminationDate=Date.fromISOString("2020-08-19");varperiod=newPeriod(3,TimeUnit.Months);varfirstDate=newDate();varnextToLastDate=newDate();varschedule=newSchedule(effectiveDate,terminationDate,period,QuantLib.TARGET,BusinessDayConvention.ModifiedFollowing,BusinessDayConvention.ModifiedFollowing,DateGenerationRule.Backward,true,firstDate,nextToLastDate);vardates=schedule.dates();for(leti=0;i<dates.size();i++){letd=dates.get(i);console.log(d.toISOString());d.delete();}[effectiveDate,terminationDate,period,firstDate,nextToLastDate,dates,schedule].forEach((d)=>d.delete());

Emscripten

This implementation uses Emscripten to compile QuantLib. Emscripten compiles C++ into low level JavaScript called asm.js, which is highly optimizable and can be executed at close to native speed. A long list of projects are already using Emscripten to port codebases to JavaScript.

Embind is used to bind C++ functions and classes to JavaScript. The bindings are done with a few lines of code. The technique for defining bindings is similar to Boost Python.

The easiest way to run the Emscripten environment is in a prebuild Docker container. trzeci/emscripten is a good container and when running it compilations are done with the emcc compiler via the command prompt. The three projects Emscripten, QuantLib and Boost (which is a dependency of QuantLib) and wrapped together in a container called captorab/emscripten-quantlib. Running in a docker container saves a lot of time. The operating system issues and the configuration are done once and can easily be shared among developers.

Memory management

When using Wasm and Embind, there is one catch though. Memory management must be handled in both the JavaScript and the Wasm environment. In JavaScript, objects are destructed automatically, but before leaving a QuantLib object in JavaScript a delete command needs to be sent to the Wasm, to destruct the C++ object. This must be done explicitly since the JavaScript objects do not have any finalizer. This is something high level programmers assume the environment will do automatically. Unfortunately this is not done automatically between the two memory areas, one in JavaScript and one in the Wasm. In the example above delete is called on the last line in the for loop and on the very last line of code.

Code like the example below cannot be used because it hides the destructor of the Date-object.

console.log(Date.fromISOString("2019-08-19").toString());// This causes a memory leak.

Here is the correct equivalent:

vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();

Memory usage can be measured in the Wasm at any time, and memory leaks can be detected.

const{ Date, mallinfo }=QuantLib;varm0=mallinfo();vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();varm1=mallinfo();console.log(m1.uordblks-m0.uordblks+(m1.hblkhd-m0.hblkhd));// Should print 0

Using the wasm in a React app

React in itself can easily use the Quantlib wasm. See the method above. When the app is build with create-react-app, webpack is used to load and build the source files. By default (version 3.1.1 or earlier of react-scripts), doesn't load wasm files. To bypass this problem Facebook's react-scripts can be forked and modified. How this is done is explained here.

One fork that loads wasm files is @captor/react-scripts. To create a new app that with the modifies script run:

npx create-react-app <app-name> --scripts-version @captor/react-scripts

Or, in an already existing app, change the installed script reference.

npm uninstall react-scripts
npm install @captor/react-scripts

Add quantlib-wasm to the app:

npm install quantlib-wasm

Status

Which objects and functions are exported? There is no documentation written yet. Until this project turns into alpha mode, the only reliable way is to check the code. In this case the binding file is the right place. It's found here.

Versioning

quantlib-wasm does not follow https://semver.org/, but the version from Quantlib with an extra number to version the quantlib-wasm package.

Development

In order to build a new version, when a new Quantlib version is available

git checkout -b $QUANTLIB_VERSION

In:

  • .circleci/config.yml
  • Dockerfile
  • Makefile
  • package.json

update from old version number to "${QUANTLIB_VERSION}"."${version}"

make build_docker_image
make build_bindings_from_unix
npm i
npm test
npm pack
npm publish

About

Build tools for Emscripten QuantLib and Boost

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

CircleCInpm versioninstall size

quantlib-wasm

A wrapper of the quantitative finance library Quantlib. Compiled as a WebAssembly for use in browsers and in Node.JS.

WARNING: This is work in progress and in alpha mode.

A live example of quantlib running in the browser can be seen here https://captorab.github.io/quantlib-wasm-demo/

Install

npm install quantlib-wasm

Usage with React

importwasmUrlfrom"quantlib-wasm/dist/quantlib.wasm?url";importquantlibWasmfrom"quantlib-wasm";constMyReactComponent=()=>{const[quantLibLoaded,setQuantLibLoaded]=useState(false);const[QuantLib,setQuantLib]=useState(null);useEffect(()=>{if(!quantLibLoaded){quantlibWasm({locateFile: ()=>wasmUrl,}).then((loaded)=>{setQuantLib(loaded);setQuantLibLoaded(true);});}});
....

Introduction

Quantlib is a quantitative finance library, used for pricing, hedging and valuation of financial sequrities and derivatives. It's open source and widely used. The library is written in C++ and it has been exported to many languages such as Python, Java and C#.

How about exporting QuantLib to JavaScript? In Node.js there are many ways of importing external libraries, including node-gyp, addons and N-API. None of these techniques work client side in a browser. WebAssembly on the other hand, works both client and server-side.

WebAssembly (Wasm) is a sandboxed environment running inside the JavaScript virtual machine. High-level languages like C/C++ can be compiled into the Wasm. WebAssembly is supported by four major browsers (Chrome, Firefox, Safari and Edge). Therefore, QuantLib as WebAssembly can be used from JavaScript both client (web browser) and server-side (Node.js).

Working with QuantLib in JavaScript

QuantLib is an object oriented library, rather than functional oriented. The QuantLib calculations are done with many objects, such as Date, Calendar, Schedule, PricingEngine, YieldCurve and all kind of instrument objects. These objects can be exported and used in JavaScript. The code in JavaScript will be similar to versions in Python or C++.

Here is a schedule generator example:

const{ Date, TimeUnit, Schedule, Period, BusinessDayConvention, DateGenerationRule }=QuantLib;vareffectiveDate=Date.fromISOString("2019-08-19");varterminationDate=Date.fromISOString("2020-08-19");varperiod=newPeriod(3,TimeUnit.Months);varfirstDate=newDate();varnextToLastDate=newDate();varschedule=newSchedule(effectiveDate,terminationDate,period,QuantLib.TARGET,BusinessDayConvention.ModifiedFollowing,BusinessDayConvention.ModifiedFollowing,DateGenerationRule.Backward,true,firstDate,nextToLastDate);vardates=schedule.dates();for(leti=0;i<dates.size();i++){letd=dates.get(i);console.log(d.toISOString());d.delete();}[effectiveDate,terminationDate,period,firstDate,nextToLastDate,dates,schedule].forEach((d)=>d.delete());

Emscripten

This implementation uses Emscripten to compile QuantLib. Emscripten compiles C++ into low level JavaScript called asm.js, which is highly optimizable and can be executed at close to native speed. A long list of projects are already using Emscripten to port codebases to JavaScript.

Embind is used to bind C++ functions and classes to JavaScript. The bindings are done with a few lines of code. The technique for defining bindings is similar to Boost Python.

The easiest way to run the Emscripten environment is in a prebuild Docker container. trzeci/emscripten is a good container and when running it compilations are done with the emcc compiler via the command prompt. The three projects Emscripten, QuantLib and Boost (which is a dependency of QuantLib) and wrapped together in a container called captorab/emscripten-quantlib. Running in a docker container saves a lot of time. The operating system issues and the configuration are done once and can easily be shared among developers.

Memory management

When using Wasm and Embind, there is one catch though. Memory management must be handled in both the JavaScript and the Wasm environment. In JavaScript, objects are destructed automatically, but before leaving a QuantLib object in JavaScript a delete command needs to be sent to the Wasm, to destruct the C++ object. This must be done explicitly since the JavaScript objects do not have any finalizer. This is something high level programmers assume the environment will do automatically. Unfortunately this is not done automatically between the two memory areas, one in JavaScript and one in the Wasm. In the example above delete is called on the last line in the for loop and on the very last line of code.

Code like the example below cannot be used because it hides the destructor of the Date-object.

console.log(Date.fromISOString("2019-08-19").toString());// This causes a memory leak.

Here is the correct equivalent:

vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();

Memory usage can be measured in the Wasm at any time, and memory leaks can be detected.

const{ Date, mallinfo }=QuantLib;varm0=mallinfo();vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();varm1=mallinfo();console.log(m1.uordblks-m0.uordblks+(m1.hblkhd-m0.hblkhd));// Should print 0

Using the wasm in a React app

React in itself can easily use the Quantlib wasm. See the method above. When the app is build with create-react-app, webpack is used to load and build the source files. By default (version 3.1.1 or earlier of react-scripts), doesn't load wasm files. To bypass this problem Facebook's react-scripts can be forked and modified. How this is done is explained here.

One fork that loads wasm files is @captor/react-scripts. To create a new app that with the modifies script run:

npx create-react-app <app-name> --scripts-version @captor/react-scripts

Or, in an already existing app, change the installed script reference.

npm uninstall react-scripts
npm install @captor/react-scripts

Add quantlib-wasm to the app:

npm install quantlib-wasm

Status

Which objects and functions are exported? There is no documentation written yet. Until this project turns into alpha mode, the only reliable way is to check the code. In this case the binding file is the right place. It's found here.

Versioning

quantlib-wasm does not follow https://semver.org/, but the version from Quantlib with an extra number to version the quantlib-wasm package.

Development

In order to build a new version, when a new Quantlib version is available

git checkout -b $QUANTLIB_VERSION

In:

  • .circleci/config.yml
  • Dockerfile
  • Makefile
  • package.json

update from old version number to "${QUANTLIB_VERSION}"."${version}"

make build_docker_image
make build_bindings_from_unix
npm i
npm test
npm pack
npm publish

About

Build tools for Emscripten QuantLib and Boost

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

CircleCInpm versioninstall size

quantlib-wasm

A wrapper of the quantitative finance library Quantlib. Compiled as a WebAssembly for use in browsers and in Node.JS.

WARNING: This is work in progress and in alpha mode.

A live example of quantlib running in the browser can be seen here https://captorab.github.io/quantlib-wasm-demo/

Install

npm install quantlib-wasm

Usage with React

importwasmUrlfrom"quantlib-wasm/dist/quantlib.wasm?url";importquantlibWasmfrom"quantlib-wasm";constMyReactComponent=()=>{const[quantLibLoaded,setQuantLibLoaded]=useState(false);const[QuantLib,setQuantLib]=useState(null);useEffect(()=>{if(!quantLibLoaded){quantlibWasm({locateFile: ()=>wasmUrl,}).then((loaded)=>{setQuantLib(loaded);setQuantLibLoaded(true);});}});
....

Introduction

Quantlib is a quantitative finance library, used for pricing, hedging and valuation of financial sequrities and derivatives. It's open source and widely used. The library is written in C++ and it has been exported to many languages such as Python, Java and C#.

How about exporting QuantLib to JavaScript? In Node.js there are many ways of importing external libraries, including node-gyp, addons and N-API. None of these techniques work client side in a browser. WebAssembly on the other hand, works both client and server-side.

WebAssembly (Wasm) is a sandboxed environment running inside the JavaScript virtual machine. High-level languages like C/C++ can be compiled into the Wasm. WebAssembly is supported by four major browsers (Chrome, Firefox, Safari and Edge). Therefore, QuantLib as WebAssembly can be used from JavaScript both client (web browser) and server-side (Node.js).

Working with QuantLib in JavaScript

QuantLib is an object oriented library, rather than functional oriented. The QuantLib calculations are done with many objects, such as Date, Calendar, Schedule, PricingEngine, YieldCurve and all kind of instrument objects. These objects can be exported and used in JavaScript. The code in JavaScript will be similar to versions in Python or C++.

Here is a schedule generator example:

const{ Date, TimeUnit, Schedule, Period, BusinessDayConvention, DateGenerationRule }=QuantLib;vareffectiveDate=Date.fromISOString("2019-08-19");varterminationDate=Date.fromISOString("2020-08-19");varperiod=newPeriod(3,TimeUnit.Months);varfirstDate=newDate();varnextToLastDate=newDate();varschedule=newSchedule(effectiveDate,terminationDate,period,QuantLib.TARGET,BusinessDayConvention.ModifiedFollowing,BusinessDayConvention.ModifiedFollowing,DateGenerationRule.Backward,true,firstDate,nextToLastDate);vardates=schedule.dates();for(leti=0;i<dates.size();i++){letd=dates.get(i);console.log(d.toISOString());d.delete();}[effectiveDate,terminationDate,period,firstDate,nextToLastDate,dates,schedule].forEach((d)=>d.delete());

Emscripten

This implementation uses Emscripten to compile QuantLib. Emscripten compiles C++ into low level JavaScript called asm.js, which is highly optimizable and can be executed at close to native speed. A long list of projects are already using Emscripten to port codebases to JavaScript.

Embind is used to bind C++ functions and classes to JavaScript. The bindings are done with a few lines of code. The technique for defining bindings is similar to Boost Python.

The easiest way to run the Emscripten environment is in a prebuild Docker container. trzeci/emscripten is a good container and when running it compilations are done with the emcc compiler via the command prompt. The three projects Emscripten, QuantLib and Boost (which is a dependency of QuantLib) and wrapped together in a container called captorab/emscripten-quantlib. Running in a docker container saves a lot of time. The operating system issues and the configuration are done once and can easily be shared among developers.

Memory management

When using Wasm and Embind, there is one catch though. Memory management must be handled in both the JavaScript and the Wasm environment. In JavaScript, objects are destructed automatically, but before leaving a QuantLib object in JavaScript a delete command needs to be sent to the Wasm, to destruct the C++ object. This must be done explicitly since the JavaScript objects do not have any finalizer. This is something high level programmers assume the environment will do automatically. Unfortunately this is not done automatically between the two memory areas, one in JavaScript and one in the Wasm. In the example above delete is called on the last line in the for loop and on the very last line of code.

Code like the example below cannot be used because it hides the destructor of the Date-object.

console.log(Date.fromISOString("2019-08-19").toString());// This causes a memory leak.

Here is the correct equivalent:

vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();

Memory usage can be measured in the Wasm at any time, and memory leaks can be detected.

const{ Date, mallinfo }=QuantLib;varm0=mallinfo();vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();varm1=mallinfo();console.log(m1.uordblks-m0.uordblks+(m1.hblkhd-m0.hblkhd));// Should print 0

Using the wasm in a React app

React in itself can easily use the Quantlib wasm. See the method above. When the app is build with create-react-app, webpack is used to load and build the source files. By default (version 3.1.1 or earlier of react-scripts), doesn't load wasm files. To bypass this problem Facebook's react-scripts can be forked and modified. How this is done is explained here.

One fork that loads wasm files is @captor/react-scripts. To create a new app that with the modifies script run:

npx create-react-app <app-name> --scripts-version @captor/react-scripts

Or, in an already existing app, change the installed script reference.

npm uninstall react-scripts
npm install @captor/react-scripts

Add quantlib-wasm to the app:

npm install quantlib-wasm

Status

Which objects and functions are exported? There is no documentation written yet. Until this project turns into alpha mode, the only reliable way is to check the code. In this case the binding file is the right place. It's found here.

Versioning

quantlib-wasm does not follow https://semver.org/, but the version from Quantlib with an extra number to version the quantlib-wasm package.

Development

In order to build a new version, when a new Quantlib version is available

git checkout -b $QUANTLIB_VERSION

In:

  • .circleci/config.yml
  • Dockerfile
  • Makefile
  • package.json

update from old version number to "${QUANTLIB_VERSION}"."${version}"

make build_docker_image
make build_bindings_from_unix
npm i
npm test
npm pack
npm publish

About

Build tools for Emscripten QuantLib and Boost

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

CircleCInpm versioninstall size

quantlib-wasm

A wrapper of the quantitative finance library Quantlib. Compiled as a WebAssembly for use in browsers and in Node.JS.

WARNING: This is work in progress and in alpha mode.

A live example of quantlib running in the browser can be seen here https://captorab.github.io/quantlib-wasm-demo/

Install

npm install quantlib-wasm

Usage with React

importwasmUrlfrom"quantlib-wasm/dist/quantlib.wasm?url";importquantlibWasmfrom"quantlib-wasm";constMyReactComponent=()=>{const[quantLibLoaded,setQuantLibLoaded]=useState(false);const[QuantLib,setQuantLib]=useState(null);useEffect(()=>{if(!quantLibLoaded){quantlibWasm({locateFile: ()=>wasmUrl,}).then((loaded)=>{setQuantLib(loaded);setQuantLibLoaded(true);});}});
....

Introduction

Quantlib is a quantitative finance library, used for pricing, hedging and valuation of financial sequrities and derivatives. It's open source and widely used. The library is written in C++ and it has been exported to many languages such as Python, Java and C#.

How about exporting QuantLib to JavaScript? In Node.js there are many ways of importing external libraries, including node-gyp, addons and N-API. None of these techniques work client side in a browser. WebAssembly on the other hand, works both client and server-side.

WebAssembly (Wasm) is a sandboxed environment running inside the JavaScript virtual machine. High-level languages like C/C++ can be compiled into the Wasm. WebAssembly is supported by four major browsers (Chrome, Firefox, Safari and Edge). Therefore, QuantLib as WebAssembly can be used from JavaScript both client (web browser) and server-side (Node.js).

Working with QuantLib in JavaScript

QuantLib is an object oriented library, rather than functional oriented. The QuantLib calculations are done with many objects, such as Date, Calendar, Schedule, PricingEngine, YieldCurve and all kind of instrument objects. These objects can be exported and used in JavaScript. The code in JavaScript will be similar to versions in Python or C++.

Here is a schedule generator example:

const{ Date, TimeUnit, Schedule, Period, BusinessDayConvention, DateGenerationRule }=QuantLib;vareffectiveDate=Date.fromISOString("2019-08-19");varterminationDate=Date.fromISOString("2020-08-19");varperiod=newPeriod(3,TimeUnit.Months);varfirstDate=newDate();varnextToLastDate=newDate();varschedule=newSchedule(effectiveDate,terminationDate,period,QuantLib.TARGET,BusinessDayConvention.ModifiedFollowing,BusinessDayConvention.ModifiedFollowing,DateGenerationRule.Backward,true,firstDate,nextToLastDate);vardates=schedule.dates();for(leti=0;i<dates.size();i++){letd=dates.get(i);console.log(d.toISOString());d.delete();}[effectiveDate,terminationDate,period,firstDate,nextToLastDate,dates,schedule].forEach((d)=>d.delete());

Emscripten

This implementation uses Emscripten to compile QuantLib. Emscripten compiles C++ into low level JavaScript called asm.js, which is highly optimizable and can be executed at close to native speed. A long list of projects are already using Emscripten to port codebases to JavaScript.

Embind is used to bind C++ functions and classes to JavaScript. The bindings are done with a few lines of code. The technique for defining bindings is similar to Boost Python.

The easiest way to run the Emscripten environment is in a prebuild Docker container. trzeci/emscripten is a good container and when running it compilations are done with the emcc compiler via the command prompt. The three projects Emscripten, QuantLib and Boost (which is a dependency of QuantLib) and wrapped together in a container called captorab/emscripten-quantlib. Running in a docker container saves a lot of time. The operating system issues and the configuration are done once and can easily be shared among developers.

Memory management

When using Wasm and Embind, there is one catch though. Memory management must be handled in both the JavaScript and the Wasm environment. In JavaScript, objects are destructed automatically, but before leaving a QuantLib object in JavaScript a delete command needs to be sent to the Wasm, to destruct the C++ object. This must be done explicitly since the JavaScript objects do not have any finalizer. This is something high level programmers assume the environment will do automatically. Unfortunately this is not done automatically between the two memory areas, one in JavaScript and one in the Wasm. In the example above delete is called on the last line in the for loop and on the very last line of code.

Code like the example below cannot be used because it hides the destructor of the Date-object.

console.log(Date.fromISOString("2019-08-19").toString());// This causes a memory leak.

Here is the correct equivalent:

vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();

Memory usage can be measured in the Wasm at any time, and memory leaks can be detected.

const{ Date, mallinfo }=QuantLib;varm0=mallinfo();vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();varm1=mallinfo();console.log(m1.uordblks-m0.uordblks+(m1.hblkhd-m0.hblkhd));// Should print 0

Using the wasm in a React app

React in itself can easily use the Quantlib wasm. See the method above. When the app is build with create-react-app, webpack is used to load and build the source files. By default (version 3.1.1 or earlier of react-scripts), doesn't load wasm files. To bypass this problem Facebook's react-scripts can be forked and modified. How this is done is explained here.

One fork that loads wasm files is @captor/react-scripts. To create a new app that with the modifies script run:

npx create-react-app <app-name> --scripts-version @captor/react-scripts

Or, in an already existing app, change the installed script reference.

npm uninstall react-scripts
npm install @captor/react-scripts

Add quantlib-wasm to the app:

npm install quantlib-wasm

Status

Which objects and functions are exported? There is no documentation written yet. Until this project turns into alpha mode, the only reliable way is to check the code. In this case the binding file is the right place. It's found here.

Versioning

quantlib-wasm does not follow https://semver.org/, but the version from Quantlib with an extra number to version the quantlib-wasm package.

Development

In order to build a new version, when a new Quantlib version is available

git checkout -b $QUANTLIB_VERSION

In:

  • .circleci/config.yml
  • Dockerfile
  • Makefile
  • package.json

update from old version number to "${QUANTLIB_VERSION}"."${version}"

make build_docker_image
make build_bindings_from_unix
npm i
npm test
npm pack
npm publish

About

Build tools for Emscripten QuantLib and Boost

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

CircleCInpm versioninstall size

quantlib-wasm

A wrapper of the quantitative finance library Quantlib. Compiled as a WebAssembly for use in browsers and in Node.JS.

WARNING: This is work in progress and in alpha mode.

A live example of quantlib running in the browser can be seen here https://captorab.github.io/quantlib-wasm-demo/

Install

npm install quantlib-wasm

Usage with React

importwasmUrlfrom"quantlib-wasm/dist/quantlib.wasm?url";importquantlibWasmfrom"quantlib-wasm";constMyReactComponent=()=>{const[quantLibLoaded,setQuantLibLoaded]=useState(false);const[QuantLib,setQuantLib]=useState(null);useEffect(()=>{if(!quantLibLoaded){quantlibWasm({locateFile: ()=>wasmUrl,}).then((loaded)=>{setQuantLib(loaded);setQuantLibLoaded(true);});}});
....

Introduction

Quantlib is a quantitative finance library, used for pricing, hedging and valuation of financial sequrities and derivatives. It's open source and widely used. The library is written in C++ and it has been exported to many languages such as Python, Java and C#.

How about exporting QuantLib to JavaScript? In Node.js there are many ways of importing external libraries, including node-gyp, addons and N-API. None of these techniques work client side in a browser. WebAssembly on the other hand, works both client and server-side.

WebAssembly (Wasm) is a sandboxed environment running inside the JavaScript virtual machine. High-level languages like C/C++ can be compiled into the Wasm. WebAssembly is supported by four major browsers (Chrome, Firefox, Safari and Edge). Therefore, QuantLib as WebAssembly can be used from JavaScript both client (web browser) and server-side (Node.js).

Working with QuantLib in JavaScript

QuantLib is an object oriented library, rather than functional oriented. The QuantLib calculations are done with many objects, such as Date, Calendar, Schedule, PricingEngine, YieldCurve and all kind of instrument objects. These objects can be exported and used in JavaScript. The code in JavaScript will be similar to versions in Python or C++.

Here is a schedule generator example:

const{ Date, TimeUnit, Schedule, Period, BusinessDayConvention, DateGenerationRule }=QuantLib;vareffectiveDate=Date.fromISOString("2019-08-19");varterminationDate=Date.fromISOString("2020-08-19");varperiod=newPeriod(3,TimeUnit.Months);varfirstDate=newDate();varnextToLastDate=newDate();varschedule=newSchedule(effectiveDate,terminationDate,period,QuantLib.TARGET,BusinessDayConvention.ModifiedFollowing,BusinessDayConvention.ModifiedFollowing,DateGenerationRule.Backward,true,firstDate,nextToLastDate);vardates=schedule.dates();for(leti=0;i<dates.size();i++){letd=dates.get(i);console.log(d.toISOString());d.delete();}[effectiveDate,terminationDate,period,firstDate,nextToLastDate,dates,schedule].forEach((d)=>d.delete());

Emscripten

This implementation uses Emscripten to compile QuantLib. Emscripten compiles C++ into low level JavaScript called asm.js, which is highly optimizable and can be executed at close to native speed. A long list of projects are already using Emscripten to port codebases to JavaScript.

Embind is used to bind C++ functions and classes to JavaScript. The bindings are done with a few lines of code. The technique for defining bindings is similar to Boost Python.

The easiest way to run the Emscripten environment is in a prebuild Docker container. trzeci/emscripten is a good container and when running it compilations are done with the emcc compiler via the command prompt. The three projects Emscripten, QuantLib and Boost (which is a dependency of QuantLib) and wrapped together in a container called captorab/emscripten-quantlib. Running in a docker container saves a lot of time. The operating system issues and the configuration are done once and can easily be shared among developers.

Memory management

When using Wasm and Embind, there is one catch though. Memory management must be handled in both the JavaScript and the Wasm environment. In JavaScript, objects are destructed automatically, but before leaving a QuantLib object in JavaScript a delete command needs to be sent to the Wasm, to destruct the C++ object. This must be done explicitly since the JavaScript objects do not have any finalizer. This is something high level programmers assume the environment will do automatically. Unfortunately this is not done automatically between the two memory areas, one in JavaScript and one in the Wasm. In the example above delete is called on the last line in the for loop and on the very last line of code.

Code like the example below cannot be used because it hides the destructor of the Date-object.

console.log(Date.fromISOString("2019-08-19").toString());// This causes a memory leak.

Here is the correct equivalent:

vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();

Memory usage can be measured in the Wasm at any time, and memory leaks can be detected.

const{ Date, mallinfo }=QuantLib;varm0=mallinfo();vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();varm1=mallinfo();console.log(m1.uordblks-m0.uordblks+(m1.hblkhd-m0.hblkhd));// Should print 0

Using the wasm in a React app

React in itself can easily use the Quantlib wasm. See the method above. When the app is build with create-react-app, webpack is used to load and build the source files. By default (version 3.1.1 or earlier of react-scripts), doesn't load wasm files. To bypass this problem Facebook's react-scripts can be forked and modified. How this is done is explained here.

One fork that loads wasm files is @captor/react-scripts. To create a new app that with the modifies script run:

npx create-react-app <app-name> --scripts-version @captor/react-scripts

Or, in an already existing app, change the installed script reference.

npm uninstall react-scripts
npm install @captor/react-scripts

Add quantlib-wasm to the app:

npm install quantlib-wasm

Status

Which objects and functions are exported? There is no documentation written yet. Until this project turns into alpha mode, the only reliable way is to check the code. In this case the binding file is the right place. It's found here.

Versioning

quantlib-wasm does not follow https://semver.org/, but the version from Quantlib with an extra number to version the quantlib-wasm package.

Development

In order to build a new version, when a new Quantlib version is available

git checkout -b $QUANTLIB_VERSION

In:

  • .circleci/config.yml
  • Dockerfile
  • Makefile
  • package.json

update from old version number to "${QUANTLIB_VERSION}"."${version}"

make build_docker_image
make build_bindings_from_unix
npm i
npm test
npm pack
npm publish

About

Build tools for Emscripten QuantLib and Boost

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

CircleCInpm versioninstall size

quantlib-wasm

A wrapper of the quantitative finance library Quantlib. Compiled as a WebAssembly for use in browsers and in Node.JS.

WARNING: This is work in progress and in alpha mode.

A live example of quantlib running in the browser can be seen here https://captorab.github.io/quantlib-wasm-demo/

Install

npm install quantlib-wasm

Usage with React

importwasmUrlfrom"quantlib-wasm/dist/quantlib.wasm?url";importquantlibWasmfrom"quantlib-wasm";constMyReactComponent=()=>{const[quantLibLoaded,setQuantLibLoaded]=useState(false);const[QuantLib,setQuantLib]=useState(null);useEffect(()=>{if(!quantLibLoaded){quantlibWasm({locateFile: ()=>wasmUrl,}).then((loaded)=>{setQuantLib(loaded);setQuantLibLoaded(true);});}});
....

Introduction

Quantlib is a quantitative finance library, used for pricing, hedging and valuation of financial sequrities and derivatives. It's open source and widely used. The library is written in C++ and it has been exported to many languages such as Python, Java and C#.

How about exporting QuantLib to JavaScript? In Node.js there are many ways of importing external libraries, including node-gyp, addons and N-API. None of these techniques work client side in a browser. WebAssembly on the other hand, works both client and server-side.

WebAssembly (Wasm) is a sandboxed environment running inside the JavaScript virtual machine. High-level languages like C/C++ can be compiled into the Wasm. WebAssembly is supported by four major browsers (Chrome, Firefox, Safari and Edge). Therefore, QuantLib as WebAssembly can be used from JavaScript both client (web browser) and server-side (Node.js).

Working with QuantLib in JavaScript

QuantLib is an object oriented library, rather than functional oriented. The QuantLib calculations are done with many objects, such as Date, Calendar, Schedule, PricingEngine, YieldCurve and all kind of instrument objects. These objects can be exported and used in JavaScript. The code in JavaScript will be similar to versions in Python or C++.

Here is a schedule generator example:

const{ Date, TimeUnit, Schedule, Period, BusinessDayConvention, DateGenerationRule }=QuantLib;vareffectiveDate=Date.fromISOString("2019-08-19");varterminationDate=Date.fromISOString("2020-08-19");varperiod=newPeriod(3,TimeUnit.Months);varfirstDate=newDate();varnextToLastDate=newDate();varschedule=newSchedule(effectiveDate,terminationDate,period,QuantLib.TARGET,BusinessDayConvention.ModifiedFollowing,BusinessDayConvention.ModifiedFollowing,DateGenerationRule.Backward,true,firstDate,nextToLastDate);vardates=schedule.dates();for(leti=0;i<dates.size();i++){letd=dates.get(i);console.log(d.toISOString());d.delete();}[effectiveDate,terminationDate,period,firstDate,nextToLastDate,dates,schedule].forEach((d)=>d.delete());

Emscripten

This implementation uses Emscripten to compile QuantLib. Emscripten compiles C++ into low level JavaScript called asm.js, which is highly optimizable and can be executed at close to native speed. A long list of projects are already using Emscripten to port codebases to JavaScript.

Embind is used to bind C++ functions and classes to JavaScript. The bindings are done with a few lines of code. The technique for defining bindings is similar to Boost Python.

The easiest way to run the Emscripten environment is in a prebuild Docker container. trzeci/emscripten is a good container and when running it compilations are done with the emcc compiler via the command prompt. The three projects Emscripten, QuantLib and Boost (which is a dependency of QuantLib) and wrapped together in a container called captorab/emscripten-quantlib. Running in a docker container saves a lot of time. The operating system issues and the configuration are done once and can easily be shared among developers.

Memory management

When using Wasm and Embind, there is one catch though. Memory management must be handled in both the JavaScript and the Wasm environment. In JavaScript, objects are destructed automatically, but before leaving a QuantLib object in JavaScript a delete command needs to be sent to the Wasm, to destruct the C++ object. This must be done explicitly since the JavaScript objects do not have any finalizer. This is something high level programmers assume the environment will do automatically. Unfortunately this is not done automatically between the two memory areas, one in JavaScript and one in the Wasm. In the example above delete is called on the last line in the for loop and on the very last line of code.

Code like the example below cannot be used because it hides the destructor of the Date-object.

console.log(Date.fromISOString("2019-08-19").toString());// This causes a memory leak.

Here is the correct equivalent:

vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();

Memory usage can be measured in the Wasm at any time, and memory leaks can be detected.

const{ Date, mallinfo }=QuantLib;varm0=mallinfo();vardate=Date.fromISOString("2019-08-19");console.log(date.toString());date.delete();varm1=mallinfo();console.log(m1.uordblks-m0.uordblks+(m1.hblkhd-m0.hblkhd));// Should print 0

Using the wasm in a React app

React in itself can easily use the Quantlib wasm. See the method above. When the app is build with create-react-app, webpack is used to load and build the source files. By default (version 3.1.1 or earlier of react-scripts), doesn't load wasm files. To bypass this problem Facebook's react-scripts can be forked and modified. How this is done is explained here.

One fork that loads wasm files is @captor/react-scripts. To create a new app that with the modifies script run:

npx create-react-app <app-name> --scripts-version @captor/react-scripts

Or, in an already existing app, change the installed script reference.

npm uninstall react-scripts
npm install @captor/react-scripts

Add quantlib-wasm to the app:

npm install quantlib-wasm

Status

Which objects and functions are exported? There is no documentation written yet. Until this project turns into alpha mode, the only reliable way is to check the code. In this case the binding file is the right place. It's found here.

Versioning

quantlib-wasm does not follow https://semver.org/, but the version from Quantlib with an extra number to version the quantlib-wasm package.

Development

In order to build a new version, when a new Quantlib version is available

git checkout -b $QUANTLIB_VERSION

In:

  • .circleci/config.yml
  • Dockerfile
  • Makefile
  • package.json

update from old version number to "${QUANTLIB_VERSION}"."${version}"

make build_docker_image
make build_bindings_from_unix
npm i
npm test
npm pack
npm publish

About

Build tools for Emscripten QuantLib and Boost

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages