Hello everyone, I'm trying to write a program to calculate the RSI of a stock. The following is inside a for loop. MSFT is a vector of Microsoft stock prices. On each iteration of the loop, a new price gets put into the vector. I know MSFT is filled with the correct data.
If the most recent price in MSFT (today) is greater than the second to most recent (yesterday), then subtract yesterday's price from today and call that u, and call d zero.
If the most recent price in MSFT (today) is lesser than the second to most recent (yesterday), then subtract today's price from yesterday's and call that d, and call u zero.
If today is unchanged from yesterday, call both u and d zero.
Calculate the n-period exponential moving average (EMA) of u and d.
define relative strength rs = EMA(u)/EMA(d);
then relative strength rsi = 100 - 100 / (1+rs);
In general capital letters are vectors, i.e U is a vector to store u for calculating the EMA.
The code runs but does not produce the correct numbers, if someone can point out an error I would very much appreciate it. Thank you!
if (MSFT.back() > *(MSFT.rbegin()+1) )
u = MSFT.back() - *(MSFT.rbegin()+1);
d = 0;
else if (MSFT.back() < *(MSFT.rbegin()+1) )
d = *(MSFT.rbegin()+1) - MSFT.back();
u = 0;
u = 0;
d = 0;
EMAU = alphaRSI*U.back()+(*(EMAUVEC.rbegin()+1))*(1-alphaRSI);
EMAD = alphaRSI*D.back()+(*(EMADVEC.rbegin()+1))*(1-alphaRSI);
rs = (EMAUVEC.back())/(EMADVEC.back());
rsi = 100 - (100/(1+rs));