LoginSignup
0

posted at

updated at

【v26】一次関数の傾きと切片を計算する

はじめに

過去記事は「auカブコム証券のkabuステーションREST APIに関する記事一覧」。

SMAなどがクロスしたときの勢いを数値で計算したいので、最小二乗法で一次関数の傾きと切片を計算してみた。

計算式

傾き = (x,y)の共分散 ÷ xの分散
切片 = yの平均 - 傾き × xの平均

x, y

xは、n-1本前から1, 2, 3,..., nの整数とする。
yは、1分足の終値とする。

ソース

xが1つづつずれてx * yを計算する必要があるので、2重ループで計算した。

		final int param1 = 5;
		for (int i = 0; i < chartList.size(); i++) {
			ChartInfo ci = chartList.get(i);
			System.out.printf("%s,%d,%d", ci.date, ci.closePrice, ci.flag);
			if (i >= param1 - 1) {
				long cov = 0;
				long sqr = 0;
				int sum1 = 0;
				int sum2 = 0;
				int cnt = 0;
				for (int j = 1; j <= param1; j++) {
					int idx = i - param1 + j;
					ChartInfo ci2 = chartList.get(idx);
					cov += j * ci2.closePrice;
					sqr += j * j;
					sum1 += j;
					sum2 += ci2.closePrice;
					cnt++;
				}
				double mean1 = (double) sum1 / cnt;
				double mean2 = (double) sum2 / cnt;
				double covar = (double) cov / cnt - mean1 * mean2;
				double variance = (double) sqr / cnt - mean1 * mean1;
				double grad = covar / variance;
				double intercept = mean2 - grad * mean1;
				System.out.printf(",%6.2f,%.2f  ", grad, intercept);
				for (int j = 1; j <= param1; j++) {
					double val = grad * j + intercept;
					System.out.printf(",%.2f", val);
				}
			}
			System.out.println();
		}

実行結果

41から45は26565~26630まで連勝しているので、傾きが16.5と大きい。
切片はx=0なので0件目の値で、1件目は切片+傾き×1の値。

2022/05/25 00:41:00,26565,1,  3.50,26548.50  ,26552.00,26555.50,26559.00,26562.50,26566.00
2022/05/25 00:42:00,26570,1,  4.50,26548.50  ,26553.00,26557.50,26562.00,26566.50,26571.00
2022/05/25 00:43:00,26590,1,  6.50,26550.50  ,26557.00,26563.50,26570.00,26576.50,26583.00
2022/05/25 00:44:00,26605,1, 10.50,26547.50  ,26558.00,26568.50,26579.00,26589.50,26600.00
2022/05/25 00:45:00,26630,1, 16.50,26542.50  ,26559.00,26575.50,26592.00,26608.50,26625.00
2022/05/25 00:46:00,26625,1, 15.00,26559.00  ,26574.00,26589.00,26604.00,26619.00,26634.00
2022/05/25 00:47:00,26630,1, 10.00,26586.00  ,26596.00,26606.00,26616.00,26626.00,26636.00

追記:ソースをarchiveブランチへ移動

最新版に移行し、もう使われることはないので、アーカイブする。

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