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!



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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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.