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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
557
"""Views for the technical Extension."""

# pylint: disable=too-many-locals,use-dict-literal

from typing import TYPE_CHECKING, Any

from openbb_charting.core.to_chart import to_chart
from openbb_charting.styles.colors import LARGE_CYCLER

if TYPE_CHECKING:
    from openbb_charting.core.openbb_figure import OpenBBFigure


class TechnicalViews:
    """Technical Views."""

    @staticmethod
    def technical_sma(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Plot simple moving average chart."""
        if "ma_type" not in kwargs:
            kwargs["ma_type"] = "sma"
        return _ta_ma(**kwargs)

    @staticmethod
    def technical_ema(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Exponential moving average chart."""
        if "ma_type" not in kwargs:
            kwargs["ma_type"] = "ema"
        return _ta_ma(**kwargs)

    @staticmethod
    def technical_hma(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Hull moving average chart."""
        if "ma_type" not in kwargs:
            kwargs["ma_type"] = "hma"
        return _ta_ma(**kwargs)

    @staticmethod
    def technical_wma(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Weighted moving average chart."""
        if "ma_type" not in kwargs:
            kwargs["ma_type"] = "wma"
        return _ta_ma(**kwargs)

    @staticmethod
    def technical_zlma(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Zero lag moving average chart."""
        if "ma_type" not in kwargs:
            kwargs["ma_type"] = "zlma"
        return _ta_ma(**kwargs)

    @staticmethod
    def technical_aroon(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Technical Aroon Chart."""
        # pylint: disable=import-outside-toplevel
        from openbb_charting.core.plotly_ta.ta_class import PlotlyTA
        from openbb_core.app.utils import basemodel_to_df
        from pandas import DataFrame

        if "data" in kwargs and isinstance(kwargs["data"], DataFrame):
            data = kwargs["data"]
        else:
            data = basemodel_to_df(
                kwargs["obbject_item"], index=kwargs.get("index", "date")
            )

        if "date" in data.columns:
            data = data.set_index("date")

        if "symbol" in data.columns and len(data.symbol.unique()) > 1:
            raise ValueError(
                "Please provide data with only one symbol and columns for OHLC."
            )

        symbol = kwargs.get("symbol", "")

        volume = kwargs.get("volume") is True
        title = f"Aroon Indicator & Oscillator {symbol}"

        length = kwargs.get("length", 25)
        scalar = kwargs.get("scalar", 100)
        symbol = kwargs.get("symbol", "")

        ta = PlotlyTA()
        fig = ta.plot(  # type: ignore
            data,
            dict(aroon=dict(length=length, scalar=scalar)),
            title,
            False,
            volume=volume,
        )

        content = fig.show(external=True).to_plotly_json()

        return fig, content

    @staticmethod
    def technical_macd(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Plot moving average convergence divergence chart."""
        # pylint: disable=import-outside-toplevel
        from openbb_charting.core.plotly_ta.ta_class import PlotlyTA
        from openbb_core.app.utils import basemodel_to_df
        from pandas import DataFrame

        if "data" in kwargs and isinstance(kwargs["data"], DataFrame):
            data = kwargs["data"]
        else:
            data = basemodel_to_df(
                kwargs["obbject_item"], index=kwargs.get("index", "date")
            )

        if "date" in data.columns:
            data = data.set_index("date")

        if "symbol" in data.columns and len(data.symbol.unique()) > 1:
            raise ValueError(
                "Please provide data with only one symbol and columns for OHLC."
            )

        fast = kwargs.get("fast", 12)
        slow = kwargs.get("slow", 26)
        signal = kwargs.get("signal", 9)
        symbol = kwargs.get("symbol", "")

        title = f"{symbol.upper()} MACD"
        volume = kwargs.get("volume") is True

        ta = PlotlyTA()
        fig = ta.plot(  # type: ignore
            data,
            dict(macd=dict(fast=fast, slow=slow, signal=signal)),
            title,
            False,
            volume=volume,
        )
        content = fig.show(external=True).to_plotly_json()

        return fig, content

    @staticmethod
    def technical_adx(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Average directional movement index chart."""
        # pylint: disable=import-outside-toplevel
        from openbb_charting.core.plotly_ta.ta_class import PlotlyTA
        from openbb_core.app.utils import basemodel_to_df
        from pandas import DataFrame

        if "data" in kwargs and isinstance(kwargs["data"], DataFrame):
            data = kwargs["data"]
        else:
            data = basemodel_to_df(
                kwargs["obbject_item"], index=kwargs.get("index", "date")
            )

        if "date" in data.columns:
            data = data.set_index("date")

        if "symbol" in data.columns and len(data.symbol.unique()) > 1:
            raise ValueError(
                "Please provide data with only one symbol and columns for OHLC."
            )

        length = kwargs.get("length", 14)
        scalar = kwargs.get("scalar", 100.0)
        drift = kwargs.get("drift", 1)
        symbol = kwargs.get("symbol", "")

        ta = PlotlyTA()
        fig = ta.plot(  # type: ignore
            data,
            dict(adx=dict(length=length, scalar=scalar, drift=drift)),
            f"Average Directional Movement Index (ADX) {symbol}",
            False,
            volume=False,
        )
        content = fig.show(external=True).to_plotly_json()

        return fig, content

    @staticmethod
    def technical_rsi(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Relative strength index chart."""
        # pylint: disable=import-outside-toplevel
        from openbb_charting.core.plotly_ta.ta_class import PlotlyTA
        from openbb_core.app.utils import basemodel_to_df
        from pandas import DataFrame

        if "data" in kwargs and isinstance(kwargs["data"], DataFrame):
            data = kwargs["data"]
        else:
            data = basemodel_to_df(
                kwargs["obbject_item"], index=kwargs.get("index", "date")
            )

        if "date" in data.columns:
            data = data.set_index("date")

        if "symbol" in data.columns and len(data.symbol.unique()) > 1:
            raise ValueError(
                "Please provide data with only one symbol and columns for OHLC."
            )

        window = kwargs.get("window", 14)
        scalar = kwargs.get("scalar", 100.0)
        drift = kwargs.get("drift", 1)
        symbol = kwargs.get("symbol", "")

        ta = PlotlyTA()
        fig = ta.plot(  # type: ignore
            data,
            dict(rsi=dict(length=window, scalar=scalar, drift=drift)),
            f"{symbol.upper()} RSI {window}",
            False,
            volume=False,
        )
        content = fig.show(external=True).to_plotly_json()

        return fig, content

    @staticmethod
    def technical_cones(**kwargs) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Volatility Cones Chart."""
        # pylint: disable=import-outside-toplevel
        from openbb_charting.core.chart_style import ChartStyle
        from openbb_charting.core.openbb_figure import OpenBBFigure
        from openbb_core.app.utils import basemodel_to_df
        from pandas import DataFrame

        data = kwargs.get("data")

        if isinstance(data, DataFrame) and not data.empty and "window" in data.columns:
            df_ta = data.set_index("window")
        else:
            df_ta = basemodel_to_df(kwargs["obbject_item"], index="window")  # type: ignore

        df_ta.columns = [col.title().replace("_", " ") for col in df_ta.columns]

        # Check if the data is formatted as expected.
        if not all(
            col in df_ta.columns for col in ["Realized", "Min", "Median", "Max"]
        ):
            raise ValueError("Data supplied does not match the expected format.")

        model = (
            str(kwargs.get("model"))
            .replace("std", "Standard Deviation")
            .replace("_", "-")
            .title()
            if kwargs.get("model")
            else "Standard Deviation"
        )

        symbol = str(kwargs.get("symbol")) + " - " if kwargs.get("symbol") else ""

        title = (
            str(kwargs.get("title"))
            if kwargs.get("title")
            else f"{symbol}Realized Volatility Cones - {model} Model"
        )

        colors = [
            "green",
            "red",
            "burlywood",
            "grey",
            "orange",
            "blue",
        ]

        fig = OpenBBFigure()

        fig.update_layout(ChartStyle().plotly_template.get("layout", {}))

        text_color = "black" if ChartStyle().plt_style == "light" else "white"

        for i, col in enumerate(df_ta.columns):
            fig.add_scatter(
                x=df_ta.index,
                y=df_ta[col],
                name=col,
                mode="lines+markers",
                hovertemplate=f"{col}: %{{y}}<extra></extra>",
                marker=dict(
                    color=colors[i],
                    size=11,
                ),
            )

        fig.set_title(title)

        fig.update_layout(
            paper_bgcolor=(
                "rgba(0,0,0,0)" if text_color == "white" else "rgba(255,255,255,0)"
            ),
            plot_bgcolor=(
                "rgba(0,0,0,0)" if text_color == "white" else "rgba(255,255,255,0)"
            ),
            font=dict(color=text_color),
            legend=dict(
                orientation="h",
                yanchor="bottom",
                xanchor="right",
                y=1.02,
                x=1,
                bgcolor=(
                    "rgba(0,0,0,0)" if text_color == "white" else "rgba(255,255,255,0)"
                ),
            ),
            yaxis=dict(
                ticklen=0,
                showgrid=True,
                showline=True,
                mirror=True,
                zeroline=False,
                gridcolor="rgba(128,128,128,0.3)",
            ),
            xaxis=dict(
                type="category",
                tickmode="array",
                ticklen=0,
                tickvals=df_ta.index,
                ticktext=df_ta.index,
                title_text="Period",
                showgrid=False,
                showline=True,
                mirror=True,
                zeroline=False,
            ),
            margin=dict(l=20, r=20, b=20),
            dragmode="pan",
        )

        content = fig.to_plotly_json()

        return fig, content

    @staticmethod
    def technical_relative_rotation(
        **kwargs: Any,
    ) -> tuple["OpenBBFigure", dict[str, Any]]:
        """Relative Rotation Chart."""
        # pylint: disable=import-outside-toplevel
        from openbb_charting.charts import relative_rotation  # noqa
        from openbb_charting.core.chart_style import ChartStyle  # noqa
        from openbb_charting.core.openbb_figure import OpenBBFigure  # noqa
        from openbb_core.app.utils import basemodel_to_df  # noqa

        ratios_df = basemodel_to_df(kwargs["obbject_item"].rs_ratios, index="date")  # type: ignore
        momentum_df = basemodel_to_df(kwargs["obbject_item"].rs_momentum, index="date")  # type: ignore
        benchmark_symbol = kwargs["obbject_item"].benchmark  # type: ignore
        study = kwargs.get("study")
        study = str(kwargs["obbject_item"].study) if study is None else str(study)
        show_tails = kwargs.get("show_tails")
        show_tails = True if show_tails is None else show_tails
        tail_periods = int(kwargs.get("tail_periods")) if "tail_periods" in kwargs else 16  # type: ignore
        tail_interval = str(kwargs.get("tail_interval")) if "tail_interval" in kwargs else "week"  # type: ignore
        date = kwargs.get("date") if "date" in kwargs else None  # type: ignore
        show_tails = False if date is not None else show_tails
        if ratios_df.empty or momentum_df.empty:
            raise RuntimeError("Error: No data to plot.")

        if show_tails is True:
            fig = relative_rotation.create_rrg_with_tails(
                ratios_df, momentum_df, study, benchmark_symbol, tail_periods, tail_interval  # type: ignore
            )

        if show_tails is False:
            fig = relative_rotation.create_rrg_without_tails(
                ratios_df, momentum_df, benchmark_symbol, study, date  # type: ignore
            )

        figure = OpenBBFigure(fig)  # pylint: disable=E0606
        font_color = "black" if ChartStyle().plt_style == "light" else "white"
        figure.update_layout(
            paper_bgcolor=(
                "rgba(0,0,0,0)" if font_color == "white" else "rgba(255,255,255,255)"
            ),
            plot_bgcolor="rgba(255,255,255,1)",
            font=dict(color=font_color),
            yaxis=dict(
                showgrid=True,
                gridcolor="rgba(128,128,128,0.3)",
                side="left",
                showline=True,
                zeroline=True,
                mirror=True,
                ticklen=0,
                tickfont=dict(size=14),
                title=dict(font=dict(size=16)),
            ),
            xaxis=dict(
                showgrid=True,
                gridcolor="rgba(128,128,128,0.3)",
                showline=True,
                zeroline=True,
                mirror=True,
                ticklen=0,
                tickfont=dict(size=14),
                title=dict(font=dict(size=16)),
                hoverformat="",
            ),
            hoverlabel=dict(
                font_size=12,
            ),
        )

        if kwargs.get("title") is not None:
            figure.set_title(str(kwargs.get("title")))
        content = figure.to_plotly_json()

        return figure, content


def _ta_ma(**kwargs):
    """Plot moving average helper."""
    # pylint: disable=import-outside-toplevel
    from openbb_charting.core.chart_style import ChartStyle
    from openbb_charting.core.openbb_figure import OpenBBFigure
    from openbb_core.app.utils import basemodel_to_df
    from pandas import DataFrame

    index = (
        kwargs.get("index")
        if "index" in kwargs and kwargs.get("index") is not None
        else "date"
    )
    data = kwargs.get("data")
    ma_type = (
        kwargs["ma_type"]
        if "ma_type" in kwargs and kwargs.get("ma_type") is not None
        else "sma"
    )
    ma_types = ma_type.split(",") if isinstance(ma_type, str) else ma_type

    if isinstance(data, DataFrame) and not data.empty:
        data = data.set_index(index) if index in data.columns else data

    if data is None:
        data = basemodel_to_df(kwargs["obbject_item"], index=index)

    if isinstance(data, list):
        data = basemodel_to_df(data, index=index)

    window = (
        kwargs.get("length", [])
        if "length" in kwargs and kwargs.get("length") is not None
        else [50]
    )
    offset = kwargs.get("offset", 0)
    target = (
        kwargs.get("target")
        if "target" in kwargs and kwargs.get("target") is not None
        else "close"
    )

    if target not in data.columns and "close" in data.columns:
        target = "close"

    if target not in data.columns and "close" not in data.columns:
        raise ValueError(f"Column '{target}', or 'close', not found in the data.")

    df = data.copy()
    if target in data.columns:
        df = df[[target]]
        df.columns = ["close"]
    title = (
        kwargs.get("title")
        if "title" in kwargs and kwargs.get("title") is not None
        else f"{ma_type.upper()}"
    )

    fig = OpenBBFigure()
    fig = fig.create_subplots(
        1,
        1,
        shared_xaxes=True,
        vertical_spacing=0.06,
        horizontal_spacing=0.01,
        row_width=[1],
        specs=[[{"secondary_y": True}]],
    )
    fig.update_layout(ChartStyle().plotly_template.get("layout", {}))
    font_color = "black" if ChartStyle().plt_style == "light" else "white"
    ma_df = DataFrame()
    window = [window] if isinstance(window, int) else window
    for w in window:
        for ma_type in ma_types:
            ma_df[f"{ma_type.upper()} {w}"] = getattr(df.ta, ma_type)(
                length=w, offset=offset
            )

    if kwargs.get("dropnan") is True:
        ma_df = ma_df.dropna()
        data = data.iloc[-len(ma_df) :]

    if (
        "candles" in kwargs
        and kwargs.get("candles") is True
        and kwargs.get("target") is None
    ):
        volume = kwargs.get("volume") is True
        fig, _ = to_chart(data, candles=True, volume=volume)

    else:
        ma_df[f"{target}".title()] = data[target]

    for i, col in enumerate(ma_df.columns):
        name = col.replace("_", " ")
        fig.add_scatter(
            x=ma_df.index,
            y=ma_df[col],
            name=name,
            mode="lines",
            hovertemplate=f"{name}: %{{y}}<extra></extra>",
            line=dict(width=1, color=LARGE_CYCLER[i]),
            showlegend=True,
        )

    fig.update_layout(
        title=dict(text=title, x=0.5, font=dict(size=16)),
        paper_bgcolor=(
            "rgba(0,0,0,0)" if font_color == "white" else "rgba(255,255,255,255)"
        ),
        plot_bgcolor=(
            "rgba(0,0,0,0)" if font_color == "white" else "rgba(255,255,255,0)"
        ),
        showlegend=True,
        legend=dict(
            orientation="h",
            yanchor="bottom",
            xanchor="right",
            y=1.02,
            x=0.95,
            bgcolor="rgba(0,0,0,0)" if font_color == "white" else "rgba(255,255,255,0)",
        ),
        xaxis=dict(
            ticklen=0,
            showgrid=True,
            gridcolor="rgba(128,128,128,0.3)",
            zeroline=True,
            mirror=True,
        ),
        yaxis=dict(
            ticklen=0,
            showgrid=True,
            gridcolor="rgba(128,128,128,0.3)",
            zeroline=True,
            mirror=True,
            autorange=True,
        ),
        font=dict(color=font_color),
    )

    content = fig.show(external=True).to_plotly_json()

    return fig, content