0
Help us understand the problem. What are the problem?

posted at

updated at

# はじめに

SMAの次はボリンジャーバンドを計算します。
SMA12と±σ、±2σの5つの値になります。

# 2重ループで計算

SMA12はすでに計算できるので、σを計算します。

``````			ChartInfo ci = chartList.get(i);
long sqr = 0;
int sum = 0;
int cnt = 0;
System.out.printf("%s,%d,%d", ci.date, ci.closePrice, ci.flag);
if (i >= 11) {
for (int j = i; j > i - 12; j--) {
ChartInfo ci2 = chartList.get(j);
sqr += ci2.closePrice * ci2.closePrice;
sum += ci2.closePrice;
cnt++;
}
double mean = (double) sum / cnt;
double variance = (double)sqr / cnt - mean * mean;
double sd = Math.sqrt(variance);
System.out.printf(",%.2f,%.2f,%.2f,%.2f,%.2f,%.2f", sd, mean - 2 * sd, mean - sd, mean, mean + sd, mean + 2 * sd);
}
System.out.println();
``````

SMAと同じく、13番目のsqrとsumを足すときに、1番目のsqrとsumを引けば、1重ループで計算できそうです。

# 実行結果

``````2022/05/07 05:00:00,26845,2,50.08,26730.68,26780.76,26830.83,26880.91,26930.99
2022/05/07 05:05:00,26860,2,47.63,26742.66,26790.29,26837.92,26885.55,26933.18
2022/05/07 05:10:00,26840,2,43.70,26755.93,26799.63,26843.33,26887.03,26930.73
2022/05/07 05:15:00,26855,2,41.25,26765.84,26807.09,26848.33,26889.58,26930.83
2022/05/07 05:20:00,26850,2,28.75,26799.17,26827.92,26856.67,26885.41,26914.16
2022/05/07 05:25:00,26845,2,22.44,26815.96,26838.40,26860.83,26883.27,26905.71
2022/05/07 05:30:00,26850,2,19.18,26824.96,26844.15,26863.33,26882.52,26901.70
2022/05/07 05:35:00,26850,2,16.89,26825.81,26842.69,26859.58,26876.47,26893.36
2022/05/07 05:40:00,26845,2,17.26,26823.41,26840.66,26857.92,26875.17,26892.43
2022/05/07 05:45:00,26840,2,13.74,26825.85,26839.59,26853.33,26867.08,26880.82
2022/05/07 05:50:00,26825,2,14.78,26820.01,26834.80,26849.58,26864.37,26879.15
2022/05/07 05:55:00,26825,3,10.17,26823.82,26833.99,26844.17,26854.34,26864.51
2022/05/07 06:00:00,26800,2,15.87,26808.67,26824.55,26840.42,26856.29,26872.16
``````

※5/7の翌営業日→5/9

# 追記：和と2乗和を差分で計算する

sqrとsumを差分で計算することで、1重ループになる。

``````			ChartInfo ci = chartList.get(i);
System.out.printf("%s,%d,%d", ci.date, ci.closePrice, ci.flag);
int price = ci.closePrice;
if (cnt < 12) {
sqr += price * price;
sum += price;
cnt++;
} else {
int p_12 = chartList.get(i - 12).closePrice;
sqr += price * price - p_12 * p_12;
sum += price - p_12;
}
if (cnt == 12) {
double mean = (double) sum / cnt;
double variance = (double)sqr / cnt - mean * mean;
double sd = Math.sqrt(variance);
System.out.printf(",%.2f,%.2f,%.2f,%.2f,%.2f,%.2f", sd, mean - 2 * sd, mean - sd, mean, mean + sd, mean + 2 * sd);
}
System.out.println();
``````

# githubソース

Register as a new user and use Qiita more conveniently

1. You get articles that match your needs
2. You can efficiently read back useful information
What you can do with signing up
0
Help us understand the problem. What are the problem?