How To Compute Relative Strength Index (RSI) in Fortran?

Member

by kadin , in category: Third Party Scripts , 5 months ago

How To Compute Relative Strength Index (RSI) in Fortran?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 5 months ago

@kadin 

To compute the Relative Strength Index (RSI) in Fortran, you can use the following algorithm:

  1. Initialize variables: n: the number of periods to consider for the RSI calculation (typically 14) upsum: the sum of gains over the last n periods downsum: the sum of losses over the last n periods
  2. Iterate through the price data for each period: Calculate the price change (delta) from the previous period If delta is positive, add it to upsum; if delta is negative, add its absolute value to downsum
  3. Calculate the average gain (avgup) and average loss (avgdown) over the last n periods: avgup = upsum / n avgdown = downsum / n
  4. Calculate the Relative Strength (RS): RS = avgup / avgdown
  5. Calculate the RSI using the formula: RSI = 100 - (100 / (1 + RS))


Here is a sample Fortran code snippet to compute the RSI for a given price data:

 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
program RSI_calculation
    implicit none
    integer, parameter :: n = 14
    real :: upsum = 0.0, downsum = 0.0
    real :: avgup, avgdown, RS, RSI
    real :: price(n)
    integer :: i

    ! initialize price data
    price = [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.4, 1.3, 1.2, 1.1, 1.0, 0.9, 0.8, 0.7]

    ! calculate upsum and downsum
    do i = 2, n
        if (price(i) > price(i-1)) then
            upsum = upsum + (price(i) - price(i-1))
        else
            downsum = downsum + abs(price(i) - price(i-1))
        end if
    end do

    ! calculate avgup and avgdown
    avgup = upsum / n
    avgdown = downsum / n

    ! calculate RS and RSI
    RS = avgup / avgdown
    RSI = 100.0 - (100.0 / (1.0 + RS))

    print *, "RSI: ", RSI

end program RSI_calculation


This code snippet demonstrates how to compute the RSI for a simple price data array. You can modify the price data array and adjust the parameters (e.g., n) as needed for your specific use case.