我正在计算RSI
(Relative Strength Index)
。我有这样的数据
**Date|Close|Change|Gain|Loss**
计算它的公式是
RSI = 100 - 100/(1+RS)
where RS = Average Gain / Average Loss
所以我想通过JavaScript
或C#
中的一些编程语言来计算,但我不知道如何在编程语言中转换它或我需要什么步骤。
如果有什么想要了解我的问题,我会尝试解释。
答案 0 :(得分:6)
翻译RSI公式的简单方法:
public static double CalculateRsi(IEnumerable<double> closePrices)
{
var prices = closePrices as double[] ?? closePrices.ToArray();
double sumGain = 0;
double sumLoss = 0;
for (int i = 1; i < prices.Length; i++)
{
var difference = prices[i] - prices[i - 1];
if (difference >= 0)
{
sumGain += difference;
}
else
{
sumLoss -= difference;
}
}
if (sumGain == 0) return 0;
if (Math.Abs(sumLoss) < Tolerance) return 100;
var relativeStrength = sumGain / sumLoss;
return 100.0 - (100.0 / (1 + relativeStrength));
}
有很多项目以不同的方式实施RSI。 An incremental way can be found here
答案 1 :(得分:0)
我会用伪代码编写它,你可以用任何语言轻松编写它。 最简单的编码方式是:
v0 = 0
v1 = 0
v2 = 0
v3 = 1/N
v4 = 0
if Step == 1: #initialisation
v0 = (Price[t] - Price[t-N] ) / N
v1 = mean( abs( diff(Price[(t-N):t] ) ) # average price change over previous N
else
v2 = Price[t] - Price[t-1]
v0 = vv[t-1] + v3 * ( v2 - v0[t-1] )
v1 = v1[t-1] + v3 * ( abs( v2 ) - v1[t-1] )
if v1 != 0:
v4 = v0 / v1
else
v4 = 0
RSI = 50 * ( v4 + 1 )
这可能是在模拟中应用RSI的最有效方法。
答案 2 :(得分:0)
这应该与里加的答案没什么不同,但是它似乎永远不会低于40,所以要小心,也许只是坚持使用TA_LIB?
//Relative Strength Index
function rsi($ar, $period, $opt, $offset=0) //opt: 0=none, 1=exponential, 2=wilder, 3=average all
{
GLOBAL $smoothsteps;
$pag = 0; //Previous Average Losses
$pal = 0; //Previous Average Gains
//Count average losses and gains
$len = sizeof($ar)-1-$offset;
$end = $len-$period-$offset;
for($i = $len; $i > $end; $i--)
{
if($ar[$i] > $ar[$i-1]) //Gain
$pag += $ar[$i] - $ar[$i-1];
else //Loss
$pal += $ar[$i-1] - $ar[$i];
}
$pag /= $period;
$pal /= $period;
//Smooth
$ag = 0; //Average Losses
$al = 0; //Average Gains
for($i = $len; $i > 0; $i--)
{
if($ar[$i] > $ar[$i-1]) //Gain
$ag += $ar[$i] - $ar[$i-1];
else //Loss
$al += $ar[$i-1] - $ar[$i];
}
if($opt == 3) //Average All Three
{
$a = 1 / $smoothsteps;
$tag = $a * $ag + (1 - $a) * $pag;
$tal = $a * $al + (1 - $a) * $pal;
$wag = $pag * 13 + $ag;
$wal = $pal * 13 + $al;
$ag = ($wag+$tag+$pag)/3;
$al = ($wal+$tal+$pal)/3;
}
else if($opt == 2) //Wilder Exp
{
$ag = $pag * 13 + $ag;
$al = $pal * 13 + $al;
}
else if($opt == 1) //Exponential (Lame) [Closest to Trading View]
{
$sa = 1 / $smoothsteps;
$ag = $sa * $ag + (1 - $sa) * $pag;
$al = $sa * $al + (1 - $sa) * $pal;
}
else if($opt == 0) //None
{
$ag = $pag;
$al = $pal;
}
//Relative Strength
$rs = $ag / $al;
//Relative Strength Index
return 100 - (100 / (1+$rs));
}