用java写一个 股票dmi指标计算
时间: 2023-08-04 17:39:42 浏览: 163
以下是一个简单的Java程序,用于计算股票的DMI指标:
```java
import java.util.ArrayList;
public class DMICalculator {
// 计算TR值
private static double calculateTR(double high, double low, double prevClose) {
double tr1 = Math.abs(high - low);
double tr2 = Math.abs(high - prevClose);
double tr3 = Math.abs(low - prevClose);
return Math.max(Math.max(tr1, tr2), tr3);
}
// 计算方向线DI
private static double calculateDI(double[] trList, double[] highList, double[] lowList, int period) {
double[] dmPlusList = new double[trList.length];
double[] dmMinusList = new double[trList.length];
double dmPlusSum = 0;
double dmMinusSum = 0;
for (int i = 0; i < trList.length; i++) {
if (i == 0) {
dmPlusList[i] = 0;
dmMinusList[i] = 0;
} else {
double upMove = highList[i] - highList[i - 1];
double downMove = lowList[i - 1] - lowList[i];
if (upMove > downMove && upMove > 0) {
dmPlusList[i] = upMove;
dmMinusList[i] = 0;
} else if (downMove > upMove && downMove > 0) {
dmPlusList[i] = 0;
dmMinusList[i] = downMove;
} else {
dmPlusList[i] = 0;
dmMinusList[i] = 0;
}
}
if (i >= period) {
dmPlusSum -= dmPlusList[i - period];
dmMinusSum -= dmMinusList[i - period];
}
dmPlusSum += dmPlusList[i];
dmMinusSum += dmMinusList[i];
}
double di = 100 * dmPlusSum / (dmPlusSum + dmMinusSum);
return di;
}
// 计算DMI指标
public static ArrayList<Double> calculateDMI(double[] highList, double[] lowList, double[] closeList, int period) {
ArrayList<Double> dmiList = new ArrayList<Double>();
double[] trList = new double[closeList.length];
double[] diPlusList = new double[closeList.length];
double[] diMinusList = new double[closeList.length];
for (int i = 0; i < closeList.length; i++) {
trList[i] = calculateTR(highList[i], lowList[i], closeList[i]);
if (i >= period) {
double diPlus = calculateDI(trList, highList, lowList, period);
double diMinus = calculateDI(trList, highList, lowList, period);
diPlusList[i] = diPlus;
diMinusList[i] = diMinus;
double adx = 100 * Math.abs(diPlus - diMinus) / (diPlus + diMinus);
dmiList.add(adx);
}
}
return dmiList;
}
// 测试
public static void main(String[] args) {
double[] highList = {10.0, 12.0, 11.0, 13.0, 15.0, 14.0, 16.0, 18.0, 17.0, 19.0};
double[] lowList = {9.0, 11.0, 10.0, 12.0, 14.0, 13.0, 15.0, 17.0, 16.0, 18.0};
double[] closeList = {9.5, 11.5, 10.5, 12.5, 14.5, 13.5, 15.5, 17.5, 16.5, 18.5};
int period = 5;
ArrayList<Double> dmiList = calculateDMI(highList, lowList, closeList, period);
System.out.println(dmiList);
}
}
```
在这个程序中,我们使用了TR值、DI值和DMI值来计算股票的DMI指标。具体来说,TR值代表真实波动幅度,DI值代表方向线,DMI值代表趋向指标。
在计算TR值时,我们使用了最高价、最低价和前一个收盘价来计算。
在计算DI值时,我们首先计算了上升动向和下降动向,然后使用动态平均数来计算DI值。
最后,我们根据DI值计算了DMI值,并将其添加到一个ArrayList中返回。
阅读全文