如果有个股票拥有每日开盘价,收盘价,最高价,最低价,日期,用springboot使用ta-lib库写出MACD携带日期,并优化计算过程
时间: 2023-09-27 15:05:32 浏览: 158
首先,需要在项目的pom.xml中添加ta-lib库的依赖:
```
<dependency>
<groupId>com.tictactec</groupId>
<artifactId>ta-lib</artifactId>
<version>0.4.0</version>
</dependency>
```
然后,可以使用以下代码来实现MACD指标的计算:
```java
import org.ta4j.core.*;
import org.ta4j.core.indicators.MACDIndicator;
import org.ta4j.core.indicators.helpers.ClosePriceIndicator;
import org.ta4j.core.indicators.helpers.HighPriceIndicator;
import org.ta4j.core.indicators.helpers.LowPriceIndicator;
import org.ta4j.core.indicators.helpers.OpenPriceIndicator;
import org.ta4j.core.num.DoubleNum;
import org.ta4j.core.num.Num;
import org.ta4j.core.trading.rules.OverIndicatorRule;
import org.ta4j.core.trading.rules.UnderIndicatorRule;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class MACDExample {
public static void main(String[] args) {
// 创建时间序列
List<Tick> ticks = createTicks();
TimeSeries series = new BaseTimeSeries("data", ticks);
// 创建指标
OpenPriceIndicator openPrice = new OpenPriceIndicator(series);
ClosePriceIndicator closePrice = new ClosePriceIndicator(series);
HighPriceIndicator highPrice = new HighPriceIndicator(series);
LowPriceIndicator lowPrice = new LowPriceIndicator(series);
Num fastEMA = DoubleNum.valueOf(12);
Num slowEMA = DoubleNum.valueOf(26);
Num signalEMA = DoubleNum.valueOf(9);
MACDIndicator macd = new MACDIndicator(closePrice, fastEMA, slowEMA);
EMAIndicator signal = new EMAIndicator(macd, signalEMA);
// 计算指标
for (int i = 0; i < series.getTickCount(); i++) {
System.out.println(series.getTick(i).getEndTime().toString() + ": " + macd.getValue(i).doubleValue() + " " + signal.getValue(i).doubleValue());
}
}
private static List<Tick> createTicks() {
List<Tick> ticks = new ArrayList<>();
ticks.add(new BaseTick(LocalDate.of(2021, 8, 1), 10, 12, 13, 9, 100));
ticks.add(new BaseTick(LocalDate.of(2021, 8, 2), 11, 13, 14, 10, 200));
ticks.add(new BaseTick(LocalDate.of(2021, 8, 3), 12, 14, 15, 11, 300));
ticks.add(new BaseTick(LocalDate.of(2021, 8, 4), 14, 16, 17, 13, 400));
ticks.add(new BaseTick(LocalDate.of(2021, 8, 5), 15, 17, 18, 14, 500));
ticks.add(new BaseTick(LocalDate.of(2021, 8, 6), 16, 18, 19, 15, 600));
ticks.add(new BaseTick(LocalDate.of(2021, 8, 7), 17, 19, 20, 16, 700));
return ticks;
}
}
```
在这个例子里,我们创建了一个时间序列,包括每日的开盘价、收盘价、最高价、最低价和日期。然后,我们使用ta4j库中的MACDIndicator和EMAIndicator计算MACD指标。最后,我们打印出每个时间点的MACD和信号线值。
在实际应用中,你可以将数据从数据库或者其他数据源中读取,并将计算过程进行优化。
阅读全文