Git Product home page Git Product logo

lequant40 / portfolio_allocation_js Goto Github PK

View Code? Open in Web Editor NEW
172.0 12.0 32.0 3.05 MB

A JavaScript library to allocate and optimize financial portfolios.

Home Page: https://lequant40.github.io/portfolio_allocation_js/

License: MIT License

JavaScript 99.77% HTML 0.23%
quantitative-finance risk-parity risk-budgeting markowitz critical-line-algorithm clustering convex-optimization portfolio-optimization fista quadratic-programming

portfolio_allocation_js's Introduction

PortfolioAllocation (Changelog)

npm Travis Build Status Feature Requests

PortfolioAllocation is a JavaScript library designed to help constructing financial portfolios made of several assets: bonds, commodities, cryptocurrencies, currencies, exchange traded funds (ETFs), mutual funds, stocks...

When constructing such portfolios, one of the main problems faced is to determine the proportion of the different assets to hold.

PortfolioAllocation solves this problem using mathematical optimization algorithms.

Do not hesitate to report any bug / request additional features !

Foreword / Project Status

I initially developed the PortfolioAllocation library to allow the optimization of financial portfolios within Google Sheets.

Unfortunately, I quickly noticed two issues:

  • The integration of PortfolioAllocation inside a Google Sheet requires stronger IT skills than I anticipated
  • The execution of PortfolioAllocation algorithms on Google Sheets servers is 1) slow and 2) severely time constrained

For these reasons, I decided to stop developing the "vanilla" PortfolioAllocation library and replaced it with Portfolio Optimizer, a Web API to analyze and optimize financial portfolios.

As the integration of a Web API inside Google Sheets is much easier than the integration of a third party JavaScript library, this proved a wise choice.

TL;RD: If you need a software library to optimize financial portfolios within Google Sheets, please use the Portfolio Optimizer Web API.

Features

  • Compatible with Google Sheets
  • Compatible with any browser supporting ECMAScript 5 for front-end development
  • Compatible with Node.js for back-end development
  • Code continuously tested and integrated by Travis CI
  • Code documented for developers using JSDoc

Usage

Usage in Google Sheets

Note: Examples of how to integrate PortfolioAllocation in Google Sheets are provided in this spreadsheet.

First, make the PortfolioAllocation functions available in your spreadsheet script:

Then, you can call these functions your preferred way in your spreadsheet script.

Here is an example through a wrapper function, to which spreadsheet data ranges (e.g. A1:B3) can be provided directly:

function computeERCPortfolioWeights(covarianceMatrix) {
  // Note: The input range coming from the spreadsheet is directly usable.
    
  // Compute the ERC portfolio weights
  var ercWeights = PortfolioAllocation.equalRiskContributionWeights(covarianceMatrix);
  
  // Return them to the spreadsheet
  return ercWeights;
}

Usage in a browser

Note: PortfolioAllocation is delivered through the CDN jsDelivr, at this URL.

Include PortfolioAllocation minified source file in an HTML page, and you are done:

<script src="https://cdn.jsdelivr.net/npm/portfolio-allocation/dist/portfolio_allocation.dist.min.js" type="text/javascript"></script>
<script type="text/javascript">
  var w = PortfolioAllocation.riskBudgetingWeights([[0.1,0], [0,0.2]], [0.25, 0.75]);
</script>

Usage with Node.js

Note: PortfolioAllocation is delivered as the npm package portfolio-allocation.

First, declare PortfolioAllocation as a dependency in your project's package.json file, using the package name portfolio-allocation.

Then, this is standard Node.js:

var PortfolioAllocation = require('portfolio-allocation');
var w = PortfolioAllocation.riskBudgetingWeights([[0.1,0], [0,0.2]], [0.25, 0.75]);

Included algorithms

Portfolio allocation and optimization algorithms

Misc. other algorithms

  • Post-processing of numerical portfolio weights
    The weights obtained through a portfolio optimization algorithm (e.g. w = 0.123456789) need in practice to be either rounded off (e.g. w = 0.12) or converted into an integer number of shares (e.g. q = 10 shares, or q = 2 lots of 100 shares).

  • Computation of the mean-variance efficient frontier
    The continuous set of all mean-variance efficient portfolios (the mean-variance efficient frontier) as well as its generating discrete set (the set of corner portfolios) can both be efficiently computed thanks to a specialized algorithm developed by Harry M. Markowitz: the critical line method.

  • Computation of the nearest portfolio on the mean-variance efficient frontier
    Thanks to the Markowitz's critical line method, it is possible to exactly compute the nearest mean-variance efficient portfolio of any given portfolio.

  • Generation of perturbed mean vectors, variances and correlation matrices
    As demonstrated in The effect of errors in means, variances, and covariances on optimal portfolio choice by Vijay Chopra and William Ziemba, the impact of estimation errors in expected returns, variances and correlation matrices on the output of a portfolio optimization algorithm can be significant, so that it is useful to have an algorithm to perturb these quantities for portfolio weights sensitivity analysis.

  • Generic random subspace optimization
    A direct extension of the RSO-MVO method, allowing to use the random subspace optimization method with any portfolio optimization method.

  • Generic numerical optimization
    When no specialized algorithm exist to solve a particular portfolio optimization problem, it is always possible to use a generic numerical optimization algorithm (e.g., grid search on the simplex).

  • Random generation of mean vectors, variances and correlation matrices
    When implementing portfolio optimization algorithms, the capability to generate random mean vectors, random variances and random correlation matrices can be of great help.

  • Computation of shrinkage estimators for mean vectors and covariance matrices
    Shrinkage estimators for mean vectors can help to reduce the estimation errors in expected returns as observed in DeMiguel et al. Size Matters: Optimal Calibration of Shrinkage Estimators for Portfolio Selection, and shrinkage estimators for covariance matrices like Ledoit-Wolf's A Well-Conditioned Estimator for Large-Dimensional Covariance Matrices provide an elegant solution to the problem of the ill-conditioning and non-invertibility of sample covariance matrices.

  • Repairing indefinite or positive semi-definite correlation matrices
    With certain use-cases (e.g. alteration of correlation pairs for stress testing), correlation matrices might lose their positive (semi) definiteness, which is possible to recover thanks for instance to the spectral method described by Rebonato and Jaeckel in their paper The Most General Methodology to Create a Valid Correlation Matrix for Risk Management and Option Pricing Purposes or to other methods like the computation of the nearest correlation matrix addressed by Nicholas J. Higham in his paper Computing the nearest correlation matrix - A problem from Finance.

Documentation

The code is heavily documented, using JSDoc.

That being said, the documentation is rather for developer's usage, so that in case of trouble to use any algorithm, do not hesitate to ask for support !

Contributing

Fork the project from Github...

Install the Grunt dependencies and command line

npm install
npm install -g grunt-cli

Develop...

Compile and test

  • The following commands generates the files to be used inside a browser or with Node.js in the dist directory:
grunt deliver-dev
grunt deliver-dist
  • The following command generates the files to be used in Google Sheets in the dist\gs directory:
grunt deliver-gs

Submit a pull-request...

License

MIT License

portfolio_allocation_js's People

Contributors

lequant40 avatar masterjames avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

portfolio_allocation_js's Issues

Internal error in meanVarianceOptimizationWeights / maximumTargetVolatility method

Describe the bug
When min/max weights constraints are provided in the meanVarianceOptimizationWeights portfolio allocation method, using the optimization method maximumTargetVolatility, an internal error is produced with the input data below.

	var covMat = [[0.0004246616877,-0.00005520852069,0.0003954256465,0.00000001152437917,0.0001590470407,0.0002580332644,0.0003335881244,0.0003605784739],[-0.00005520852069,0.00002480135555,-0.00005059666822,-0.00000001082496581,-0.00001673167975,-0.00003073486553,-0.00003900214181,-0.00004548279667],[0.0003954256465,-0.00005059666822,0.0003976604822,-0.000000008144301394,0.0001740534739,0.0002593777442,0.0003420673729,0.0003593307083],[0.00000001152437917,-0.00000001082496581,-0.000000008144301394,0.00000001790999881,-0.00000008021468402,-0.00000006461917657,-0.00000007037516421,0.00000004991265269],[0.0001590470407,-0.00001673167975,0.0001740534739,-0.00000008021468402,0.000110482962,0.0001154225601,0.000157800705,0.0001589926655],[0.0002580332644,-0.00003073486553,0.0002593777442,-0.00000006461917657,0.0001154225601,0.0002185122484,0.0002506289478,0.0002558291246],[0.0003335881244,-0.00003900214181,0.0003420673729,-0.00000007037516421,0.000157800705,0.0002506289478,0.0003278326867,0.0003411302813],[0.0003605784739,-0.00004548279667,0.0003593307083,0.00000004991265269,0.0001589926655,0.0002558291246,0.0003411302813,0.0004078706675]];

	var returns = [0.02836270809, 0.01289860823, 0.003013461519, 0.0009824011995, -0.002791817978, -0.003228292398, -0.01390104713, -0.01415404063];

	var minWeights = [0, 0, 0, 0, 0, 0, 0, 0];
	var maxWeights = [0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 1, 1];

	var maxVolatility = 0.05/Math.sqrt(252);

	PortfolioAllocation.meanVarianceOptimizationWeights(returns, covMat, { optimizationMethod: 'maximumTargetVolatility', constraints: {maxVolatility: maxVolatility, minWeights: minWeights, maxWeights: maxWeights}});

To Reproduce
C.f. above.

Expected behavior
No internal error, but proper portfolio weights should be computed !

Link to Google Sheets / On-line npm code
N/A

Additional context
N/A

README Google Sheets Example Not Working as Expected

Hi Roman -

Thanks for this library! I'm just getting started with it on Google Sheets but can't seem to get the example in the README to work. In Google Sheets, I added your library with the Script ID, using static version 15 (v0.0.9). Then, I pasted this function into the Script Editor:

function computeERCPortfolioWeights(covarianceMatrix) {
// Note: The input range coming from the spreadsheet is directly usable.

// Compute the ERC portfolio weights
var ercWeights = PortfolioAllocation.equalRiskContributionWeights(covarianceMatrix);

// Return them to the spreadsheet
return (ercWeights);
}

In cells A1:B2 of my Google Sheet, I entered a sample covariance matrix: [[1,0.3],[0.3,1]]. In cell A4, I typed the following formula: =computeERCPortfolioWeights(A1:B2) but I get a #ERROR! with Error:unsupported input type (line 238).

I would've expected to get weights in cells A4:B4 or A4:A5.

Any help would be greatly appreciated.

Mean Variance Optimization not working as expected


X ref. from #7, to better separate issues.

Thanks Roman. That did the trick! Now I'm running into a different issue and would greatly appreciate any help:

I'm using the function below I created in Google Sheets, but am getting a #ERROR! that says "Error: unsupported problem detected (line 5838)". My goal is to calculate mean variance weights given an expected return stream, a covariance matrix, a target volatility, min weights, and max weights:

function computeWts(rets, cv, targetVol, minWts, maxWts) {
return (PortfolioAllocation.meanVarianceOptimizationWeights(rets, cv, {constraints: {optimizationMethod: 'maximumTargetVolatility', maxVolatility: targetVol, minWeights: minWts, maxWeights: maxWts}}));
}

The arguments I'm passing are below (and are all in cells in Google Sheets):

rets:
4.7%
5.0%
6.1%
4.0%
5.4%
2.0%
2.2%
2.4%
2.4%
3.6%

cv:
2.3% | 2.5% | 3.3% | 1.7% | 2.3% | -0.4% | -0.3% | -0.3% | 0.1% | 1.7%
2.5% | 2.9% | 3.8% | 1.9% | 2.5% | -0.4% | -0.3% | -0.3% | 0.2% | 1.9%
3.3% | 3.8% | 5.3% | 2.3% | 3.1% | -0.5% | -0.3% | -0.4% | 0.3% | 2.9%
1.7% | 1.9% | 2.3% | 1.4% | 1.8% | -0.3% | -0.3% | -0.3% | 0.0% | 1.1%
2.3% | 2.5% | 3.1% | 1.8% | 4.0% | -0.1% | 0.0% | 0.2% | 0.7% | 1.8%
-0.4% | -0.4% | -0.5% | -0.3% | -0.1% | 0.2% | 0.2% | 0.2% | 0.2% | -0.1%
-0.3% | -0.3% | -0.3% | -0.3% | 0.0% | 0.2% | 0.4% | 0.2% | 0.3% | 0.0%
-0.3% | -0.3% | -0.4% | -0.3% | 0.2% | 0.2% | 0.2% | 0.3% | 0.2% | 0.0%
0.1% | 0.2% | 0.3% | 0.0% | 0.7% | 0.2% | 0.3% | 0.2% | 0.5% | 0.4%
1.7% | 1.9% | 2.9% | 1.1% | 1.8% | -0.1% | 0.0% | 0.0% | 0.4% | 2.0%

targetVol:
5.5%

minWts:
3%
3%
3%
0%
0%
0%
0%
3%
0%
0%

maxWts:
35%
35%
35%
35%
35%
35%
35%
35%
35%
35%

Originally posted by @grantackerman1 in #7 (comment)

lambda_e is not defined when calling meanVarianceEfficientFrontierPortfolios

Hello @lequant40, I'm trying to use this library for a personal project and it's proving a very valuable learning exercise for understanding the relevant concepts in Portfolio Optimization space. Thanks a lot for making this resource open source!

I was hoping to get some clarification on a bug I'm running into while using method meanVarianceEfficientFrontierPortfolios from lib/allocation/mean-variance.js. Here are the details -

Describe the bug
Getting the following error while using the method meanVarianceEfficientFrontierPortfolios -

ReferenceError: lambda_e is not defined
    at computeCornerPortfolios (portfolio_allocation.dist.js:15132:4)
    at new MeanVarianceEfficientFrontierCla (portfolio_allocation.dist.js:14596:26)
    at new MeanVarianceEfficientFrontierWrapper (portfolio_allocation.dist.js:16471:28)
    at self.meanVarianceEfficientFrontierPortfolios (portfolio_allocation.dist.js:17353:23)
    at getOptimalPortfolio (mvt-utils.ts?t=1699625436099:16:49)
    at App.tsx?t=1699626061247:25:17
    at commitHookEffectListMount (react-dom.development.js:23150:26)
    at commitPassiveMountOnFiber (react-dom.development.js:24926:13)
    at commitPassiveMountEffects_complete (react-dom.development.js:24891:9)
    at commitPassiveMountEffects_begin (react-dom.development.js:24878:7)

To Reproduce
I am trying to run this method on dummy data, like so -

let stockData = [[0.05, 0.01, 0.01], [0.1, -0.03, 0.05],]

let covMat = PortfolioAllocation.covarianceMatrix(stockData, {
  assumeZeroMean: false,
}).toRowArray();

let returns = [];

for (let s_i = 0; s_i < stockData.length; s_i += 1) {
  let R_i = PortfolioAllocation.returns(stockData[s_i]);
  let returns_i = 1;
  for (let s_i_t = 0; s_i_t < stockData[s_i].length - 1; s_i_t += 1) {
    returns_i *= 1 + R_i[s_i_t];
  }

  returns.push(returns_i - 1);
}

let mvEfficientFrontier =
  PortfolioAllocation.meanVarianceEfficientFrontierPortfolios(
    returns,
    covMat,
    { nbPortfolios: 10 }
  );

and got the aforementioned error.

Expected behavior
meanVarianceEfficientFrontierPortfolios method should return n portfolios (n=10 in this case) when called.

I would really appreciate it if you could look into this and provide some information. Thanks!

Real world example

Hi. I am just wondering is there any real-world example? Don't really get how to use this package

NaNs with ERC (Equal Risk Contribution)

Hello

Thanks a lot for this very cool library :)

I came across some NaN results while experimenting with the ERC algorithm. A Google Sheet with a specific test case can be found here:

https://docs.google.com/spreadsheets/d/1WNw4GLkoyOmC0Qjefga6N_imQejEIOtC_OjMXGWJkF0/edit?usp=sharing

I don't know whether this is supposed to happen, so please excuse this if it's a beginner's mistake.

Anyway, I thought I'd bring this to your attention.

Thanks again and best regards

Maximum number of iterations reached, while simple problem to solve

Describe the bug
The meanVarianceOptimizationWeights method returns "Maximum number of iterations reached", whatever the number of iterations set, when using the following inputs:

	var covMat = [[0.04902254557, 0.04255604021, 0.04501327517, 0.04330779376, 0.03019691712, 0.02548665503, -0.01073017105, -0.0004006905689],
				[0.04682328959, 0.04455486658, 0.03786639547, 0.03747189194, 0.02769367774, 0.02256710184, -0.007460602423, -0.000360821725],
				[0.04501327517, 0.03441543433, 0.05846027012, 0.04801847343, 0.02887413717, 0.02797183226, -0.01440997349, -0.0003895354954],
				[0.04330779376, 0.03405688396, 0.04801847343, 0.04558680387, 0.03111517718, 0.02477230838, -0.01272882784, -0.0003624611328],
				[0.03019691712, 0.02516980916, 0.02887413717, 0.03111517718, 0.02614411029, 0.01475643353, -0.008794983792, -0.0002160623154],
				[0.02548665503, 0.02051044473, 0.02797183226, 0.02477230838, 0.01475643353, 0.01618991115, -0.006014483461, -0.0002507995642],
				[-0.01073017105, -0.006780679005, -0.01440997349, -0.01272882784, -0.008794983792, -0.006014483461, 0.005138124692, 0.00007878547574],
				[-0.0004006905689, -0.0003279381686, -0.0003895354954, -0.0003624611328, -0.0002160623154, -0.0002507995642, 0.00007878547574, 0.000007405024165]];
	var returns = [0.01807438883, 0.03238795043, 0.007555801824, 0.007427269126, 0.009034317809, 0.006707731718, 0.007769863126, 0.0007622417915];
	
	var minWeights = [0, 0, 0, 0, 0, 0, 0, 0];
	var maxWeights = [0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 1, 1];

To Reproduce
C.f. above inputs.

Expected behavior
A solution to the mean variance optimization problem should be computed !

Link to Google Sheets / On-line npm code
N/A

Additional context
N/A

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.