summaryrefslogtreecommitdiffstats
path: root/openbb_platform/providers/intrinio/openbb_intrinio/models/company_news.py
blob: 7577e4225e9bfe5e13d01e7312553f9770eaf8ee (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
"""Intrinio Company News Model."""

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

from openbb_core.provider.abstract.fetcher import Fetcher
from openbb_core.provider.standard_models.company_news import (
    CompanyNewsData,
    CompanyNewsQueryParams,
)
from openbb_core.provider.utils.errors import EmptyDataError
from openbb_core.provider.utils.helpers import (
    amake_request,
    get_querystring,
)
from openbb_intrinio.utils.helpers import get_data
from openbb_intrinio.utils.references import IntrinioSecurity
from pydantic import Field, field_validator


class IntrinioCompanyNewsQueryParams(CompanyNewsQueryParams):
    """Intrinio Company News Query.

    Source: https://docs.intrinio.com/documentation/web_api/get_company_news_v2
    """

    __alias_dict__ = {
        "limit": "page_size",
        "source": "specific_source",
    }
    __json_schema_extra__ = {"symbol": {"multiple_items_allowed": True}}

    source: Optional[
        Literal["yahoo", "moody", "moody_us_news", "moody_us_press_releases"]
    ] = Field(
        default=None,
        description="The source of the news article.",
    )
    sentiment: Union[None, Literal["positive", "neutral", "negative"]] = Field(
        default=None,
        description="Return news only from this source.",
    )
    language: Optional[str] = Field(
        default=None,
        description="Filter by language. Unsupported for yahoo source.",
    )
    topic: Optional[str] = Field(
        default=None,
        description="Filter by topic. Unsupported for yahoo source.",
    )
    word_count_greater_than: Optional[int] = Field(
        default=None,
        description="News stories will have a word count greater than this value."
        + " Unsupported for yahoo source.",
    )
    word_count_less_than: Optional[int] = Field(
        default=None,
        description="News stories will have a word count less than this value."
        + " Unsupported for yahoo source.",
    )
    is_spam: Optional[bool] = Field(
        default=None,
        description="Filter whether it is marked as spam or not."
        + " Unsupported for yahoo source.",
    )
    business_relevance_greater_than: Optional[float] = Field(
        default=None,
        ge=0,
        le=1,
        description="News stories will have a business relevance score more than this value."
        + " Unsupported for yahoo source. Value is a decimal between 0 and 1.",
    )
    business_relevance_less_than: Optional[float] = Field(
        default=None,
        ge=0,
        le=1,
        description="News stories will have a business relevance score less than this value."
        + " Unsupported for yahoo source. Value is a decimal between 0 and 1.",
    )


class IntrinioCompanyNewsData(CompanyNewsData):
    """Intrinio Company News Data."""

    __alias_dict__ = {
        "date": "publication_date",
        "sentiment": "article_sentiment",
        "sentiment_confidence": "article_sentiment_confidence",
        "symbols": "symbol",
    }
    source: Optional[str] = Field(
        default=None,
        description="The source of the news article.",
    )
    summary: Optional[str] = Field(
        default=None,
        description="The summary of the news article.",
    )
    topics: Optional[str] = Field(
        default=None,
        description="The topics related to the news article.",
    )
    word_count: Optional[int] = Field(
        default=None,
        description="The word count of the news article.",
    )
    business_relevance: Optional[float] = Field(
        default=None,
        description=" 	How strongly correlated the news article is to the business",
    )
    sentiment: Optional[str] = Field(
        default=None,
        description="The sentiment of the news article - i.e, negative, positive.",
    )
    sentiment_confidence: Optional[float] = Field(
        default=None,
        description="The confidence score of the sentiment rating.",
    )
    language: Optional[str] = Field(
        default=None,
        description="The language of the news article.",
    )
    spam: Optional[bool] = Field(
        default=None,
        description="Whether the news article is spam.",
    )
    copyright: Optional[str] = Field(
        default=None,
        description="The copyright notice of the news article.",
    )
    id: str = Field(description="Article ID.")
    security: Optional[IntrinioSecurity] = Field(
        default=None,
        description="The Intrinio Security object. Contains the security details related to the news article.",
    )

    @field_validator("publication_date", mode="before", check_fields=False)
    @classmethod
    def date_validate(cls, v):
        """Return the date as a datetime object."""
        return datetime.strptime(v, "%Y-%m-%dT%H:%M:%S.000Z")

    @field_validator("topics", mode="before", check_fields=False)
    @classmethod
    def topics_validate(cls, v):
        """ "Parse the topics as a string."""
        if v:
            topics = [t.get("name") for t in v if t and t not in ["", " "]]
            return ", ".join(topics)
        return None

    @field_validator("copyright", mode="before", check_fields=False)
    @classmethod
    def copyright_validate(cls, v):
        """Clean empty strings"""
        return None if v in ["", " "] else v


class IntrinioCompanyNewsFetcher(
    Fetcher[
        IntrinioCompanyNewsQueryParams,
        List[IntrinioCompanyNewsData],
    ]
):
    """Transform the query, extract and transform the data from the Intrinio endpoints."""

    @staticmethod
    def transform_query(params: Dict[str, Any]) -> IntrinioCompanyNewsQueryParams:
        """Transform the query params."""
        transformed_params = params
        if not transformed_params.get("start_date"):
            transformed_params["start_date"] = (
                datetime.now() - timedelta(days=365)
            ).date()
        if not transformed_params.get("end_date"):
            transformed_params["end_date"] = (datetime.now() + timedelta(days=1)).date()
        if transformed_params["start_date"] == transformed_params["end_date"]:
            transformed_params["end_date"] = (
                transformed_params["end_date"] + timedelta(days=1)
            ).date()
        return IntrinioCompanyNewsQueryParams(**transformed_params)

    @staticmethod
    async def aextract_data(
        query: IntrinioCompanyNewsQueryParams,
        credentials: Optional[Dict[str, str]],
        **kwargs: Any,
    ) -> List[Dict]:
        """Return the raw data from the Intrinio endpoint."""
        api_key = credentials.get("intrinio_api_key") if credentials else ""

        base_url = "https://api-v2.intrinio.com/companies"
        ignore = (
            ["symbol", "page_size", "is_spam"]
            if not query.source or query.source == "yahoo"
            else ["symbol", "page_size"]
        )
        query_str = get_querystring(query.model_dump(by_alias=True), ignore)
        symbols = query.symbol.split(",") if query.symbol else []
        news: List = []

        async def callback(response, session):
            """Response callback."""
            result = await response.json()
            if "error" in result:
                raise RuntimeError(f"Intrinio Error Message -> {result['error']}")
            symbol = response.url.parts[-2]
            _data = result.get("news", [])
            data = []
            data.extend([{"symbol": symbol, **d} for d in _data])
            articles = len(data)
            next_page = result.get("next_page")
            # query.limit can be None...
            limit = query.limit or 2500
            while next_page and limit > articles:
                url = (
                    f"{base_url}/{symbol}/news?{query_str}"
                    + f"&page_size={query.limit}&api_key={api_key}&next_page={next_page}"
                )
                result = await get_data(url, session=session, **kwargs)
                _data = result.get(