summaryrefslogtreecommitdiffstats
path: root/openbb_platform/providers/fred/openbb_fred/models/mortgage_indices.py
blob: 68a59dca4fd6f0c7f9a551b623ae6deb95081e56 (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
"""FRED Mortgage Indices Model."""

# pylint: disable=unused-argument

from typing import Any, Dict, List, Literal, Optional, Union
from warnings import warn

from openbb_core.app.model.abstract.error import OpenBBError
from openbb_core.provider.abstract.annotated_result import AnnotatedResult
from openbb_core.provider.abstract.fetcher import Fetcher
from openbb_core.provider.standard_models.mortgage_indices import (
    MortgageIndicesData,
    MortgageIndicesQueryParams,
)
from openbb_core.provider.utils.errors import EmptyDataError
from openbb_fred.models.series import FredSeriesFetcher
from pandas import Categorical, DataFrame
from pydantic import Field, field_validator

MORTGAGE_ID_TO_TITLE = {
    "OBMMIC30YF": "30-Year Fixed Rate Conforming",
    "OBMMIC30YFNA": "30-Year Fixed Rate Conforming Non-Adjusted",
    "OBMMIJUMBO30YF": "30-Year Fixed Rate Jumbo",
    "OBMMIFHA30YF": "30-Year Fixed Rate FHA",
    "OBMMIVA30YF": "30-Year Fixed Rate Veterans Affairs",
    "OBMMIUSDA30YF": "30-Year Fixed Rate USDA",
    "OBMMIC15YF": "15-Year Fixed Rate Conforming",
    "OBMMIC30YFLVLE80FGE740": "30-Year Fixed Rate Conforming LTV <= 80 FICO >= 740",
    "OBMMIC30YFLVLE80FB720A739": "30-Year Fixed Rate Conforming LTV <= 80 FICO 720-739",
    "OBMMIC30YFLVLE80FB700A719": "30-Year Fixed Rate Conforming LTV <= 80 FICO 700-719",
    "OBMMIC30YFLVLE80FB680A699": "30-Year Fixed Rate Conforming LTV <= 80 FICO 680-699",
    "OBMMIC30YFLVLE80FLT680": "30-Year Fixed Rate Conforming LTV <= 80 FICO < 680",
    "OBMMIC30YFLVGT80FGE740": "30-Year Fixed Rate Conforming LTV > 80 FICO >= 740",
    "OBMMIC30YFLVGT80FB720A739": "30-Year Fixed Rate Conforming LTV > 80 FICO 720-739",
    "OBMMIC30YFLVGT80FB700A719": "30-Year Fixed Rate Conforming LTV > 80 FICO 700-719",
    "OBMMIC30YFLVGT80FB680A699": "30-Year Fixed Rate Conforming LTV > 80 FICO 680-699",
    "OBMMIC30YFLVGT80FLT680": "30-Year Fixed Rate Conforming LTV > 80 FICO < 680",
}

MORTGAGE_GROUPS = {
    "primary": [
        "OBMMIC30YF",
        "OBMMIC30YFNA",
        "OBMMIJUMBO30YF",
        "OBMMIFHA30YF",
        "OBMMIVA30YF",
        "OBMMIUSDA30YF",
        "OBMMIC15YF",
    ],
    "ltv_lte_80": [
        "OBMMIC30YFLVLE80FGE740",
        "OBMMIC30YFLVLE80FB720A739",
        "OBMMIC30YFLVLE80FB700A719",
        "OBMMIC30YFLVLE80FB680A699",
        "OBMMIC30YFLVLE80FLT680",
    ],
    "ltv_gt_80": [
        "OBMMIC30YFLVGT80FGE740",
        "OBMMIC30YFLVGT80FB720A739",
        "OBMMIC30YFLVGT80FB700A719",
        "OBMMIC30YFLVGT80FB680A699",
        "OBMMIC30YFLVGT80FLT680",
    ],
}

MORTGAGE_CHOICES_TO_ID = {
    "primary": ",".join(MORTGAGE_GROUPS["primary"]),
    "ltv_lte_80": ",".join(MORTGAGE_GROUPS["ltv_lte_80"]),
    "ltv_gt_80": ",".join(MORTGAGE_GROUPS["ltv_gt_80"]),
    "conforming_30y": "OBMMIC30YF",
    "conforming_30y_na": "OBMMIC30YFNA",
    "jumbo_30y": "OBMMIJUMBO30YF",
    "fha_30y": "OBMMIFHA30YF",
    "va_30y": "OBMMIVA30YF",
    "usda_30y": "OBMMIUSDA30YF",
    "conforming_15y": "OBMMIC15YF",
    "ltv_lte80_fico_ge740": "OBMMIC30YFLVLE80FGE740",
    "ltv_lte80_fico_a720b739": "OBMMIC30YFLVLE80FB720A739",
    "ltv_lte80_fico_a700b719": "OBMMIC30YFLVLE80FB700A719",
    "ltv_lte80_fico_a680b699": "OBMMIC30YFLVLE80FB680A699",
    "ltv_lte80_fico_lt680": "OBMMIC30YFLVLE80FLT680",
    "ltv_gt80_fico_ge740": "OBMMIC30YFLVGT80FGE740",
    "ltv_gt80_fico_a720b739": "OBMMIC30YFLVGT80FB720A739",
    "ltv_gt80_fico_a700b719": "OBMMIC30YFLVGT80FB700A719",
    "ltv_gt80_fico_a680b699": "OBMMIC30YFLVGT80FB680A699",
    "ltv_gt80_fico_lt680": "OBMMIC30YFLVGT80FLT680",
}

MortgageChoices = Literal[
    "primary",
    "ltv_lte_80",
    "ltv_gt_80",
    "conforming_30y",
    "conforming_30y_na",
    "jumbo_30y",
    "fha_30y",
    "va_30y",
    "usda_30y",
    "conforming_15y",
    "ltv_lte80_fico_ge740",
    "ltv_lte80_fico_a720b739",
    "ltv_lte80_fico_a700b719",
    "ltv_lte80_fico_a680b699",
    "ltv_lte80_fico_lt680",
    "ltv_gt80_fico_ge740",
    "ltv_gt80_fico_a720b739",
    "ltv_gt80_fico_a700b719",
    "ltv_gt80_fico_a680b699",
    "ltv_gt80_fico_lt680",
]


class FredMortgageIndicesQueryParams(MortgageIndicesQueryParams):
    """FRED Mortgage Indices Query."""

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

    index: Union[MortgageChoices, str] = Field(
        default="primary",
        description="The specific index, or index group, to query. Default is the 'primary' group.",
        choices=list(MORTGAGE_CHOICES_TO_ID.keys()),
    )
    frequency: Union[
        None,
        Literal[
            "a",
            "q",
            "m",
            "w",
            "d",
            "wef",
            "weth",
            "wew",
            "wetu",
            "wem",
            "wesu",
            "wesa",
            "bwew",
            "bwem",
        ],
    ] = Field(
        default=None,
        description="""
        Frequency aggregation to convert daily data to lower frequency.
            None = No change
            a = Annual
            q = Quarterly
            m = Monthly
            w = Weekly
            d = Daily
            wef = Weekly, Ending Friday
            weth = Weekly, Ending Thursday
            wew = Weekly, Ending Wednesday
            wetu = Weekly, Ending Tuesday
            wem = Weekly, Ending Monday
            wesu = Weekly, Ending Sunday
            wesa = Weekly, Ending Saturday
            bwew = Biweekly, Ending Wednesday
            bwem = Biweekly, Ending Monday
        """,
        json_schema_extra={
            "choices": [
                "a",
                "q",
                "m",
                "w",
                "d",
                "wef",
                "weth",
                "wew",
                "wetu",
                "wem",
                "wesu",
                "wesa",
                "bwew",
                "bwem",
            ]
        },
    )
    aggregation_method: Literal["avg", "sum", "eop"] = Field(
        default="avg",
        description="""
        A key that indicates the aggregation method used for frequency aggregation.
        This parameter has no affect if the frequency parameter is not set, default is 'avg'.
            avg = Average
            sum = Sum
            eop = End of Period
        """,
        json_schema_extra={"choices": ["avg", "sum", "eop"]},
    )
    transform: Union[
        None, Literal["chg", "ch1", "pch", "pc1", "pca", "cch", "cca", "log"]
    ] = Field(
        default=None,
        description="""
        Transformation type
            None = No transformation
            chg = Change
            ch1 = Change from Year Ago
            pch = Percent Change
            pc1 = Percent Change from Year Ago
            pca = Compounded Annual Rate of Change
            cch = Continuously Compounded Rate of Change
            cca = Continuously Compounded Annual Rate of Change
            log = Natural Log
        """,
        json_schema_extra={
            "choices": ["chg", "ch1", "pch", "pc1", "pca", "cch", "cca", "log"]
        },
    )

    @field_validator("index", mode="before", check_fields=False)
    @classmethod
    def validate_index(cls, v):
        """Validate index."""
        indices = v.split(",")
        new_indices: List = []
        for index in indices:
            if index in MORTGAGE_CHOICES_TO_ID:
                new_indices.append(index)
            else:
                warn(f"Invalid index '{index}' will be ignored.")
        if not new_indices:
            raise OpenBBError(
                f"No valid indices found. Must be any of: {list(MORTGAGE_CHOICES_TO_ID.keys())}"
            )
        return ",".join(new_indices)


class FredMortgageIndicesData(MortgageIndicesData):
    """FRED Mortgage Indices Data."""


class FredMortgageIndicesFetcher(
    Fetcher[
        FredMortgageIndicesQueryParams,
        List[FredMortgageIndicesData],
    ]
):
    """FRED Mortgage Indices Fetcher."""

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

    @staticmethod
    async def aextract_data(
        query: FredMortgageIndicesQueryParams,
        credentials: Optional[Dict[str, str]],
        **kwargs: Any,
    ) -> Dict:
        """Extract data."""
        indices = query.index.split(",")
        ids = [MORTGAGE_CHOICES_TO_ID[index] for index in indices]
        try:
            response = await FredSeriesFetcher.fetch_data(
                dict(
                    symbol=",".join(ids),
                    start_date=query.start_date,
                    end_date=query.end_date,
                    transform=query.transform,
                    frequency=query.frequency,
                    aggregation_method=query.aggregation_method,
                ),
                credentials,
            )
        except Exception as e:
            raise e from e

        return {
            "metadata": response.metadata,
            "data": [d.model_dump() for d in response.result],
        }

    @staticmethod
    def transform_data(
        query: FredMortgageIndicesQueryParams,
        data: Dict,
        **kwargs: Any,
    ) -> AnnotatedResult[List[FredMortgageIndicesData]]:
        """Transform data."""
        if not data.get("data"):
            raise EmptyDataError("The request was returned empty.")
        df = DataFrame.from_records(data["data"])
        metadata = data.get("metadata", {})
        # Flatten the data.
        df = (
            df.melt(id_vars="date", var_name="symbol", value_name="value")
            .query("value.notnull()")
            .