最近做的项目需要实现EMA和MACD,但苦于网上没有具体的实现

已经和通达信等主流股票分析软件核对过结果,并将其开源放在GitHub上,含Junit 测试用例。

GitHub地址:https://github.com/wizardbyron/finance-indicators

/**

* Calculate EMA,

*

* @param list

* :Price list to calculate,the first at head, the last at tail.

* @return

*/

public static final Double getEXPMA(final List list, final int number) {

// 开始计算EMA值,

Double k = 2.0 / (number + 1.0);// 计算出序数

Double ema = list.get(0);// 第一天ema等于当天收盘价

for (int i = 1; i < list.size(); i++) {

// 第二天以后,当天收盘 收盘价乘以系数再加上昨天EMA乘以系数-1

ema = list.get(i) * k + ema * (1 - k);

}

return ema;

}

/**

* calculate MACD values

*

* @param list

* :Price list to calculate,the first at head, the last at tail.

* @param shortPeriod

* :the short period value.

* @param longPeriod

* :the long period value.

* @param midPeriod

* :the mid period value.

* @return

*/

public static final HashMap getMACD(final List list, final int shortPeriod, final int longPeriod, int midPeriod) {

HashMap macdData = new HashMap();

List diffList = new ArrayList();

Double shortEMA = 0.0;

Double longEMA = 0.0;

Double dif = 0.0;

Double dea = 0.0;

for (int i = list.size() - 1; i >= 0; i--) {

List sublist = list.subList(0, list.size() - i);

shortEMA = Indicators.getEXPMA(sublist, shortPeriod);

longEMA = Indicators.getEXPMA(sublist, longPeriod);

dif = shortEMA - longEMA;

diffList.add(dif);

}

dea = Indicators.getEXPMA(diffList, midPeriod);

macdData.put("DIF", dif);

macdData.put("DEA", dea);

macdData.put("MACD", (dif - dea) * 2);

return macdData;

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐