Calculating Relative Strength Index

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!

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647`` ``````MSFT.push_back(msft); if (MSFT.back() > *(MSFT.rbegin()+1) ) { u = MSFT.back() - *(MSFT.rbegin()+1); U.push_back(u); d = 0; D.push_back(d); } else if (MSFT.back() < *(MSFT.rbegin()+1) ) { d = *(MSFT.rbegin()+1) - MSFT.back(); D.push_back(d); u = 0; U.push_back(u); } else { u = 0; U.push_back(u); d = 0; D.push_back(d); } EMAU = alphaRSI*U.back()+(*(EMAUVEC.rbegin()+1))*(1-alphaRSI); EMAUVEC.push_back(EMAU); EMAD = alphaRSI*D.back()+(*(EMADVEC.rbegin()+1))*(1-alphaRSI); EMADVEC.push_back(EMAD); rs = (EMAUVEC.back())/(EMADVEC.back()); rsi = 100 - (100/(1+rs)); RSI.push_back(rsi);``````
Topic archived. No new replies allowed.