Here's a VBA sub to calculate Stochastic RSI using Open, High, Low, Close data from columns A to D. Please note that the data should have headers as required.
Option Explicit
Sub CalculateStochasticRSI()
Dim ws As Worksheet
Dim lastRow As Long
Dim rsiPeriod As Integer
Dim stochPeriod As Integer
Dim row As Long
Dim rsi As Double
Dim high As Double, low As Double
Dim stochK As Double, stochD As Double
' Set the periods for RSI and Stochastic calculations
rsiPeriod = 14 ' Change this to the desired RSI period
stochPeriod = 14 ' Change this to the desired Stochastic period
' Set the worksheet containing the data
Set ws = ThisWorkbook.Worksheets("Sheet1") ' Change this to the desired sheet name
' Find the last row with data
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
' Add headers for RSI, Stochastic %K and %D
ws.Cells(1, 5).Value = "RSI"
ws.Cells(1, 6).Value = "Stochastic %K"
ws.Cells(1, 7).Value = "Stochastic %D"
' Loop through the rows with data
For row = rsiPeriod + 1 To lastRow
' Calculate the RSI
rsi = WorksheetFunction.Average( _
WorksheetFunction.IfError( _
WorksheetFunction.Max( _
ws.Range(ws.Cells(row - rsiPeriod, 4), ws.Cells(row, 4)).Offset(, -1) - _
ws.Range(ws.Cells(row - rsiPeriod, 4), ws.Cells(row, 4)).Offset(, -1), _
0), 0)) - _
WorksheetFunction.Average( _
WorksheetFunction.IfError( _
WorksheetFunction.Max( _
ws.Range(ws.Cells(row - rsiPeriod, 4), ws.Cells(row, 4)).Offset(, -1) - _
ws.Range(ws.Cells(row - rsiPeriod, 4), ws.Cells(row, 4)).Offset(, -1), _
0), 0))
rsi = rsi / (rsi + 1)
' Store RSI value in column E
ws.Cells(row, 5).Value = rsi
' Calculate Stochastic %K and %D
If row >= rsiPeriod + stochPeriod Then
high = WorksheetFunction.Max(ws.Range(ws.Cells(row - stochPeriod, 4), ws.Cells(row, 4)).Offset(, -3))
low = WorksheetFunction.Max(ws.Range(ws.Cells(row - stochPeriod, 4), ws.Cells(row, 4)).Offset(, -2))
stochK = (rsi - low) / (high - low)
' Store Stochastic %K value in column F
ws.Cells(row, 6).Value = stochK
' Calculate the Stochastic %D
stochD = WorksheetFunction.Average(ws.Range(ws.Cells(row - stochPeriod + 1, 6), ws.Cells(row, 6)))
' Store Stochastic %D value in column G
ws.Cells(row, 7).Value = stochD
End If
Next row
End Sub
The Stochastic RSI values will be stored in columns E, F and G with headers "RSI", "Stochastic %K", and "Stochastic %D" respectively.