Debian Codegraph @

bqplot/js/src/OHLC.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 { Mark } from './Mark';
19 import { OHLCModel } from './OHLCModel';
20 import { d3GetEvent } from './utils';
21
22 export class OHLC extends Mark {
23 async render() {
24 this.display_el_classes = ['stick_body'];
25 const base_creation_promise = super.render();
26 this.selected_indices = this.model.get('selected');
27 this.selected_style = this.model.get('selected_style');
28 this.unselected_style = this.model.get('unselected_style');
29
30 this.display_el_classes = ['stick_body', 'stick_tail', 'stick_head'];
31
32 this.displayed.then(() => {
33 this.parent.tooltip_div.node().appendChild(this.tooltip_div.node());
34 this.create_tooltip();
35 });
36
37 await base_creation_promise;
38 this.event_listeners = {};
39 this.process_interactions();
40 this.create_listeners();
41 this.draw();
42 }
43
44 set_ranges() {
45 if (this.scales.x) {
46 this.scales.x.set_range(
47 this.parent.padded_range('x', this.scales.x.model)
48 );
49 }
50 if (this.scales.y) {
51 this.scales.y.set_range(
52 this.parent.padded_range('y', this.scales.y.model)
53 );
54 }
55 }
56
57 set_positional_scales() {
58 this.listenTo(this.scales.x, 'domain_changed', () => {
59 if (!this.model.dirty) {
60 this.draw();
61 }
62 });
63 this.listenTo(this.scales.y, 'domain_changed', () => {
64 if (!this.model.dirty) {
65 this.draw();
66 }
67 });
68 }
69
70 /**
71 * Creates event listeners and binds them to rendered d3 elements
72 */
73 create_listeners() {
74 super.create_listeners.apply(this);
75 this.d3el
76 .on('mouseover', () => {
77 this.event_dispatcher('mouse_over');
78 })
79 .on('mousemove', () => {
80 this.event_dispatcher('mouse_move');
81 })
82 .on('mouseout', () => {
83 this.event_dispatcher('mouse_out');
84 });
85
86 this.listenTo(this.model, 'change:tooltip', this.create_tooltip);
87 this.listenTo(this.model, 'change:interactions', this.process_interactions);
88 this.listenTo(this.model, 'change:selected', this.update_selected);
89 this.listenTo(this.model, 'change:stroke', this.updateStroke);
90 this.listenTo(this.model, 'change:stroke_width', this.updateStrokeWidth);
91 this.listenTo(this.model, 'change:colors', this.updateColors);
92 this.listenTo(this.model, 'change:opacities', this.updateOpacities);
93 this.listenTo(this.model, 'change:marker', this.updateMarker);
94 this.listenTo(this.model, 'format_updated', this.draw);
95 this.listenTo(this.model, 'data_updated', this.draw);
96 this.listenTo(this.parent, 'bg_clicked', () => {
97 this.event_dispatcher('parent_clicked');
98 });
99 }
100
101 /**
102 * Sets event listeners depending on the interaction typr
103 * @param interaction - string representing the interaction
104 */
105 process_click(interaction) {
106 super.process_click(interaction);
107
108 if (interaction === 'select') {
109 this.event_listeners.parent_clicked = this.reset_selection;
110 this.event_listeners.element_clicked = this.ohlc_click_handler;
111 }
112 }
113
114 /**
115 * Resets model state for selected indices
116 */
117 reset_selection() {
118 this.model.set('selected', null);
119 this.selected_indices = null;
120 this.touch();
121 }
122
123 /**
124 * Updates model state with selected indices
125 * @param model - model object
126 * @param value - array of indices
127 */
128 update_selected(model, value) {
129 this.selected_indices = value;
130 this.apply_styles();
131 }
132
133 /**
134 * Updates model state with selected indices (adapted from Bars.ts)
135 * @param args - data object of {x, y, index}
136 */
137 ohlc_click_handler(args) {
138 const index = args.index;
139 const idx = this.model.get('selected') || [];
140 let selected: number[] = Array.from(idx);
141
142 // index of candle i. Checking if it is already present in the list.
143 const elem_index = selected.indexOf(index);
144 // Replacement for "Accel" modifier.
145 const accelKey = d3GetEvent().ctrlKey || d3GetEvent().metaKey;
146 if (elem_index > -1 && accelKey) {
147 // if the index is already selected and if accel key is
148 // pressed, remove the element from the list
149 selected.splice(elem_index, 1);
150 } else {
151 if (d3GetEvent().shiftKey) {
152 //If shift is pressed and the element is already
153 //selected, do not do anything
154 if (elem_index > -1) {
155 return;
156 }
157 //Add elements before or after the index of the current
158 //candle which has been clicked
159 const min_index = selected.length !== 0 ? d3.min(selected) : -1;
160 const max_index =
161 selected.length !== 0
162 ? d3.max(selected)
163 : this.model.mark_data.length;
164 if (index > max_index) {
165 _.range(max_index + 1, index + 1).forEach((i) => {
166 selected.push(i);
167 });
168 } else if (index < min_index) {
169 _.range(index, min_index).forEach((i) => {
170 selected.push(i);
171 });
172 }
173 } else if (accelKey) {
174 //If accel is pressed and the candle is not already selected
175 //add the candle to the list of selected candles.
176 selected.push(index);
177 }
178 // updating the array containing the candle indexes selected
179 // and updating the style
180 else {
181 //if accel is not pressed, then clear the selected ones
182 //and set the current element to the selected
183 selected = [];
184 selected.push(index);
185 }
186 }
187 this.model.set('selected', selected.length === 0 ? null : selected, {
188 updated_view: this,
189 });
190 this.touch();
191 const e = d3GetEvent();
192 if (e.cancelBubble !== undefined) {
193 // IE
194 e.cancelBubble = true;
195 }
196 if (e.stopPropagation) {
197 e.stopPropagation();
198 }
199 e.preventDefault();
200 }
201
202 private updateStroke() {
203 const stroke = this.model.get('stroke');
204 this.d3el.selectAll('.stick').style('stroke', stroke);
205
206 if (this.legendEl) {
207 this.legendEl.selectAll('path').style('stroke', stroke);
208 this.legendEl.selectAll('text').style('fill', stroke);
209 }
210 }
211
212 private updateStrokeWidth() {
213 const stroke_width = this.model.get('stroke_width');
214 this.d3el.selectAll('.stick').attr('stroke-width', stroke_width);
215 }
216
217 private updateColors() {
218 const colors = this.model.get('colors');
219 const up_color = colors[0] ? colors[0] : 'none';
220 const down_color = colors[1] ? colors[1] : 'none';
221
222 // Fill candles based on the opening and closing values
223 this.d3el.selectAll('.stick').style('fill', (d: any) => {
224 return d.y[this.model.px.o] > d.y[this.model.px.c]
225 ? down_color
226 : up_color;
227 });
228
229 if (this.legendEl) {
230 this.legendEl.selectAll('path').style('fill', up_color);
231 }
232 }
233
234 private updateOpacities() {
235 const opacities = this.model.get('opacities');
236 this.d3el.selectAll('.stick').style('opacity', (d, i) => {
237 return opacities[i];
238 });
239
240 if (this.legendEl) {
241 this.legendEl.selectAll('path').attr('opacity', (d, i) => {
242 return opacities[i];
243 });
244 }
245 }
246
247 private updateMarker() {
248 const marker = this.model.get('marker');
249
250 if (this.legendEl && this.rectDim) {
251 this.draw_legend_icon(this.rectDim, this.legendEl);
252 }
253
254 // Redraw existing marks
255 this.drawMarkPaths(
256 marker,
257 this.d3el,
258 this.model.mark_data.map((d, index) => {
259 return d[1];
260 })
261 );
262 }
263
264 private updateSelectedColors(idx_start, idx_end) {
265 let current_range = _.range(idx_start, idx_end + 1);
266 if (current_range.length == this.model.mark_data.length) {
267 current_range = [];
268 }
269 const stroke = this.model.get('stroke');
270 const colors = this.model.get('colors');
271 const up_color = colors[0] ? colors[0] : stroke;
272 const down_color = colors[1] ? colors[1] : stroke;
273 const px = this.model.px;
274
275 _.range(0, this.model.mark_data.length).forEach((d) => {
276 this.d3el.selectAll('#stick' + d).style('stroke', stroke);
277 });
278
279 current_range.forEach((d) => {
280 this.d3el.selectAll('#stick' + d).style('stroke', (d) => {
281 return d[px.o] > d[px.c] ? down_color : up_color;
282 });
283 });
284 }
285
286 invert_range(start_pxl, end_pxl) {
287 if (
288 start_pxl === undefined ||
289 end_pxl === undefined ||
290 this.model.mark_data.length === 0
291 ) {
292 this.updateSelectedColors(-1, -1);
293 return [];
294 }
295
296 const indices = new Uint32Array(_.range(this.model.mark_data.length));
297 const selected = indices.filter((index) => {
298 const elem = this.xPixels[index];
299 return elem >= start_pxl && elem <= end_pxl;
300 });
301
302 let idx_start = -1;
303 let idx_end = -1;
304 if (
305 selected.length > 0 &&
306 (start_pxl !== this.scales.x.scale.range()[0] ||
307 end_pxl !== this.scales.x.scale.range()[1])
308 ) {
309 idx_start = selected[0];
310 idx_end = selected[selected.length - 1];
311 }
312 this.updateSelectedColors(idx_start, idx_end);
313 this.model.set('selected', selected);
314 this.touch();
315 return super.invert_range(start_pxl, end_pxl);
316 }
317
318 invert_point(pixel) {
319 const abs_diff = this.xPixels.map((elem) => {
320 return Math.abs(elem - pixel);
321 });
322 const sel_index = abs_diff.indexOf(d3.min(abs_diff));
323 this.updateSelectedColors(sel_index, sel_index);
324 this.model.set('selected', [sel_index]);
325 this.touch();
326 return;
327 }
328
329 draw() {
330 const x_scale = this.scales.x,
331 y_scale = this.scales.y;
332 this.set_ranges();
333 const colors = this.model.get('colors');
334 const opacities = this.model.get('opacities');
335 const up_color = colors[0] ? colors[0] : 'none';
336 const down_color = colors[1] ? colors[1] : 'none';
337 const px = this.model.px;
338 const stick = this.d3el.selectAll('.stick').data(
339 this.model.mark_data.map((data, index) => {
340 return {
341 x: data[0],
342 y: data[1],
343 index: index,
344 };
345 })
346 );
347
348 // Create new
349 const new_sticks = stick
350 .enter()
351 .append('g')
352 .attr('class', 'stick')
353 .attr('id', (d, i) => {
354 return 'stick' + i;
355 })
356 .style('stroke', this.model.get('stroke'))
357 .style('opacity', (d, i) => {
358 return opacities[i];
359 });
360
361 new_sticks.append('path').attr('class', 'stick_head');
362 new_sticks.append('path').attr('class', 'stick_tail');
363 new_sticks.append('path').attr('class', 'stick_body');
364
365 stick.exit().remove();
366
367 // Determine offset to use for translation
368 let y_index = px.h;
369 if (px.h === -1) {
370 y_index = px.o;
371 }
372 // Update all of the marks
373 this.d3el
374 .selectAll('.stick')
375 .style('fill', (d: any, i) => {
376 return d.y[px.o] > d.y[px.c] ? down_color : up_color;
377 })
378 .attr('stroke-width', this.model.get('stroke_width'));
379 if (x_scale.model.type === 'ordinal') {
380 // If we are out of range, we just set the mark in the final
381 // bucket's range band. FIXME?
382 const x_max = d3.max(this.parent.range('x'));
383 this.d3el.selectAll('.stick').attr('transform', (d: any, i) => {
384 return (
385 'translate(' +
386 ((x_scale.scale(this.model.mark_data[i][0]) !== undefined
387 ? x_scale.scale(this.model.mark_data[i][0])
388 : x_max) +
389 x_scale.scale.bandwidth() / 2) +
390 ',' +
391 (y_scale.scale(d.y[y_index]) + y_scale.offset) +
392 ')'
393 );
394 });
395 } else {
396 this.d3el.selectAll('.stick').attr('transform', (d: any, i) => {
397 return (
398 'translate(' +
399 (x_scale.scale(this.model.mark_data[i][0]) + x_scale.offset) +
400 ',' +
401 (y_scale.scale(d.y[y_index]) + y_scale.offset) +
402 ')'
403 );
404 });
405 }
406
407 this.d3el.selectAll('.stick').on('click', (d, i) => {
408 return this.event_dispatcher('element_clicked', { data: d, index: i });
409 });
410
411 // Draw the mark paths
412 this.drawMarkPaths(
413 this.model.get('marker'),
414 this.d3el,
415 this.model.mark_data.map((d) => {
416 return d[1];
417 })
418 );
419
420 this.xPixels = this.model.mark_data.map((el) => {
421 return x_scale.scale(el[0]) + x_scale.offset;
422 });
423 }
424
425 private drawMarkPaths(type: string, selector, dat) {
426 /* Calculate some values so that we can draw the marks
427 * | <----- high (0,0)
428 * |
429 * --------- <- headline_top (open or close)
430 * | |
431 * | |
432 * | |
433 * --------- <- headline_bottom (open or close)
434 * |
435 * | <----- low
436 *
437 *
438 * | <----- high (0,0)
439 * ____| <----- open
440 * |
441 * |
442 * |
443 * |____ <- close
444 * | <----- low
445 */
446
447 const px = this.model.px;
448 const open = [];
449 const high = [];
450 const low = [];
451 const close = [];
452 const headline_top = [];
453 const headline_bottom = [];
454 const to_left_side = [];
455 const scaled_mark_widths = [];
456
457 let min_x_difference = this.calculateMarkWidth();
458 const x_scale = this.scales.x;
459 const y_scale = this.scales.y;
460 let offset_in_x_units;
461 let data_point;
462
463 for (let i = 0; i < dat.length; i++) {
464 if (px.o === -1) {
465 open[i] = undefined;
466 } else {
467 open[i] = y_scale.scale(dat[i][px.o]);
468 }
469 if (px.c === -1) {
470 close[i] = undefined;
471 } else {
472 close[i] = y_scale.scale(dat[i][px.c]);
473 }
474 // We can only compute these (and only need to compute these)
475 // when we have both the open and the close values
476 if (px.o !== -1 && px.c !== -1) {
477 headline_top[i] = dat[i][px.o] > dat[i][px.c] ? open[i] : close[i];
478 headline_bottom[i] = dat[i][px.o] < dat[i][px.c] ? open[i] : close[i];
479 }
480
481 // We never have high without low and vice versa, so we can
482 // check everything at once
483 if (px.h === -1 || px.l === -1) {
484 high[i] = open[i];
485 low[i] = close[i];
486 } else {
487 high[i] = y_scale.scale(dat[i][px.h]);
488 low[i] = y_scale.scale(dat[i][px.l]);
489 }
490
491 data_point = this.model.mark_data[i][0];
492 // Check for dates so that we don't concatenate
493 if (min_x_difference instanceof Date) {
494 min_x_difference = min_x_difference.getTime();
495 }
496 if (data_point instanceof Date) {
497 data_point = data_point.getTime();
498 }
499 offset_in_x_units = data_point + min_x_difference;
500
501 if (x_scale.model.type === 'ordinal') {
502 scaled_mark_widths[i] = x_scale.scale.bandwidth() * 0.75;
503 } else {
504 scaled_mark_widths[i] =
505 (x_scale.scale(offset_in_x_units) - x_scale.scale(data_point)) * 0.75;
506 }
507 to_left_side[i] = (-1 * scaled_mark_widths[i]) / 2;
508 }
509
510 // Determine OHLC marker type
511 // Note: if we do not have open or close data then we have to draw
512 // a bar.
513 if (type == 'candle' && px.o !== -1 && px.c !== -1) {
514 /*
515 * | <-------- head
516 * ---------
517 * | |
518 * | | <---- body
519 * | |
520 * ---------
521 * | <-------- tail
522 */
523 if (px.h !== -1 || px.l !== -1) {
524 selector.selectAll('.stick_head').attr('d', (d, i) => {
525 return this.headPathCandle(headline_top[i] - high[i]);
526 });
527 selector.selectAll('.stick_tail').attr('d', (d, i) => {
528 return this.tailPathCandle(
529 headline_bottom[i] - high[i],
530 low[i] - headline_bottom[i]
531 );
532 });
533 } else {
534 selector.selectAll('.stick_head').attr('d', '');
535 selector.selectAll('.stick_tail').attr('d', '');
536 }
537 selector.selectAll('.stick_body').attr('d', (d, i) => {
538 return this.bodyPathCandle(
539 to_left_side[i],
540 open[i] - high[i],
541 scaled_mark_widths[i],
542 close[i] - open[i]
543 );
544 });
545 } else {
546 // bar
547 /*
548 * |
549 * ____| <-------- head (horizontal piece)
550 * |
551 * | <-------- body (vertical piece)
552 * |
553 * |____ <---- tail (horizontal piece)
554 * |
555 */
556 if (px.o !== -1) {
557 selector.selectAll('.stick_head').attr('d', (d, i) => {
558 return this.headPathBar(
559 to_left_side[i],
560 open[i] - high[i],
561 to_left_side[i] * -1
562 );
563 });
564 } else {
565 selector.selectAll('.stick_head').attr('d', '');
566 }
567 if (px.c !== -1) {
568 selector.selectAll('.stick_tail').attr('d', (d, i) => {
569 return this.tailPathBar(close[i] - high[i], to_left_side[i] * -1);
570 });
571 } else {
572 selector.selectAll('.stick_tail').attr('d', '');
573 }
574 selector.selectAll('.stick_body').attr('d', (d, i) => {
575 return this.bodyPathBar(low[i] - high[i]);
576 });
577 }
578 }
579
580 /* SVG path for head of candle */
581 private headPathCandle(height: number) {
582 return 'm0,0 l0,' + height;
583 }
584
585 /* SVG path for tail of candle */
586 private tailPathCandle(yOffset: number, height: number) {
587 return 'm0,' + yOffset + ' l0,' + height;
588 }
589
590 /* SVG path for body of candle */
591 private bodyPathCandle(xOffset, yOffset, width, height) {
592 return (
593 'm' +
594 xOffset +
595 ',' +
596 yOffset +
597 ' l' +
598 width +
599 ',0' +
600 ' l0,' +
601 height +
602 ' l' +
603 -1 * width +
604 ',0' +
605 ' z'
606 );
607 }
608
609 /* SVG path for head of bar */
610 private headPathBar(xOffset, yOffset, width) {
611 return 'm' + xOffset + ',' + yOffset + ' l' + width + ',0';
612 }
613
614 /* SVG path for tail of bar */
615 private tailPathBar(yOffset, width) {
616 return 'm0,' + yOffset + ' l' + width + ',0';
617 }
618
619 /* SVG path for body of bar */
620 private bodyPathBar(height: number) {
621 return 'm0,0 l0,' + height;
622 }
623
624 private calculateMarkWidth() {
625 /*
626 * Calculate the mark width for this data set based on the minimum
627 * distance between consecutive points.
628 */
629 let min_distance: any = Number.POSITIVE_INFINITY;
630 const scales = this.model.get('scales');
631
632 for (let i = 1; i < this.model.mark_data.length; i++) {
633 const dist = this.model.mark_data[i][0] - this.model.mark_data[i - 1][0];
634 if (dist < min_distance) {
635 min_distance = dist;
636 }
637 }
638 // Check if there are less than two data points
639 if (min_distance === Number.POSITIVE_INFINITY) {
640 min_distance = (scales.x.domain[1] - scales.x.domain[0]) / 2;
641 }
642 if (min_distance < 0) {
643 min_distance = -1 * min_distance;
644 }
645 return min_distance;
646 }
647
648 relayout() {
649 this.set_ranges();
650 this.d3el
651 .select('.intselmouse')
652 .attr('width', this.width)
653 .attr('height', this.height);
654
655 // We have to redraw every time that we relayout
656 this.draw();
657 }
658
659 draw_legend(elem, x_disp, y_disp, inter_x_disp, inter_y_disp) {
660 const stroke = this.model.get('stroke');
661 const colors = this.model.get('colors');
662 const up_color = colors[0] ? colors[0] : 'none';
663 this.rectDim = inter_y_disp * 0.8;
664
665 this.legendEl = elem
666 .selectAll('#legend' + this.uuid)
667 .data([this.model.mark_data]);
668
669 const leg = this.legendEl
670 .enter()
671 .append('g')
672 .attr('transform', (d, i) => {
673 return 'translate(0, ' + (i * inter_y_disp + y_disp) + ')';
674 })
675 .attr('class', 'legend')
676 .attr('id', 'legend' + this.uuid)
677 .style('fill', up_color)
678 .on('mouseover', _.bind(this.highlight_axes, this))
679 .on('mouseout', _.bind(this.unhighlight_axes, this));
680
681 leg.append('path').attr('class', 'stick_head stick');
682 leg.append('path').attr('class', 'stick_tail stick');
683 leg
684 .append('path')
685 .attr('class', 'stick_body stick')
686 .style('fill', up_color);
687
688 // Add stroke color and set position
689 leg
690 .selectAll('path')
691 .style('stroke', stroke)
692 .attr('transform', 'translate(' + this.rectDim / 2 + ',0)');
693
694 // Draw icon and text
695 this.draw_legend_icon(this.rectDim, leg);
696 this.legendEl
697 .append('text')
698 .attr('class', 'legendtext sticktext')
699 .attr('x', this.rectDim * 1.2)
700 .attr('y', this.rectDim / 2)
701 .attr('dy', '0.35em')
702 .text((d, i) => {
703 return this.model.get('labels')[i];
704 })
705 .style('fill', stroke);
706
707 const max_length = d3.max(this.model.get('labels'), (d: any) => {
708 return Number(d.length);
709 });
710
711 this.legendEl.exit().remove();
712 return [1, max_length];
713 }
714
715 draw_legend_icon(size, selector) {
716 /*
717 * Draw OHLC icon next to legend text
718 * Drawing the icon like this means we can avoid scaling when we
719 * already know what the size of the mark is in pixels
720 */
721 const height = size;
722 const width = size / 2;
723 const bottom_y_offset = (size * 3) / 4;
724 const top_y_offset = size / 4;
725 if (this.model.get('marker') === 'candle') {
726 selector
727 .selectAll('.stick_head')
728 .attr('d', this.headPathCandle(width / 2));
729 selector
730 .selectAll('.stick_tail')
731 .attr('d', this.tailPathCandle(bottom_y_offset, width / 2));
732 selector
733 .selectAll('.stick_body')
734 .attr(
735 'd',
736 this.bodyPathCandle((width * -1) / 2, top_y_offset, width, height / 2)
737 );
738 } else {
739 // bar
740 selector
741 .selectAll('.stick_head')
742 .attr(
743 'd',
744 this.headPathBar((width * -1) / 2, bottom_y_offset, width / 2)
745 );
746 selector
747 .selectAll('.stick_tail')
748 .attr('d', this.tailPathBar(top_y_offset, width / 2));
749 selector.selectAll('.stick_body').attr('d', this.bodyPathBar(height));
750 }
751 }
752
753 clear_style() {}
754 compute_view_padding() {}
755 set_default_style() {}
756 set_style_on_elements() {}
757
758 model: OHLCModel;
759
760 private legendEl: d3.Selection<d3.BaseType, any, any, any>;
761 private rectDim: number;
762 private xPixels: number[];
763 private width: number;
764 private height: number;
765 }