Debian Codegraph @

bqplot/js/src/OHLCModel.ts

raw
1 /* Copyright 2015 Bloomberg Finance L.P.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 import * as d3 from 'd3';
17 import * as _ from 'underscore';
18 import { MarkModel } from './MarkModel';
19 import * as serialize from './serialize';
20
21 export type OHLCData = number[][];
22
23 export class OHLCModel extends MarkModel {
24 defaults() {
25 return {
26 ...MarkModel.prototype.defaults(),
27 _model_name: 'OHLCModel',
28 _view_name: 'OHLC',
29
30 x: [],
31 y: [],
32 scales_metadata: {
33 x: { orientation: 'horizontal', dimension: 'x' },
34 y: { orientation: 'vertical', dimension: 'y' },
35 },
36 marker: 'candle',
37 stroke: null,
38 stroke_width: 1.0,
39 colors: ['green', 'red'],
40 opacities: [],
41 format: 'ohlc',
42 };
43 }
44
45 initialize(attributes, options) {
46 super.initialize(attributes, options);
47
48 this.on_some_change(['x', 'y'], this.update_data, this);
49 this.on_some_change(['preserve_domain'], this.update_domains, this);
50 this.on('change:format', this.updateFormat, this);
51 this.px = { o: -1, h: -1, l: -1, c: -1 };
52 this.mark_data = [];
53 this.update_data();
54 this.update_domains();
55 this.updateFormat();
56 }
57
58 private updateFormat() {
59 this.update_data();
60 this.trigger('format_updated');
61 }
62
63 update_data() {
64 let x = this.get('x');
65 let y = this.get('y');
66 const format = this.get('format');
67
68 // Local private function to report errors in format
69 function printBadFormat(format) {
70 if (console) {
71 console.error("Invalid OHLC format: '" + format + "'");
72 }
73 }
74
75 // Generate positional map and check for duplicate characters
76 this.px = format
77 .toLowerCase()
78 .split('')
79 .reduce(
80 (dict, key, val) => {
81 if (dict[key] !== -1) {
82 printBadFormat(format);
83 x = [];
84 y = [];
85 }
86 dict[key] = val;
87 return dict;
88 },
89 { o: -1, h: -1, l: -1, c: -1 }
90 );
91
92 // We cannot have high without low and vice versa
93 if (
94 (this.px.h !== -1 && this.px.l === -1) ||
95 (this.px.h === -1 && this.px.l !== -1) ||
96 format.length < 2 ||
97 format.length > 4
98 ) {
99 printBadFormat(format);
100 x = [];
101 y = [];
102 } else {
103 // Verify that OHLC data is valid
104 const px = this.px;
105 if (
106 (this.px.h !== -1 &&
107 !y.every((d) => {
108 return d[px.h] === d3.max(d) && d[px.l] === d3.min(d);
109 })) ||
110 !y.every((d) => {
111 return d.length === format.length;
112 })
113 ) {
114 x = [];
115 y = [];
116 if (console) {
117 console.error('Invalid OHLC data');
118 }
119 }
120 }
121
122 // Make x and y data the same length
123 if (x.length > y.length) {
124 x = x.slice(0, y.length);
125 } else if (x.length < y.length) {
126 y = y.slice(0, x.length);
127 }
128
129 this.mark_data = _.zip(x, y);
130 this.update_domains();
131 this.trigger('data_updated');
132 }
133
134 update_domains() {
135 if (!this.mark_data) {
136 return;
137 }
138 const scales = this.get('scales');
139 const xScale = scales.x,
140 yScale = scales.y;
141 let min_x_dist = Number.POSITIVE_INFINITY;
142 let max_y_height = 0;
143 let dist = 0;
144 let height = 0;
145
146 /*
147 * Compute the minimum x distance between the data points. We will
148 * use this to pad either side of the x domain.
149 * Also compute the maximum height of all of the marks (i.e. maximum
150 * distance from high to low) and use that to pad the y domain.
151 */
152 for (let i = 0; i < this.mark_data.length; i++) {
153 if (i > 0) {
154 dist = this.mark_data[i][0] - this.mark_data[i - 1][0];
155 if (dist < min_x_dist) {
156 min_x_dist = dist;
157 }
158 }
159 height = this.mark_data[i][this.px.h] - this.mark_data[i][this.px.l];
160 if (height > max_y_height) {
161 max_y_height = height;
162 }
163 }
164 if (this.mark_data.length < 2) {
165 min_x_dist = 0;
166 }
167
168 let min;
169 let max;
170 // X Scale
171 if (!this.get('preserve_domain').x && this.mark_data.length !== 0) {
172 if (xScale.type === 'ordinal') {
173 xScale.compute_and_set_domain(
174 this.mark_data.map((d) => {
175 return d[0];
176 })
177 );
178 } else {
179 min = d3.min(
180 this.mark_data.map((d) => {
181 return d[0];
182 })
183 );
184 max = d3.max(
185 this.mark_data.map((d) => {
186 return d[0];
187 })
188 );
189 if (max instanceof Date) {
190 max = max.getTime();
191 }
192 xScale.set_domain(
193 [min - min_x_dist / 2, max + min_x_dist / 2],
194 this.model_id + '_x'
195 );
196 }
197 } else {
198 xScale.del_domain([], this.model_id + '_x');
199 }
200
201 // Y Scale
202 if (!this.get('preserve_domain').y && this.mark_data.length !== 0) {
203 // Remember that elem contains OHLC data here so we cannot use
204 // compute_and_set_domain
205 let top = this.px.h;
206 let bottom = this.px.l;
207 if (top === -1 || bottom === -1) {
208 top = this.px.o;
209 bottom = this.px.c;
210 }
211 min = d3.min(
212 this.mark_data.map((d) => {
213 return d[1][bottom] < d[1][top] ? d[1][bottom] : d[1][top];
214 })
215 );
216 max = d3.max(
217 this.mark_data.map((d) => {
218 return d[1][top] > d[1][bottom] ? d[1][top] : d[1][bottom];
219 })
220 );
221 if (max instanceof Date) {
222 max = max.getTime();
223 }
224 yScale.set_domain(
225 [min - max_y_height, max + max_y_height],
226 this.model_id + '_y'
227 );
228 } else {
229 yScale.del_domain([], this.model_id + '_y');
230 }
231 }
232
233 get_data_dict(data, index) {
234 const return_val = {
235 index: index,
236 x: data.x,
237 };
238
239 ['open', 'low', 'high', 'close'].forEach((str) => {
240 return_val[str] = data.y[this.px[str.substr(0, 1)]];
241 });
242
243 return return_val;
244 }
245
246 static serializers = {
247 ...MarkModel.serializers,
248 x: serialize.array_or_json_serializer,
249 y: serialize.array_or_json_serializer,
250 };
251
252 px: { o: number; h: number; l: number; c: number };
253
254 mark_data: OHLCData;
255 }