I'm attempting to make a stock trading game in Javascript and I've been trying to find an algorithm to generate fake stock prices. Currently, each Stock
object has a minimum value, maximum value, and volatility which I will explain later. The code is as follows:
Stock.prototype.generateValue = function () {
//mod = probability that the value will decrease next turn
var mod = 0.5;
if (this.value > this.max) mod = 0.8;
if (this.value < this.min) mod = 0.2;
var dir = (Math.random() >= mod) ? 1 : -1;
//maxToAdd = max amount that the value can change
var maxToAdd = (this.max - this.min) * this.volatility / 100;
this.value += (Math.random() * maxToAdd * dir);
//value can't be 0 -- random number from 0 to 10
if (this.value < 0) this.value = Math.random()*10;
//rounds to 2 decimal places
this.value = (Math.round(100*this.value))/100;
this.pastValues[this.pastValues.length] = this.value;
return this.value;
};
Right now, if the current value is within the allowed range (minimum to maximum), then it has a 50% chance of going up and a 50% chance of going down. If it is out of said range, then it has an 80% chance of heading back towards the range and a 20% chance of heading farther out.
Volatility is how much the stock changes on average. Each turn, it changes by a random number between \$0\$ and \$\frac{volatility}{100} \cdot{range}\$ - that is, the volatility is the percentage of the entire range that it can change each turn (if anyone understands this and can explain it better, I would appreciate it).
The results so far have been pretty believable, but if there's any better algorithm that can be found it would be helpful. I would like something that isn't so, well, random. My algorithm stays between the range but there's not a ton of room for something unexpected to happen.
Some screenshots of results (the second is a new chart, but zoomed in on the lower values):