summaryrefslogtreecommitdiffstats
path: root/openbb_platform/obbject_extensions/charting/openbb_charting/__init__.py
blob: b2e5efcfd4a5a079ef4c3d79909294efceecbaec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
"""OpenBB OBBject extension for charting."""

# pylint: disable=too-many-arguments,unused-argument

import warnings
from typing import (
    Any,
    Callable,
    Dict,
    List,
    Literal,
    Optional,
    Tuple,
    Union,
)
from warnings import warn

import numpy as np
import pandas as pd
from openbb_core.app.model.charts.chart import Chart
from openbb_core.app.model.extension import Extension
from openbb_core.app.model.obbject import OBBject
from openbb_core.app.utils import basemodel_to_df, convert_to_basemodel
from openbb_core.provider.abstract.data import Data
from plotly.graph_objs import Figure

from openbb_charting import charting_router
from openbb_charting.core.backend import Backend, create_backend, get_backend
from openbb_charting.core.openbb_figure import OpenBBFigure
from openbb_charting.query_params import ChartParams, IndicatorsParams
from openbb_charting.utils.generic_charts import bar_chart, line_chart
from openbb_charting.utils.helpers import get_charting_functions

warnings.filterwarnings(
    "ignore", category=UserWarning, module="openbb_core.app.model.extension", lineno=47
)

ext = Extension(name="charting", description="Create custom charts from OBBject data.")


@ext.obbject_accessor
class Charting:
    """Charting extension.

    Methods
    -------
    show
        Display chart and save it to the OBBject.
    to_chart
        Redraw the chart and save it to the OBBject, with an optional entry point for Data.
    functions
        Return a list of Platform commands with charting functions.
    get_params
        Return the charting parameters for the function the OBBject was created from.
    indicators
        Return the list of the available technical indicators to use with the `to_chart` method and OHLC+V data.
    table
        Display an interactive table.
    create_line_chart
        Create a line chart from external data.
    create_bar_chart
        Create a bar chart, on a single x-axis with one or more values for the y-axis, from external data.
    toggle_chart_style
        Toggle the chart style, of an existing chart, between light and dark mode.
    """

    def __init__(self, obbject):
        """Initialize Charting extension."""
        # pylint: disable=import-outside-toplevel
        from openbb_core.app.model.charts.charting_settings import ChartingSettings

        self._obbject: OBBject = obbject
        self._charting_settings = ChartingSettings(
            user_settings=self._obbject._user_settings,  # type: ignore
            system_settings=self._obbject._system_settings,  # type: ignore
        )
        self._backend: Backend = self._handle_backend()

    @classmethod
    def indicators(cls):
        """Return an instance of the IndicatorsParams class, containing all available indicators and their parameters.

        Without assigning to a variable, it will print the the information to the console.
        """
        return IndicatorsParams()

    @classmethod
    def functions(cls):
        """Return a list of the available functions."""
        return get_charting_functions()

    def _handle_backend(self) -> Backend:
        """Create and start the backend."""
        create_backend(self._charting_settings)
        backend = get_backend()
        backend.start(debug=self._charting_settings.debug_mode)
        return backend

    @staticmethod
    def _get_chart_function(route: str) -> Callable:
        """Given a route, it returns the chart function. The module must contain the given route."""
        if route is None:
            raise ValueError("OBBject was initialized with no function route.")
        adjusted_route = route.replace("/", "_")[1:]
        return getattr(charting_router, adjusted_route)

    def get_params(self) -> ChartParams:
        """Return the ChartQueryParams class for the function the OBBject was created from.

        Without assigning to a variable, it will print the docstring to the console.
        """
        if self._obbject._route is None:  # pylint: disable=protected-access
            raise ValueError("OBBject was initialized with no function route.")
        charting_function = (
            self._obbject._route  # pylint: disable=protected-access
        ).replace("/", "_")[1:]
        if hasattr(ChartParams, charting_function):
            return getattr(ChartParams, charting_function)()
        raise ValueError(
            f"Error: No chart parameters are defined for the route: {charting_function}"
        )

    def _prepare_data_as_df(
        self, data: Optional[Union[pd.DataFrame, pd.Series]]
    ) -> Tuple[pd.DataFrame, bool]:
        """Convert supplied data to a DataFrame."""
        has_data = (
            isinstance(data, (Data, pd.DataFrame, pd.Series)) and not data.empty  # type: ignore
        ) or (bool(data))
        index = (
            data.index.name
            if has_data and isinstance(data, (pd.DataFrame, pd.Series))
            else None
        )
        data_as_df: pd.DataFrame = (
            basemodel_to_df(convert_to_basemodel(data), index=index)
            if has_data
            else self._obbject.to_dataframe(index=index)
        )
        if "date" in data_as_df.columns:
            data_as_df = data_as_df.set_index("date")
        if "provider" in data_as_df.columns:
            data_as_df.drop(columns="provider", inplace=True)
        return data_as_df, has_data

    # pylint: disable=too-many-locals
    def create_line_chart(
        self,
        data: Union[
            list,
            dict,
            pd.DataFrame,
            List[pd.DataFrame],
            pd.Series,
            List[pd.Series],
            np.ndarray,
            Data,
        ],
        index: Optional[str] = None,
        target: Optional[str] = None,
        title: Optional[str] = None,
        x: Optional[str] = None,
        xtitle: Optional[str] = None,
        y: Optional[Union[str, List[str]]] = None,
        ytitle: Optional[str] = None,
        y2: Optional[Union[str, List[str]]] = None,
        y2title: Optional[str] = None,
        layout_kwargs: Optional[dict] = None,
        scatter_kwargs: Optional[dict] = None,
        normalize: bool = False,
        returns: bool = False,
        same_axis: bool = False,
        render: bool = True,
        **kwargs,
    ) -> Union[OpenBBFigure, Figure, None]:
        """Create a line chart from external data and render a chart or return the OpenBBFigure.

        Parameters
        ----------
        data : Union[Data, pd.DataFrame, pd.Series]
            Data to be plotted (OHLCV data).
        index : Optional[str], optional
            Index column, by default None
        target : Optional[str], optional
            Target column to be plotted, by default None
        title : Optional[str], optional