@samara
To calculate the Relative Strength Index (RSI) in PHP, you can follow these steps:
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 |
function calculateRSI($priceData, $period = 14) { $changes = []; for ($i = 1; $i < count($priceData); $i++) { $change = $priceData[$i] - $priceData[$i-1]; $changes[] = $change; } $gains = $losses = []; foreach ($changes as $change) { if ($change > 0) { $gains[] = $change; } else { $losses[] = abs($change); } } $avgGain = array_sum($gains) / $period; $avgLoss = array_sum($losses) / $period; $RS = $avgGain / $avgLoss; $RSI = 100 - (100 / (1 + $RS)); return $RSI; } // Example usage $priceData = [50, 52, 55, 53, 56, 58, 57, 59, 60, 62, 61, 63, 65, 68]; $rsi = calculateRSI($priceData); echo "RSI: " . $rsi; |
This function takes an array of price data and calculates the RSI for the specified period (default is 14 days). You can adjust the period as needed for your analysis. The function returns the calculated RSI value.