用Java代码实现股票的kdj计算
时间: 2024-03-11 18:46:57 浏览: 165
基于java的股票系统的实现
5星 · 资源好评率100%
KDJ 是股票领域中常用的技术指标之一,它由三条曲线组成,分别是 K 线、D 线和 J 线。KDJ 的计算非常复杂,需要用到一些中间变量和参数。下面是用 Java 代码实现 KDJ 计算的示例:
```java
public class KDJ {
public static void main(String[] args) {
double[] prices = {10.0, 15.0, 12.0, 18.0, 20.0};
double[] ks = new double[prices.length];
double[] ds = new double[prices.length];
double[] js = new double[prices.length];
int period = 9;
double k1 = 2.0 / 3.0;
double k2 = 1.0 / 3.0;
double[] lows = new double[period];
double[] highs = new double[period];
for (int i = 0; i < prices.length; i++) {
double p = prices[i];
double rsv = 0.0;
if (i >= period) {
double low = Double.MAX_VALUE;
double high = Double.MIN_VALUE;
for (int j = i - period; j < i; j++) {
if (prices[j] < low) {
low = prices[j];
}
if (prices[j] > high) {
high = prices[j];
}
}
lows[i % period] = low;
highs[i % period] = high;
double minLow = Double.MAX_VALUE;
double maxHigh = Double.MIN_VALUE;
for (int j = 0; j < period; j++) {
if (lows[j] < minLow) {
minLow = lows[j];
}
if (highs[j] > maxHigh) {
maxHigh = highs[j];
}
}
rsv = (p - minLow) / (maxHigh - minLow) * 100.0;
}
double k = 0.0;
double d = 0.0;
double j = 0.0;
if (i == period) {
k = 50.0;
d = 50.0;
j = 0.0;
} else if (i > period) {
k = ks[i - 1] * k1 + rsv * k2;
d = ds[i - 1] * k1 + k * k2;
j = 3.0 * k - 2.0 * d;
}
ks[i] = k;
ds[i] = d;
js[i] = j;
}
System.out.println("K: " + Arrays.toString(ks));
System.out.println("D: " + Arrays.toString(ds));
System.out.println("J: " + Arrays.toString(js));
}
}
```
这段代码实现了 KDJ 的计算,其中用到了一个窗口期 period,一般取 9。KDJ 的计算中还需要用到两个参数 k1 和 k2,一般取 2/3 和 1/3。此外,还需要用到两个数组 lows 和 highs,分别保存最近 period 天的最低价和最高价。
阅读全文