Sub CalculateRSI88() Dim ws As Worksheet Dim rng As Range Dim closeData As Range Dim RSI…
- User
Sub CalculateRSI88()
Dim ws As Worksheet Dim rng As Range Dim closeData As Range Dim RSI As Double Dim period As Integer Dim gainSum As Double Dim lossSum As Double Dim AvgGain As Double Dim AvgLoss As Double Dim RS As Double Dim i As Long 'Set the period for RSI calculation period = 14 'Set the worksheet where the close data is stored Set ws = ThisWorkbook.Worksheets("Sheet1") 'Set the range where the close data is stored (Assuming data starts from row 2 in Column D) Set rng = ws.Range("D2", ws.Cells(ws.Rows.Count, "D").End(xlUp)) 'Calculate RSI for each close data point For Each closeData In rng ' Do not calculate RSI unless there are enough data points If closeData.Row >= period + 1 Then gainSum = 0 lossSum = 0 'Calculate gain and loss sum for given period For i = closeData.Row - period To closeData.Row - 1 'Calculate Gain and Loss If ws.Cells(i + 1, "D") >= ws.Cells(i, "D") Then gainSum = gainSum + ws.Cells(i + 1, "D") - ws.Cells(i, "D") Else lossSum = lossSum + ws.Cells(i, "D") - ws.Cells(i + 1, "D") End If Next i 'Calculate average gain and loss AvgGain = gainSum / period AvgLoss = lossSum / period 'Calculate RS If AvgLoss = 0 Then RS = 100 Else RS = AvgGain / AvgLoss End If 'Calculate RSI RSI = 100 - (100 / (1 + RS)) 'Store RSI in column E ws.Cells(closeData.Row, "F").Value = RSI ws.Cells(closeData.Row, "g").Value = gainSum ws.Cells(closeData.Row, "h").Value = lossSum End If Next closeDataEnd Sub i wrote above code for rsi but real rsi is differented with rsi calculated
- Assistant
It seems that your code calculates the RSI correctly, but there might be a few small adjustments needed to get the exact RSI values you're looking for. Here are a few suggestions:
-
Make sure the range you've selected for the closing prices (column D) is correct. If your data is stored in a different column, you'll need to update the range accordingly.
-
Check whether your data is sorted in ascending or descending date order. The RSI calculation assumes that the most recent closing price is at the bottom of the range. If your data is sorted in descending date order, you'll need to adjust the loop accordingly.
-
Ensure that the period variable is set to an appropriate value for your data. The RSI calculation typically uses a 14-day period, but if you have weekly or monthly data, you might need to adjust the variable accordingly.
-
If the RSI values are still not correct after making these adjustments, it's possible that there are errors in the data itself. Double-check the closing prices in the range you've selected to ensure that they are accurate and properly formatted.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.