Portfolio Optimization Constraints wrong using quadprog in JavaScript - javascript

I cannot figure out what I am doing wrong with this portfolio optimization (find optimal weights) using quadprog in numeric.js
My portfolio constraints are simple: weights should sum up to 1 and all weights (for each of the 3 assets) should be between 0 and 1 (no short selling, no leverage). Constraints are not recognized and weights get very high (and also negative).
var constraintsmatrix = [[0,0,0,0], [1,0,1,0], [1,0,0,0]];
var covmatrix = [[0.00020817,0.00016281,0.00009747],[0.00016281,0.00026680,0.00009912],[0.00009747,0.00009912,0.00019958]];
var returnsmatrix = [0.1,0.05,0.1];
var bvec = 1; // [1,0,0,0,0,0,0,1,1,1];
var result = numeric.solveQP(covmatrix, returnsmatrix, constraintsmatrix, bvec);
Any hint appreciated. Thanks

I believe your constraints are not correctly specified and the rhs is not passed on. We want the following constraints (equality first):
x1+x2+x3 = 1
x1 >= 0
x2 >= 0
x3 >= 0
This corresponds to
A=[[1,1,0,0],[1,0,1,0],[1,0,0,1]]
b=[1,0,0,0]
Here is what I get:
Note that the objective of this model is 0.5*x'Dx-d'x. Also note I pass on 5 arguments to solveQP.

Related

GLPK.js no primal feasible solution when a solution exists

I am using the glpk.js library in an Angular application to solve an ILP problem. I have been using the library for some time now and it usually works well. I have encountered similar issues in the past, but I was able to sidestep them without finding out why they occurred. It might very well be the case, that I am not using the library correctly as their documentation is quite lacking.
I construct a "base" ILP problem and then I iterate over some array, construct additional constraints depending on each element of my array and try to solve the base ILP with the new constrains for each element.
I know there is a solution for each of the ILPs, but the solver returns PROBLEM HAS NO PRIMAL FEASIBLE SOLUTION for all but one of the ILPs.
My base ILP (in human readable format):
p0 >= 0
p1 >= 0
p2 >= 0
p3 >= 0
p4 >= 0
p5 >= 0
p6 >= 0
p7 >= 0
p0 +p1 +p2 +p3 +p4 +p5 +p6 +p7 >= 1
p1 -p0 -rise0 = 0
p2 +p3 -p1 -rise1 = 0
p4 -p2 -rise2 = 0
p6 -p4 -rise3 = 0
p10 -p6 -p5 -rise4 = 0
p5 -p3 -rise5 = 0
where the objective function is to minimise the sum of the p-variables.
when I apply the following additional constraints, the solver returns a solution (p10 = 1, all other p = 0):
rise0 = 0
rise1 = 0
rise2 = 0
rise3 = 0
rise4 = 1
rise5 = 0
p0 = 0
when I apply the following additional constraints, the solver returns no solution, even if p0 = 1, all other p = 0, solves the ILP:
rise0 = -1
rise1 = 0
rise2 = 0
rise3 = 0
rise4 = 0
rise5 = 0
p0 = 1
all the other sets of constrains also contain some rise with a negative value, which seems to cause the issue.
I am using the following configuration as input to the solver (JSON for the second example ILP):
{
"name":"p0",
"objective": {
"direction":1,
"name":"region",
"vars": [
{"name":"p0","coef":1},
{"name":"p1","coef":1},
{"name":"p2","coef":1},
{"name":"p3","coef":1},
{"name":"p4","coef":1},
{"name":"p5","coef":1},
{"name":"p6","coef":1},
{"name":"p7","coef":1}
]
},
"subjectTo": [
{"name":"c0","vars":[{"name":"p0","coef":1}],"bnds":{"type":2,"ub":0,"lb":0}},
{"name":"c1","vars":[{"name":"p1","coef":1}],"bnds":{"type":2,"ub":0,"lb":0}},
{"name":"c2","vars":[{"name":"p2","coef":1}],"bnds":{"type":2,"ub":0,"lb":0}},
{"name":"c3","vars":[{"name":"p3","coef":1}],"bnds":{"type":2,"ub":0,"lb":0}},
{"name":"c4","vars":[{"name":"p4","coef":1}],"bnds":{"type":2,"ub":0,"lb":0}},
{"name":"c5","vars":[{"name":"p5","coef":1}],"bnds":{"type":2,"ub":0,"lb":0}},
{"name":"c6","vars":[{"name":"p6","coef":1}],"bnds":{"type":2,"ub":0,"lb":0}},
{"name":"c7","vars":[{"name":"p7","coef":1}],"bnds":{"type":2,"ub":0,"lb":0}},
{"name":"c8","vars":[{"name":"p0","coef":1},{"name":"p1","coef":1},{"name":"p2","coef":1},{"name":"p3","coef":1},{"name":"p4","coef":1},{"name":"p5","coef":1},{"name":"p6","coef":1},{"name":"p7","coef":1}],"bnds":{"type":2,"ub":0,"lb":1}},
{"name":"c9","vars":[{"name":"p1","coef":1},{"name":"p0","coef":-1},{"name":"rise0","coef":-1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c10","vars":[{"name":"p2","coef":1},{"name":"p3","coef":1},{"name":"p1","coef":-1},{"name":"rise1","coef":-1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c11","vars":[{"name":"p4","coef":1},{"name":"p2","coef":-1},{"name":"rise2","coef":-1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c12","vars":[{"name":"p6","coef":1},{"name":"p4","coef":-1},{"name":"rise3","coef":-1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c13","vars":[{"name":"p7","coef":1},{"name":"p6","coef":-1},{"name":"p5","coef":-1},{"name":"rise4","coef":-1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c14","vars":[{"name":"p5","coef":1},{"name":"p3","coef":-1},{"name":"rise5","coef":-1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c15","vars":[{"name":"rise0","coef":1}],"bnds":{"type":5,"ub":-1,"lb":-1}},
{"name":"c16","vars":[{"name":"rise1","coef":1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c17","vars":[{"name":"rise5","coef":1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c18","vars":[{"name":"rise2","coef":1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c19","vars":[{"name":"rise3","coef":1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c20","vars":[{"name":"rise4","coef":1}],"bnds":{"type":5,"ub":0,"lb":0}},
{"name":"c21","vars":[{"name":"p0","coef":1}],"bnds":{"type":5,"ub":1,"lb":1}}
],
"binaries":[],
"generals": ["p0","p1","p2","p3","p4","p5","p6","p7","rise0","rise1","rise2","rise3","rise4","rise5"]
}
I assumed all integers (including negative) are allowed as solutions. But the only logical explanation to my problem seems to be that this is not the case. How can I enable negative integers as possible solutions?
I should have just researched the library more. There is an issue in the repository of the library that answers my question.
It really is the case that variables are bound to non-negative integers.
Variables with negative values can be expressed by splitting them into a positive and a negative part.
In my case it means I have to create a rise0plus and a rise0minus variable and modify my constrains as follows (for each rise variable):
p1 - p0 -rise0plus +rise0minus = 0
...
rise0plus -rise0minus = -1

What can I use to add new value to previous value and repeat this a certain amount of times? (Javascript)

I'm trying to get an array of numbers based on a calculation that keeps adding a set amount to the previous amount until this have repeated 20 times. The initial number is a negative number because the client pays an initial amount of money for a solar power system and then the calculation should subtract an amount each month based on how much the client saves by not having to pay for electricity. It needs to be an array (I think) because it needs to go into a chart. Here's a google worksheet that might make what I'm trying to more clear. The part of the sheet that is relevant to my question is in columns T and U in pink.
I did tonne of reading on loops, different array types (reduce and map). I'm new to this so it didn't seem any of those types of arrays will do what I need to be done. I found the below code somewhere and it seemed like this is the closest to what I need to happen but I could be completely off track (my adjusted version is further down):
// program to generate fibonacci series up to n terms
// take input from the user
const number = parseInt(prompt('Enter the number of terms: '));
let n1 = 0, n2 = 1, nextTerm;
console.log('Fibonacci Series:');
for (let i = 1; i <= number; i++) {
console.log(n1);
nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
}
I tried to adjust it to try get it to do what I need it to do but in console it shows one number and then the rest is NAN. I know this means not a number but I don't know why or how to fix it:
function runningNetProfit(n) {
var profitSequence = [0];
var nextYear = (monthlyEstimatedSavings * 12);
for (var i = negSystemCost; i < n - 1; i++) {
profitSequence.push(nextYear);
nextYear = nextYear + profitSequence[i];
}
return profitSequence;
}
console.log(runningNetProfit(20))
I added what I did (all of the code) to a codepen as well, maybe it can make my question more clear, that can be found here The javascript relevant to this question is right at the bottom from line 145. Any advice would be much appreciated.
See if this code works for you:
It takes a given installation cost, the price they pay for electricity, and the number of months, then spits out an array with these numbers.
const installCost = 250000;
const electricityCost = 45000;
const numMonths = 20
const newArray = Array.from({length: numMonths})
const updatedArray = newArray.map((_, index) => index * electricityCost - installCost);
console.log(updatedArray) // returns [-250000,-205000,-160000,-115000,-70000,-25000,20000,65000,110000,155000,200000,245000,290000,335000,380000,425000,470000,515000,560000,605000]
Here's the code sandbox for it: https://codesandbox.io/s/blue-pine-l5rjc8?file=/src/index.js

How do you read and understand this bitshifting code?

So I found some "bit buffer" code in JavaScript which should help me out on my journey to, well, write a bit buffer (only I'm doing it in a different language).
I took the key parts of the code and pasted it here (for LittleEndian only):
function LittleEndianView(size) {
Object.defineProperty(this, 'native', {
value: new Uint8Array(size)
})
}
LittleEndianView.prototype.get = function(bits, offset) {
let available = (this.native.length * 8 - offset)
if (bits > available) {
throw new Error('Range error')
}
let value = 0
let i = 0
// why loop through like this?
while (i < bits) {
// remaining bits
const remaining = bits - i
const bitOffset = offset & 7
const currentByte = this.native[offset >> 3]
const read = Math.min(remaining, 8 - bitOffset)
const a = 0xFF << read
mask = ~a
const b = currentByte >> bitOffset
readBits = b & mask
const c = readBits << i
value = value | c
offset += read
i += read
}
return value >>> 0
}
LittleEndianView.prototype.set = function(bits, offset) {
const available = (this.native.length * 8 - offset)
if (bits > available) {
throw new Error('Range error')
}
let i = 0
while (i < bits) {
const remaining = bits - i
const bitOffset = offset & 7
const byteOffset = offset >> 3
const finished = Math.min(remaining, 8 - bitOffset)
const mask = ~(0xFF << finished)
const writeBits = value & mask
const value >>= finished
const destMask = ~(mask << bitOffset)
const byte = this.view[byteOffset]
this.native[byteOffset] = (byte & destMask) | (writeBits << bitOffset)
offset += finished
i += finished
}
}
I would like help on the comments, on what each piece means. It seems there are a lot of bit manipulation tricks that I am not aware of. For example, if I search google for "bitshift right" or "bitshift left", I get the obvious answer of shifting right or left. But why did they do the bitshift right there, with that number? Why did they negate that number? Why did they & or | that number?
I am trying to go through this code line by line and comment it out, but I am struggling writing comments because I don't know why they are applying the bitshift operations when they do.
So my main question is, how do you go about reading this bitshifting code and know why the bitshift is performed? I am going to want to be reading how md5 and other way more complex hash algorithms and image processing algorithms and other "bit" algorithms work, but first I think I need to know when to apply the bitshift operators, because just knowing how they work doesn't help much.
As a deeper question, perhaps this could be answered here... If you are given bit manipulation code without comments or good variable names, how do you figure out what it's doing?
Sidenote, is there a book or something that lists all the common bit tricks? I have seen this and others, but they are all very short.

Javascript Help - selfDividingNumbers Algorithm producing all 0's

Greetings Stack Overflow!
First off, this is my first question!
I am trying to solve the selfDividingNumbers algorithm and I ran into this interesting problem. This function is supposed to take a range of numbers to check if they are self dividing.
Self Dividing example:
128 is a self-dividing number because
128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
My attempt with Javascript.
/*
selfDividingNumbers( 1, 22 );
*/
var selfDividingNumbers = function(left, right) {
var output = [];
while(left <= right){
// convert number into an array of strings, size 1
var leftString = left.toString().split();
// initialize digit iterator
var currentDigit = leftString[0];
for(var i = 0; i < leftString.length; i++){
currentDigit = parseInt(leftString[i])
console.log( left % currentDigit );
}
// increment lower bound
left++;
}
return output
};
When comparing the current lower bound to the current digit of the lower bound, left % currentDigit it always produces zero! I figure this is probably a type error but I am unsure of why and would love for someone to point out why!
Would also like to see any other ideas to avoid this problem!
I figured this was a good chance to get a better handle on Javascript considering I am clueless as to why my program is producing this output. Any help would be appreciated! :)
Thanks Stack Overflow!
Calling split() isn't buying you anything. Remove it and you'll get the results you expect. You still have to write the code to populate output though.
The answer by #Joseph may fix your current code, but I think there is a potentially easier way to go about doing this. Consider the following script:
var start = 128;
var num = start;
var sd = true;
while (num > 0) {
var last = num % 10;
if (start % last != 0) {
sd = false;
break;
}
num = Math.floor(num / 10);
}
if (sd) {
print("Is self dividing");
}
else {
print("Is NOT self dividing");
}
Demo
To test each digit in the number for its ability to cleanly divide the original number, you can simply use a loop. In each iteration, check num % 10 to get the current digit, and then divide the number by ten. If we never see a digit which can not divide evenly, then the number is not self dividing, otherwise it is.
So the string split method takes the string and returns an array of string parts. The method expects a parameter, however, the dividing element. If no dividing element is provided, the method will return only one part, the string itself. In your case, what you probably intended was to split the string into individual characters, which would mean the divider would be the empty string:
var leftString = left.toString().split('');
Since you are already familiar with console.log, note that you could also use it to debug your program. If you are confused about the output of left % currentDigit, one thing you could try is logging the variables just before the call,
console.log(typeof left, left, typeof currentDigit, currentDigit)
which might give you ideas about where to look next.

Creating a Profit Calculator

I'm trying to create a basic profit calculator but I am struggling with one issue.
I've written some basic javascript and the formula almost works. However my issue is that the decimal point doesn't seem to want to work properly. For example:
What is the case cost: 2.80
How may units per case: 2
What is the sell price: 3.15
Total Profit = 1.75 Profit should of course be, 0.175
I'm a complete newbie to JavaScript so your help would be much appreciated.
<form id="profitCalculator">
<p><label>What is the case cost? <input type="text" name="casecost"></label></p>
<p><label>How many packs / units per case? <input type="text" name="packs"></label></p>
<p><label>What is the sell price? <input type="text" name="sell_price"></label></p>
<p>Total profit £: <input type="text" name="profit"></p>
document.getElementById('profitCalculator').onclick = function () {
var casecost = this.elements['casecost'].value || 0;
var packs = this.elements['packs'].value || 0;
var sell_price = this.elements['sell_price'].value || 0;
var profit = sell_price - casecost / packs;
this.elements['profit'].value = profit.toFixed(2); }
Thanks
It should be
var profit = (sell_price - casecost) / packs;
BUT - Never calculate currency with decimals in Javascript!
Javascript will truncate decimal values when they become to long, possibly resulting in nasty rounding errors. Always multiply your values by 100, then calculate everything, and at last, divide by 100 again.
Look at order of operations, you may know this as 'BODMAS'
Supporting Link: http://www.mathsisfun.com/operation-order-bodmas.html
Change to (sell_price - casecost) / packs;
your problem occurs because operators procedence.
var profit = sell_price - casecost / packs;
/ (division) occurs first than - (minus).
As your example.
2.80 / 2 = 1.4
3.15 - 1.4 = 1.75
You should put some parenthesis covering what has to priority, in your case, to get the value 0.175, you should put the like this.
(3.15 - 2.80) / 2 = 0.175
in code
var profit = (sell_price - casecost) / packs;
See MDN's reference on Operator Precedence and you'll see that division (and multiplication) is done before addition or subtraction. So you have essentially:
3.15 - (2.80 / 2) = 1.75
Instead of:
(3.15 - 2.80) / 2 = 0.175
Also note, as #Adrian Schmidt pointed out, using floating point numbers for math is a bad idea. If you do that above calculation in javascript you actually get:
0.17500000000000004
Because computers don't have infinite precision when representing floating point numbers. See, for example: Is floating point math broken?
So your formula should be:
(sell_price - casecost) / packs
Another thing to consider is that the values you get from your text boxes are strings, not numbers. Your formula works because there is no - operator for strings, so javascript automatically converts your values to numbers. But this is a dangerous thing to rely on. For example, if you did this:
sell_price + casecost
With your example inputs, the result would be:
"3.152.80"
Because it's doing string concatenation, not addition.
So it's worth using parseFloat to convert your strings. (and parseInt for packs as it is, presumably, an integer)
So a complete example might look like this:
var casecost = parseFloat(this.elements['casecost'].value) * 100 || 0;
var packs = parseInt(this.elements['packs'].value, 10) || 0;
var sell_price = parseFloat(this.elements['sell_price'].value) * 100 || 0;
var profit = ((sell_price - casecost) / packs) / 100;
this.elements['profit'].value = profit.toFixed(2);
Also note that if packs is 0, then you'll have a divide by zero error. You'll want to add logic to check the value of packs and do something when it's zero (not calculate the profit).

Categories