# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

# +
import os
import sys
import time
from datetime import datetime, timedelta
from typing import Optional

import ipywidgets as ipw
import matplotlib.pyplot as plt
import matplotlib_inline.backend_inline
from ipyflex import FlexLayout
from widget_helpers import price_card, stylesheet

from openbb_terminal import api as openbb

# %matplotlib widget
openbb.theme.applyMPLstyle()
ipw.HTML(f"<style>{stylesheet()}</style>")


# +
def get_exchange_rate(currency_pair: str) -> str:
    """Get exchange rate for a currency pair."""
    from_symbol, to_symbol = currency_pair.split("/")
    exchange_data = openbb.forex.models.av.get_quote(
        to_symbol=to_symbol, from_symbol=from_symbol
    )
    return exchange_data["Realtime Currency Exchange Rate"]["5. Exchange Rate"][:6]


def get_candle_widget(
    output: Optional[ipw.Output],
    to_symbol: str,
    from_symbol: str,
) -> ipw.Output:
    """Plot a candle chart for a currency pair."""
    start_date = datetime.now() - timedelta(days=1)
    start_date = start_date.strftime("%Y-%m-%d")

    exchange_rate_data = openbb.forex.models.av.get_historical(
        to_symbol=to_symbol,
        from_symbol=from_symbol,
        start_date=start_date,
        resolution="i",
        interval="15",
    )
    fig, ax = plt.subplots(1, 1, figsize=(11, 4))
    openbb.forex.candle(
        data=exchange_rate_data,
        to_symbol=to_symbol,
        from_symbol=from_symbol,
        external_axes=[ax],
    )

    ax.set_xlim(0, len(exchange_rate_data.index))
    fig.canvas.header_visible = False
    fig.canvas.footer_visible = False
    with output:
        output.clear_output(True)
        fig.canvas.show()
    return output


def on_dropdown_change(change):
    """Update charts on change of dropdown selection."""
    if change["type"] == "change" and change["name"] == "value":
        output = ipw.Output()
        get_candle_widget(
            to_symbol=to_widget.value,
            from_symbol=from_widget.value,
        )
        dashboard.children["Candle"] = output


# -

exchange_rates = {
    "EUR/USD": {"latest": None, "previous": None},
    "USD/JPY": {"latest": None, "previous": None},
    "GBP/USD": {"latest": None, "previous": None},
    "AUD/USD": {"latest": None, "previous": None},
    "USD/CAD": {"latest": None, "previous": None},
    # "USD/CNY": {"latest": None, "previous": None},
    # "USD/CHF": {"latest": None, "previous": None},
    # "USD/HKD": {"latest": None, "previous": None},
}


def compose_widgets():
    widgets = {}
    for currency_pair in exchange_rates:
        price = exchange_rates[currency_pair]["latest"]
        price_color = "neutral_color"
        if exchange_rates[currency_pair]["previous"] is not None:
            if (
                exchange_rates[currency_pair]["latest"]
                > exchange_rates[currency_pair]["previous"]
            ):
                price_color = "up_color"
            elif (
                exchange_rates[currency_pair]["latest"]
                < exchange_rates[currency_pair]["previous"]
            ):
                price_color = "down_color"
        widgets[currency_pair] = ipw.HTML(
            price_card(ticker=currency_pair, price=price, price_color=price_color)
        )
    return widgets


# +
# for currency_code in rates_to_usd:
#     rates_to_usd[currency_code]["previous"] = rates_to_usd[currency_code]["latest"]
#     rates_to_usd[currency_code]["latest"] = get_rate_against_usd(currency_code)
# -

widgets = compose_widgets()

# +
currency_list = openbb.forex.models.av.get_currency_list()
from_widget = ipw.Dropdown(
    options=currency_list,
    value="EUR",
    description="From:",
    disabled=False,
    layout=ipw.Layout(margin="130"),
)
to_widget = ipw.Dropdown(
    options=currency_list,
    value="USD",
    description="To:",
    disabled=False,
)
exchange_selection = ipw.VBox([from_widget, to_widget])

widgets["Select"] = exchange_selection
# -

output = ipw.Output()
output = get_candle_widget(
    output=output,
    to_symbol=to_widget.value,
    from_symbol=from_widget.value,
)
widgets["Candle"] = output

from_widget.observe(on_dropdown_change)
to_widget.observe(on_dropdown_change)

dashboard = FlexLayout(
    layout_config={"borderLeft": False, "borderRight": False, "enableSection": False},
    style={
        "height": "calc(100vh - 80px)",
        "backgroundColor": "rgb(0 0 0)",
        "fontFamily": "Consolas",
        "fontWeight": 800,
    },
    header={
        "title": "Currencies",
        "style": {
            "backgroundColor": "rgb(0 0 0)",
            "fontWeight": 400,
            "fontSize": "28px",
        },
        "buttons": [],
    },
    widgets=widgets,
    template=os.path.join("widgets", "currencies.json"),
    editable=False,
)
dashboard





StarcoderdataJupyterScriptsDedupFiltered