summaryrefslogtreecommitdiffstats
path: root/openbb_platform/providers/polygon/openbb_polygon/models/currency_snapshots.py
blob: 4f024bfc3a80c29f47a76840abc029c8bae32a2c (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
"""Polygon Currency Snapshots."""

# pylint: disable=unused-argument

from datetime import datetime, timezone
from typing import Any, Dict, List, Optional

from openbb_core.app.model.abstract.error import OpenBBError
from openbb_core.provider.abstract.fetcher import Fetcher
from openbb_core.provider.standard_models.currency_snapshots import (
    CurrencySnapshotsData,
    CurrencySnapshotsQueryParams,
)
from openbb_core.provider.utils.errors import EmptyDataError
from openbb_core.provider.utils.helpers import amake_request, safe_fromtimestamp
from pandas import DataFrame, concat
from pydantic import Field


class PolygonCurrencySnapshotsQueryParams(CurrencySnapshotsQueryParams):
    """Polygon Currency Snapshots Query Parameters.

    Source: https://polygon.io/docs/forex/get_v2_snapshot_locale_global_markets_forex_tickers
    """

    __json_schema_extra__ = {"base": {"multiple_items_allowed": True}}


class PolygonCurrencySnapshotsData(CurrencySnapshotsData):
    """Polygon Currency Snapshots Data."""

    vwap: Optional[float] = Field(
        description="The volume-weighted average price.", default=None
    )
    change: Optional[float] = Field(
        description="The change in price from the previous day.",
        default=None,
    )
    change_percent: Optional[float] = Field(
        description="The percentage change in price from the previous day.",
        default=None,
        json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
    )
    prev_open: Optional[float] = Field(
        description="The previous day's opening price.", default=None
    )
    prev_high: Optional[float] = Field(
        description="The previous day's high price.", default=None
    )
    prev_low: Optional[float] = Field(
        description="The previous day's low price.", default=None
    )
    prev_volume: Optional[float] = Field(
        description="The previous day's volume.", default=None
    )
    prev_vwap: Optional[float] = Field(
        description="The previous day's VWAP.", default=None
    )
    bid: Optional[float] = Field(description="The current bid price.", default=None)
    ask: Optional[float] = Field(description="The current ask price.", default=None)
    minute_open: Optional[float] = Field(
        description="The open price from the most recent minute bar.", default=None
    )
    minute_high: Optional[float] = Field(
        description="The high price from the most recent minute bar.", default=None
    )
    minute_low: Optional[float] = Field(
        description="The low price from the most recent minute bar.", default=None
    )
    minute_close: Optional[float] = Field(
        description="The close price from the most recent minute bar.", default=None
    )
    minute_volume: Optional[float] = Field(
        description="The volume from the most recent minute bar.", default=None
    )
    minute_vwap: Optional[float] = Field(
        description="The VWAP from the most recent minute bar.", default=None
    )
    minute_transactions: Optional[float] = Field(
        description="The number of transactions in the most recent minute bar.",
        default=None,
    )
    quote_timestamp: Optional[datetime] = Field(
        description="The timestamp of the last quote.", default=None
    )
    minute_timestamp: Optional[datetime] = Field(
        description="The timestamp for the start of the most recent minute bar.",
        default=None,
    )
    last_updated: Optional[datetime] = Field(
        description="The last time the data was updated."
    )


class PolygonCurrencySnapshotsFetcher(
    Fetcher[
        PolygonCurrencySnapshotsQueryParams,
        List[PolygonCurrencySnapshotsData],
    ]
):
    """Polygon Currency Snapshots Fetcher."""

    @staticmethod
    def transform_query(params: Dict[str, Any]) -> PolygonCurrencySnapshotsQueryParams:
        """Transform the query params."""
        return PolygonCurrencySnapshotsQueryParams(**params)

    @staticmethod
    async def aextract_data(
        query: PolygonCurrencySnapshotsQueryParams,
        credentials: Optional[Dict[str, str]],
        **kwargs: Any,
    ) -> List[Dict]:
        """Extract the raw data."""
        api_key = credentials.get("polygon_api_key") if credentials else ""
        url = f"https://api.polygon.io/v2/snapshot/locale/global/markets/forex/tickers?apiKey={api_key}"
        results = await amake_request(url, **kwargs)
        if results.get("status") != "OK":  # type: ignore[union-attr]
            raise OpenBBError(f"Error: {results.get('status')}")  # type: ignore[union-attr]
        return results.get("tickers", [])  # type: ignore[union-attr]

    @staticmethod
    def transform_data(  # pylint: disable=too-many-locals, too-many-statements
        query: PolygonCurrencySnapshotsQueryParams,
        data: List[Dict],
        **kwargs: Any,
    ) -> List[PolygonCurrencySnapshotsData]:
        """Transform the data."""
        if not data:
            raise EmptyDataError("No data returned.")
        counter_currencies = (
            query.counter_currencies.upper().split(",")  # type: ignore[union-attr]
            if query.counter_currencies
            else []
        )

        # Filter the data only for the symbols requested.
        df = DataFrame(data)
        df.ticker = df.ticker.str.replace("C:", "")
        new_df = DataFrame()
        for symbol in query.base.split(","):
            temp = (
                df.loc[df["ticker"].str.startswith(symbol)].copy()
                if query.quote_type == "indirect"
                else df.loc[df["ticker"].str.endswith(symbol)].copy()
            )
            temp["base_currency"] = symbol
            temp["counter_currency"] = (
                [d[3:] for d in temp["ticker"]]
                if query.quote_type == "indirect"
                else [d[:3] for d in temp["ticker"]]
            )
            # Filter for the counter currencies, if requested.
            if query.counter_currencies is not None:
                counter_currencies = (  # noqa: F841  # pylint: disable=unused-variable
                    query.counter_currencies
                    if isinstance(query.counter_currencies, list)
                    else query.counter_currencies.split(",")
                )
                temp = (
                    temp.query("`counter_currency`.isin(@counter_currencies)")
                    .set_index("counter_currency")
                    # Sets the counter currencies in the order they were requested.
                    .filter(items=counter_currencies, axis=0)
                    .reset_index()
                )
            # If there are no records, don't concatenate.
            if len(temp) > 0:
                new_df = concat([new_df, temp])
        filtered_data = new_df.to_dict(orient="records")

        if len(filtered_data) == 0 or not filtered_data:
            raise EmptyDataError("No results were found with the parameters requested.")

        results: List[PolygonCurrencySnapshotsData] = []
        # Now unpack the nested object for the filtered results only.
        for item in filtered_data:
            new_item = {}
            new_item["base_currency"] = item.get("base_currency")
            new_item["counter_currency"] = item.get("counter_currency")
            new_item["change"] = item.get("todaysChange", None)
            change_percent = item.get("todaysChangePerc", None)
            new_item["change_percent"] = (
                change_percent / 100 if change_percent else None
            )
            updated = item.get("updated")
            new_item["last_updated"] = (
                safe_fromtimestamp(updated / 1e9, tz=timezone.utc) if updated else None
            )
            day = item.get("day", {})
            if day:
                new_item["last_rate"] = day.get("c", None)
                new_item["open"] = day.get("o", None)
                new_item["high"] = day.get("h", None)
                new_item["low"] = day.get("l", None)
                new_item["volume"] = day.get("v", None)
                new_item["vwap"] = day.get("vw", None)
            prev_day = item.get("prevDay", {})
            if prev_day:
                new_item["prev_open"] = prev_day.get("o", None)
                new_item["prev_high"] = prev_day.get("h", None)
                new_item["prev_low"] = prev_day.get("l", None)
                new_item["prev_close"] = prev_day.get("c", None)
                new_item["prev_volume"] = prev_day.get("v", None)
                new_item["prev_vwap"] = prev_day.get("vw", None)
            minute = item.get("min", {})