Im trying to recreate Tradingviews pine script RSI code into Javascript code. But having a hard time figuring out how it works. I made the basic RSI using a normal moving average calculation. But the pine script uses exponential weighted moving average. And there documentation is really hard to follow to me. This is the pine script.
//#version=4
study(title="Relative Strength Index", shorttitle="RSI", format=format.price, precision=2, resolution="")
len = input(14, minval=1, title="Length")
src = input(close, "Source", type = input.source)
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
plot(rsi, "RSI", color=#7E57C2)
band1 = hline(70, "Upper Band", color=#787B86)
bandm = hline(50, "Middle Band", color=color.new(#787B86, 50))
band0 = hline(30, "Lower Band", color=#787B86)
fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="Background")
This is what I oould make of it in Javascript:
// Period = 200
// Close variable is 200 closed values. Where [0] in array = oldest, [199] in array = newest value.
/**
* Relative strength index. Based on closed periods.
*
* #param {Array} close
* #param {Integer} period
* #returns
*/
function calculateRSI(close, period) {
// Only calculate if it is worth it. First {period - 1} amount of calculations aren't correct anyway.
if (close.length < period) {
return 50;
}
let averageGain = 0;
let averageLoss = 0;
const alpha = 1 / period;
// Exponential weighted moving average.
for (let i = 1; i < period; i++)
{
let change = close[i] - close[i - 1];
if (change >= 0) {
averageGain = alpha * change + (1 - alpha) * averageGain;
} else {
averageLoss = alpha * -change + (1 - alpha) * averageLoss;
}
}
// Tried this too, but seems to not really matter.
// To get an actual average.
// averageGain /= period;
// averageLoss /= period;
// Calculate relative strength index. Where it can only be between 0 and 100.
var rsi = 100 - (100 / (1 + (averageGain / averageLoss)));
return rsi;
}
The results this function gives on my chart is not too bad, but it just isn't the same as I have it in Tradingview. I belive im missing something that the pine script does and I don't.
Things I dont understand of the pine script:
When does it do a for loop? I don't see it in there functions. If they don't, how do they calculate the average for a period of longer than 2? You have to loop for that right?
How does the rma function work? This is their docs.
I might have too many questions on this, but I think if you show a somewhat working example in Javascript of the RSI calculation like they do. Then I can probably make sense of it.
Is my calculation in Javascript correct to the one in the pine script?
Related
using Javascript in Photoshop Scripting, I wish to change the Opacity of X layers from Opacity 0 to Opacity 100, but in a gradual/slow to lastly hastened manner e.g. 'EaseInCirc' I believe.
The code I am using (not successfully) is: https://jsfiddle.net/09onhmy7/
numberOfLayers = 20;
myOpacity = 0;
x=0;
for(i = 0 ; i < numberOfLayers ; i++){
myIncrements = EaseExpo(i, 1, x, numberOfLayers);
x = myIncrements + myIncrements;
myOpacity = myOpacity + parseInt(myIncrements,10);
if (myOpacity > 100) {myOpacity = 100 ;}
document.write(myOpacity+",");
}
I found the EaseExpo(EaseInCirc) code on-line (http://gizma.com/easing/):
// t = current time
// b = start value
// c = change in value
// d = duration
// (t and d) can be frames
function EaseExpo(t, b, c, d) {
//EaseInCirc
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
}
…but so far the code returns values that don't distribute as expected from 0 - 100 -- and most likely never will, as I don't know how to go about transposing them to suit the 0-100 bounds.
Basically, I'm trying to create an iteration of values (that aren't lineal) from 0 - X to represent a rate of change that slowly ramps up to maximum velocity (I'm pretty sure it’s a squareroot graph/function?) that I'm trying to replicate.
The values that will be input will always start at 0, but could have a maximum of any value.
The trick is, I need to be able to always transpose the end values into a 0-100 result.
e.g. A) 40 values = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,30,32,34,36,39,42,46,51,58,68,83,100
e.g. B) 18 values = 1,3,5,7,9,11,13,15,17,20,23,27,32,39,49,64,88,100
I cant for the life of me work out how to do it -- or should I be using different math to achieve what I want?
Many thanks in advance, Livy
I have some sample data of vibrations analysis from sensors installed on electrical motors. The sampling is made once or, at most, 3 times per day. The values can be expressed in g, gE or mm/s.
I’m developing a personal algorithm in JavaScript to process some samples and perform a DFT. It’s a simple code that uses brute force to process my results. I compared the results (real and imaginary parts) from JavaScript and from MATLAB results and they matched perfectly.
However, my sampling rate is very slow. Because of this, I have a lot of questions which I couldn’t find the answers on my searches:
Is it possible to apply a DFT analysis on a slow sampling data as this?
How can I determine the correct frequency scale for the X axis? It’s complicated for me because I don’t have an explicit Fs (sampling rate) value.
In my case, would it be interesting to apply some window function like Hanning Window (suitable for vibrations analyses)?
JavaScriptCode:
//Signal is a pure one-dimensional of real data (vibration values)
const fft = (signal) => {
const pi2 = 6.2832 //pi const
let inputLength = signal.length;
let Xre = new Array(inputLength); //DFT real part
let Xim = new Array(inputLength); //DFT imaginary part
let P = new Array(inputLength); //Power of spectrum
let M = new Array(inputLength); //Magnitude of spectrum
let angle = 2 * Math.PI / inputLength;
//Hann Window
signal = signal.map((x, index) => {
return x * 0.5 * (1 - Math.cos((2 * Math.PI * index) / (inputLength - 1)));
});
for (let k = 0; k < inputLength; ++k) { // For each output element
Xre[k] = 0; Xim[k] = 0;
for (let n = 0; n < inputLength; ++n) { // For each input element
Xre[k] += signal[n] * Math.cos(angle * k * n);
Xim[k] -= signal[n] * Math.sin(angle * k * n);
}
P[k] = Math.pow(Xre[k], 2) + Math.pow(Xim[k], 2);
M[k] = Math.sqrt(Math.pow(Xre[k], 2) + Math.pow(Xim[k], 2));
}
return { Xre: Xre, Xim: Xim, P: P, M: M.slice(0, Math.round((inputLength / 2) + 1)) };
}
The first figure shows the charts results (time domain on the left side and frequency domain on the right side).
The second figure shows a little bit of my data samples:
Obs.: I'm sorry for the writing. I'm still a beginner English student.
The frequency doesn't matter. A frequency as low as 1/day is just as fine as any other frequency. But consider the Nyquist-Shannon theorem.
This is problematic. You need a fix sampling frequency for a DFT. You could do interpolation as preprocessing. But better would be to do the sampling at fix times.
Problem:
If you go to http://www.newedenfaces.com/ down at the bottom you can see the player leaderboard. Everyone started out with a base score 1400. There are currently over 1100 players in the database, each two being picked randomly every time you vote. As of now, the highest rating is 1572. Furthermore leaderboard is very volatile. Someone who's been in Top 10 just today is now in 70+ range.
I would like score to be more significant. Most people in the leaderboard are only a few ratings apart, and some have even rating.
Sorry for the ugly and verbose code. I'll need to refactor it later.
eloRating: function(winnerIndex) {
var kFactor = 16;
if (winnerIndex == 0) {
// A won
var ratingA = this.collection.at(0).get('rating');
var ratingB = this.collection.at(1).get('rating');
var scoreA = this.collection.at(0).get('wins');
var scoreB = this.collection.at(1).get('wins');
var expectedA = 1.0 / (1.0 + Math.pow(10, ((ratingA - ratingB) / 400)));
var expectedB = 1.0 / (1.0 + Math.pow(10, ((ratingA - ratingB) / 400)));
var newRatingA = ratingA + (kFactor * expectedA);
var newRatingB = ratingB - (kFactor * expectedA);
this.collection.at(0).set('rating', Math.round(newRatingA));
this.collection.at(1).set('rating', Math.round(newRatingB));
} else {
// B won
var ratingA = this.collection.at(0).get('rating');
var ratingB = this.collection.at(1).get('rating');
var scoreA = this.collection.at(0).get('wins');
var scoreB = this.collection.at(1).get('wins');
var expectedA = 1.0 / (1.0 + Math.pow(10, ((ratingB - ratingA) / 400)));
var expectedB = 1.0 / (1.0 + Math.pow(10, ((ratingB - ratingA) / 400)));
var newRatingA = ratingA - (kFactor * expectedA);
var newRatingB = ratingB + (kFactor * expectedA);
this.collection.at(0).set('rating', Math.round(newRatingA));
this.collection.at(1).set('rating', Math.round(newRatingB));
}
Your equation for the expected score is incorrect. For example, by your equation someone 400 points higher would have an expected score of 10/11 (0.909). This is not right, because the actual win probability is higher than this (about 0.919). Here is the real equation:
where D is the number of points in a standard deviation (normally 400 points). This equation has no closed form so a table of values which are precomputed must be used.
Also, more importantly, you are not computing the adjustment correctly. The winner gets (1-e)**k* points. The loser loses (e)**k* points where e is the expected score for the player. So, if Player A is 400 points higher than B and wins then he gets (1-0.919)*k = 1.296 points, and the loser loses 1.296 points. In your calculation the winner is getting 14.7 points (!!!) and loser is losing 14.7 points.
This is my first post but I came up with this and it appears to be a fairly concise way of doing this.
I hope it may help someone.
var aElo = 1400; // player
var bElo = 1400; // opponent
var Res = 1 // Result... 0.5 = draw, 1 = win, 0 = loss
var nElo = aElo+Math.round((32-((Math.floor(aElo/2101)+Math.floor(aElo/2401))*8)) * (Res - (1 / (1 + Math.pow(10, -(aElo - bElo) / 400)))));
alert("Players Elo was "+aElo+" but is now "+nElo);
Using Javascript, how can I generate random numbers that are skewed towards one end or the other of the distribution? Or ideally an point within the range?
For context: I'm creating a UI that has uses a grid of random grey squares. I'm generating the grey's RGB values using Math.random() but would like to be able to skew the greys to be on average darker or lighter while still having the full range from black to white represented.
(I think this is a similar question to Skewing java random number generation toward a certain number but I'm working with Javascript...)
Any help greatly appreciated.
Raise Math.random() to a power to get a gamma curve - this changes the distribution between 0 and 1, but 0 and 1 stay constant endpoints.
var r= Math.pow(Math.random(), 2);
var colour= 'rgb('+r*255+', '+r*255+', '+r*255+')';
For gamma>1, you will get darker output; for 0<gamma<1 you get lighter. (Here, '2' gives you the x-squared curve; the equidistant lightness would be '0.5' for the square-root curve.)
This seems a little crude and less graceful than #bobince's answer, but what the hell.
//setup
var colours = [], num_colours = 10, skew_to = 255, skew_chance = 20;
//get as many RGB vals as required
for (var i=0; i<num_colours; i++) {
//generate random grey
var this_grey = Math.floor(Math.random() * 256);
//skew it towards the #skew_to endpoint, or leave as-is?
if (Math.floor(Math.random() * 100) >= skew_chance && this_grey != skew_to) {
//skew by random amount (0 - difference between curr val and endpoint)
var skew_amount = Math.floor(Math.random() * Math.abs(this_grey - skew_to));
this_grey += ' (skewed to '+(skew_to < this_grey ? this_grey - skew_amount : this_grey + skew_amount)+')';
}
colours.push(this_grey);
}
console.log(colours);
Essentially it generates random greys then decides, based on probably specified (as a percentage) in skew_chance, whether to skew it or not. (In case you wanted to make this occasional, not constant). If it decides to skew, a random number is then added or subtracted from the grey value (depending on whether the skew endpoint is under or above the current value).
This random number is a number between 0 and the absolute difference between the current value and the endpoint, e.g. if current value is 40, and the endpoint is 100, the number added would be between 0 and 60.
Like I say, #bobince's answer is somewhat, er, more graceful!
[This might be a little different approach.]
This approach deals with getting the number in the following fashion:
random = numberToSkewTo + random(-1,1)*stdDeviation
Where:
numberToSkewTo is the number you want to skew towards.
stdDeviation is the deviation from numberToSkewTo
numberToSkewTo + abs(stdDeviation) <= MAX_NUMBER and
numberToSkewTo - abs(stdDeviation) >= MIN_NUMBER
What the following code does is, it pick a random number around the given number with constantly increasing standard deviations. It returns the average of results.
function skew(skewTo,stdDev){
var rand = (Math.random()*2 - 1) + (Math.random()*2 - 1) + (Math.random()*2 - 1);
return skewTo + rand*stdDev;
}
function getRandom(skewTo){
var difference = Math.min(skewTo-MIN_NUMBER, MAX_NUMBER-skewTo);
var steps = 5;
var total = 0.0;
for(var i=1; i<=steps; i++)
total += skew(skewTo, 1.0*i*difference/steps);
return total/steps
}
Lets say I have a list of numbers in the following form(Ignore the | they are there for formating help).
00|00|xx
00|xx|00
xx|00|00
etc.
Rules: XX can be any number between 1 and 50. No XX values can be identical.
Now I select a random set of numbers(no duplicates) from a list qualifying the above format, and randomly add and subtract them. For example
000011 - 002400 - 230000 = -232389
How can I determine the original numbers and if they were added or subtracted solely from -232389? I'm stumped.
Thanks!
EDIT:
I was looking for a function so I ended up having to make one. Its just a proof of concept function so variables names are ugly http://jsfiddle.net/jPW8A/.
There are bugs in the following implementation, and it fails to work in a dozen of scenarios. Check the selected answer below.
function reverse_add_subtract(num){
var nums = [];
while(num != 0){
var str = num.toString(),
L = Math.abs(num).toString().length,
MA = str.match(/^(-?[0-9]?[0-9])([0-9][0-9])([0-9][0-9])*$/);
if(MA){
var num1 = MA[1],
num2 = MA[2];
}else{
var num1 = num,
num2 = 0;
}
if(L%2)L++;
if( num2 > 50){
if(num < 0) num1--;
else num1++;
}
nums.push(num1);
var add = parseInt(num1 + Array(--L).join(0),10);
num = (num-add);
}
return nums;
}
reverse_add_subtract(-122436);
First note that each xx group is constrained from [1, 50). This implies that each associated pair in the number that is in the range [50, 99) is really 100 - xx and this means that it "borrowed from" the group to the left. (It also means that there is only one set of normalized numbers and one solution, if any.)
So given the input 23|23|89 (the initial xx spots from -232389), normalize it -- that is, starting from the right, if the value is >= 50, get 100 - value and carry the 100 rightward (must balance). Example: (23 * 100) + 89 = 2300 * 89 = 2400 - 11 = 2389. And example that shows that it doesn't matter if it's negative as the only things that change is the signs: (-23 * 100) - 89 = -2300 - 89 = -2400 + 11 = -2389
(Notes: Remember, 1 is added to the 23 group to make it 24: the sign of the groups is not actually considered in this step, the math is just to show an example that it's okay to do! It may be possible to use this step to determine the sign and avoid extra math below, but this solution just tries to find the candidate numbers at this step. If there are any repeats of the number groups after this step then there is no solution; otherwise a solution exists.)
The candidate numbers after the normalization are then 23|24|11 (let's say this is aa|bb|cc, for below). All the xx values are now known and it is just a matter of finding the combination such that e * (aa * 10000) + f * (bb * 100) + g * (cc * 1) = -232389. The values aa, bb, cc are known from above and e, f, and g will be either 1 or -1, respectively.
Solution Warning: A method of finding the addition or subtraction given the determined numbers (determined above) is provided below the horizontal separator. Take a break and reflect on the above sections before deciding if the extra "hints" are required.
This can then be solved by utilizing the fact that all the xx groups are not dependent after the normalization. (At each step, try to make the input number for the next step approach zero.)
Example:
-232389 + (23 * 10000) = -2389 (e is -1 because that undoes the + we just did)
-2389 + (24 * 100) = 11 (likewise, f is -1)
11 - (11 * 1) = 0 (0 = win! g is 1 and solution is (-1 * 23 * 10000) + (-1 * 24 * 100) + (1 * 11 * 1) = -232389)
Happy homeworking.
First, your math is wrong. Your leading zeros are converting the first two numbers to octal. If that is the intent, the rest of this post doesn't exactly apply but may be able to be adapted.
11-2400-230000 = -232389
Now the last number is easy, it's always the first two digits, 23 in this case. Remove that:
-232389 + 230000 = -2389
Your 2nd number is the next 100 below this, -2400 in this case. And your final number is simply:
-2389 + 2400 = 11
Aww! Someone posted an answer saying "brute force it" that I was about to respond to with:
function find(num){for(var i=1;i<50;i++){for(var o1=0;o1<2;o1++){for(var j=1;j<50;j++){for(var o2=0;o2<2;o2++){for(var k=1;k<50;k++){var eq;if(eval(eq=(i+(o1?'+':'-')+j+'00'+(o2?'+':'-')+k+'0000'))==num){ return eq; }}}}}}}
they deleted it... :(
It was going to go in the comment, but here's a cleaner format:
function find(num){
for(var i=1;i<50;i++){
for(var o1=0;o1<2;o1++){
for(var j=1;j<50;j++){
for(var o2=0;o2<2;o2++){
for(var k=1;k<50;k++){
var eq;
if(eval(eq=(i+(o1?'+':'-')+j+'00'+(o2?'+':'-')+k+'0000'))==num){ return eq; }
}
}
}
}
}
}