LinearRegression.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /**
  2. *
  3. * (c) 2010-2021 Kamil Kulig
  4. *
  5. * License: www.highcharts.com/license
  6. *
  7. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  8. *
  9. * */
  10. 'use strict';
  11. var __extends = (this && this.__extends) || (function () {
  12. var extendStatics = function (d, b) {
  13. extendStatics = Object.setPrototypeOf ||
  14. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  15. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  16. return extendStatics(d, b);
  17. };
  18. return function (d, b) {
  19. extendStatics(d, b);
  20. function __() { this.constructor = d; }
  21. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  22. };
  23. })();
  24. import SeriesRegistry from '../../../Core/Series/SeriesRegistry.js';
  25. var SMAIndicator = SeriesRegistry.seriesTypes.sma;
  26. import U from '../../../Core/Utilities.js';
  27. var isArray = U.isArray, extend = U.extend, merge = U.merge;
  28. /* *
  29. *
  30. * Class
  31. *
  32. * */
  33. /**
  34. * Linear regression series type.
  35. *
  36. * @private
  37. * @class
  38. * @name Highcharts.seriesTypes.linearregression
  39. *
  40. * @augments Highcharts.Series
  41. */
  42. var LinearRegressionIndicator = /** @class */ (function (_super) {
  43. __extends(LinearRegressionIndicator, _super);
  44. function LinearRegressionIndicator() {
  45. var _this = _super !== null && _super.apply(this, arguments) || this;
  46. /* *
  47. *
  48. * Properties
  49. *
  50. * */
  51. _this.data = void 0;
  52. _this.options = void 0;
  53. _this.points = void 0;
  54. return _this;
  55. }
  56. /* *
  57. *
  58. * Functions
  59. *
  60. * */
  61. /**
  62. * Return the slope and intercept of a straight line function.
  63. * @private
  64. * @param {Highcharts.LinearRegressionIndicator} this indicator to use
  65. * @param {Array<number>} xData - list of all x coordinates in a period
  66. * @param {Array<number>} yData - list of all y coordinates in a period
  67. * @return {Highcharts.RegressionLineParametersObject}
  68. * object that contains the slope and the intercept
  69. * of a straight line function
  70. */
  71. LinearRegressionIndicator.prototype.getRegressionLineParameters = function (xData, yData) {
  72. // least squares method
  73. var yIndex = this.options.params.index, getSingleYValue = function (yValue, yIndex) {
  74. return isArray(yValue) ? yValue[yIndex] : yValue;
  75. }, xSum = xData.reduce(function (accX, val) {
  76. return val + accX;
  77. }, 0), ySum = yData.reduce(function (accY, val) {
  78. return getSingleYValue(val, yIndex) + accY;
  79. }, 0), xMean = xSum / xData.length, yMean = ySum / yData.length, xError, yError, formulaNumerator = 0, formulaDenominator = 0, i, slope;
  80. for (i = 0; i < xData.length; i++) {
  81. xError = xData[i] - xMean;
  82. yError = getSingleYValue(yData[i], yIndex) - yMean;
  83. formulaNumerator += xError * yError;
  84. formulaDenominator += Math.pow(xError, 2);
  85. }
  86. slope = formulaDenominator ?
  87. formulaNumerator / formulaDenominator : 0; // don't divide by 0
  88. return {
  89. slope: slope,
  90. intercept: yMean - slope * xMean
  91. };
  92. };
  93. /**
  94. * Return the y value on a straight line.
  95. * @private
  96. * @param {Highcharts.RegressionLineParametersObject} lineParameters
  97. * object that contains the slope and the intercept
  98. * of a straight line function
  99. * @param {number} endPointX - x coordinate of the point
  100. * @return {number} - y value of the point that lies on the line
  101. */
  102. LinearRegressionIndicator.prototype.getEndPointY = function (lineParameters, endPointX) {
  103. return lineParameters.slope * endPointX + lineParameters.intercept;
  104. };
  105. /**
  106. * Transform the coordinate system so that x values start at 0 and
  107. * apply xAxisUnit.
  108. * @private
  109. * @param {Array<number>} xData - list of all x coordinates in a period
  110. * @param {number} xAxisUnit - option (see the API)
  111. * @return {Array<number>} - array of transformed x data
  112. */
  113. LinearRegressionIndicator.prototype.transformXData = function (xData, xAxisUnit) {
  114. var xOffset = xData[0];
  115. return xData.map(function (xValue) {
  116. return (xValue - xOffset) / xAxisUnit;
  117. });
  118. };
  119. /**
  120. * Find the closest distance between points in the base series.
  121. * @private
  122. * @param {Array<number>} xData list of all x coordinates in the base series
  123. * @return {number} - closest distance between points in the base series
  124. */
  125. LinearRegressionIndicator.prototype.findClosestDistance = function (xData) {
  126. var distance, closestDistance, i;
  127. for (i = 1; i < xData.length - 1; i++) {
  128. distance = xData[i] - xData[i - 1];
  129. if (distance > 0 &&
  130. (typeof closestDistance === 'undefined' ||
  131. distance < closestDistance)) {
  132. closestDistance = distance;
  133. }
  134. }
  135. return closestDistance;
  136. };
  137. // Required to be implemented - starting point for indicator's logic
  138. LinearRegressionIndicator.prototype.getValues = function (baseSeries, regressionSeriesParams) {
  139. var xData = baseSeries.xData, yData = baseSeries.yData, period = regressionSeriesParams.period, lineParameters, i, periodStart, periodEnd,
  140. // format required to be returned
  141. indicatorData = {
  142. xData: [],
  143. yData: [],
  144. values: []
  145. }, endPointX, endPointY, periodXData, periodYData, periodTransformedXData, xAxisUnit = this.options.params.xAxisUnit ||
  146. this.findClosestDistance(xData);
  147. // Iteration logic: x value of the last point within the period
  148. // (end point) is used to represent the y value (regression)
  149. // of the entire period.
  150. for (i = period - 1; i <= xData.length - 1; i++) {
  151. periodStart = i - period + 1; // adjusted for slice() function
  152. periodEnd = i + 1; // (as above)
  153. endPointX = xData[i];
  154. periodXData = xData.slice(periodStart, periodEnd);
  155. periodYData = yData.slice(periodStart, periodEnd);
  156. periodTransformedXData = this.transformXData(periodXData, xAxisUnit);
  157. lineParameters = this.getRegressionLineParameters(periodTransformedXData, periodYData);
  158. endPointY = this.getEndPointY(lineParameters, periodTransformedXData[periodTransformedXData.length - 1]);
  159. // @todo this is probably not used anywhere
  160. indicatorData.values.push({
  161. regressionLineParameters: lineParameters,
  162. x: endPointX,
  163. y: endPointY
  164. });
  165. indicatorData.xData.push(endPointX);
  166. indicatorData.yData.push(endPointY);
  167. }
  168. return indicatorData;
  169. };
  170. /**
  171. * Linear regression indicator. This series requires `linkedTo` option to be
  172. * set.
  173. *
  174. * @sample {highstock} stock/indicators/linear-regression
  175. * Linear regression indicator
  176. *
  177. * @extends plotOptions.sma
  178. * @since 7.0.0
  179. * @product highstock
  180. * @requires stock/indicators/indicators
  181. * @requires stock/indicators/linearregression
  182. * @optionparent plotOptions.linearregression
  183. */
  184. LinearRegressionIndicator.defaultOptions = merge(SMAIndicator.defaultOptions, {
  185. params: {
  186. /**
  187. * Unit (in milliseconds) for the x axis distances used to
  188. * compute the regression line paramters (slope & intercept) for
  189. * every range. In Highstock the x axis values are always
  190. * represented in milliseconds which may cause that distances
  191. * between points are "big" integer numbers.
  192. *
  193. * Highstock's linear regression algorithm (least squares
  194. * method) will utilize these "big" integers for finding the
  195. * slope and the intercept of the regression line for each
  196. * period. In consequence, this value may be a very "small"
  197. * decimal number that's hard to interpret by a human.
  198. *
  199. * For instance: `xAxisUnit` equealed to `86400000` ms (1 day)
  200. * forces the algorithm to treat `86400000` as `1` while
  201. * computing the slope and the intercept. This may enchance the
  202. * legiblitity of the indicator's values.
  203. *
  204. * Default value is the closest distance between two data
  205. * points.
  206. *
  207. * @sample {highstock} stock/plotoptions/linear-regression-xaxisunit
  208. * xAxisUnit set to 1 minute
  209. *
  210. * @example
  211. * // In Liniear Regression Slope Indicator series `xAxisUnit`is
  212. * // `86400000` (1 day) and period is `3`. There're 3 points in
  213. * // the base series:
  214. *
  215. * data: [
  216. * [Date.UTC(2020, 0, 1), 1],
  217. * [Date.UTC(2020, 0, 2), 3],
  218. * [Date.UTC(2020, 0, 3), 5]
  219. * ]
  220. *
  221. * // This will produce one point in the indicator series that
  222. * // has a `y` value of `2` (slope of the regression line). If
  223. * // we change the `xAxisUnit` to `1` (ms) the value of the
  224. * // indicator's point will be `2.3148148148148148e-8` which is
  225. * // harder to interpert for a human.
  226. *
  227. * @type {number}
  228. * @product highstock
  229. */
  230. xAxisUnit: void 0
  231. },
  232. tooltip: {
  233. valueDecimals: 4
  234. }
  235. });
  236. return LinearRegressionIndicator;
  237. }(SMAIndicator));
  238. extend(LinearRegressionIndicator.prototype, {
  239. nameBase: 'Linear Regression Indicator'
  240. });
  241. SeriesRegistry.registerSeriesType('linearRegression', LinearRegressionIndicator);
  242. /* *
  243. *
  244. * Default Export
  245. *
  246. * */
  247. export default LinearRegressionIndicator;
  248. /**
  249. * A linear regression series. If the
  250. * [type](#series.linearregression.type) option is not specified, it is
  251. * inherited from [chart.type](#chart.type).
  252. *
  253. * @extends series,plotOptions.linearregression
  254. * @since 7.0.0
  255. * @product highstock
  256. * @excluding dataParser,dataURL
  257. * @requires stock/indicators/indicators
  258. * @requires stock/indicators/linearregression
  259. * @apioption series.linearregression
  260. */
  261. ''; // to include the above in the js output