I used the below code to generate the Relative Strength Index (RSI) for a certain stock over a certain period of days. The period of days is 14 days so this RSI is called RSI 14.
The code below generates one value only, because I am providing a starting date and an ending date that between them there are 14 days of trading (excluding holidays).
I want to modify this code to be used on a wider range of dates. Something like a loop that takes from the user a starting date and an ending date (other than the starting/ending mentioned in the code currently) and from the starting date to take top 14 and do the calculation, then to go to the next trading date for same stock and take last 14 dates (including current) and do the calculation, until it reaches to the ending date.
To do this, for a start, the current variables defined starting and ending dates have to be changed of course, or at least the use of them has to be changed, because they currently are used to tell the code when do the 14 days start and when do they end, but that should be actually automated. And maybe instead to use something like Top 14 so that it takes the top 14 rows for that stock ordered by date of course.
Let me know what do you think?
DECLARE @StartingDate smalldatetime
DECLARE @EndingDate smalldatetime
DECLARE @StockID INT
DECLARE @DAYS INT
DECLARE @AG FLOAT
DECLARE @AL FLOAT
DECLARE @RS FLOAT
SET @StartingDate = '20110215'
SET @EndingDate = '20110309'
SET @StockID = 107
SET @DAYS = 14
SET @AG =(
WHERE StockID = @StockID AND (ValueDate BETWEEN @StartingDate AND @EndingDate) AND (Last-Prev)>0
--SELECT @AG AG
SET @AL =(
WHERE StockID = @StockID AND (ValueDate BETWEEN @StartingDate AND @EndingDate) AND (Last-Prev)<0
SET @RS = @AG/ABS(@AL)
SELECT 100 - (100/(1+@RS)) RSI