laplace-python-sdk 1.7.0__py3-none-any.whl → 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
laplace/live_price.py CHANGED
@@ -17,6 +17,7 @@ from laplace.models import (
17
17
  USStockLiveData,
18
18
  BISTBidAskData,
19
19
  WebsocketMonthlyUsageDataResponse,
20
+ WebsocketUrlResponse,
20
21
  )
21
22
  from laplace.base import BaseClient
22
23
  BidAskData = BISTBidAskData
@@ -403,11 +404,11 @@ class LivePriceClient:
403
404
  self,
404
405
  feeds: List[LivePriceFeed],
405
406
  external_user_id: str
406
- ) -> str:
407
+ ) -> WebsocketUrlResponse:
407
408
  """Get WebSocket URL from the API.
408
409
 
409
410
  Returns:
410
- WebSocket URL
411
+ WebsocketUrlResponse with the WebSocket URL and when it expires
411
412
  """
412
413
 
413
414
  feed_values = [feed.value for feed in feeds]
@@ -420,7 +421,7 @@ class LivePriceClient:
420
421
  },
421
422
  )
422
423
 
423
- return response["url"]
424
+ return WebsocketUrlResponse(**response)
424
425
 
425
426
  def get_websocket_usage_for_month(
426
427
  self,
laplace/models.py CHANGED
@@ -843,10 +843,60 @@ class NewsType(str, Enum):
843
843
  REUTERS = "reuters"
844
844
 
845
845
  class NewsOrderBy(str, Enum):
846
- """News order by options."""
846
+ """News order by options.
847
+
848
+ ``TIMESTAMP`` is deprecated: use ``PUBLISHED_AT`` on v2. ``QUALITY_SCORE``
849
+ is the older spelling of ``QUALITY_SCORE_V2``; both are accepted. The
850
+ other fields are accepted by :meth:`~laplace.news.NewsClient.get_news_v2`.
851
+ """
847
852
 
848
853
  TIMESTAMP = "timestamp"
849
854
  QUALITY_SCORE = "quality_score"
855
+ PUBLISHED_AT = "publishedAt"
856
+ INGESTED_AT = "ingestedAt"
857
+ UPDATED_AT = "updatedAt"
858
+ QUALITY_SCORE_V2 = "qualityScore"
859
+
860
+
861
+ class NewsTickerRelevance(str, Enum):
862
+ """How central a tagged company is to an article.
863
+
864
+ ``PRIMARY``: the article is about this company (at most one per article).
865
+ ``MENTIONED``: named with some substance. ``LISTED``: only appears in a
866
+ list, ranking or market table.
867
+ """
868
+
869
+ PRIMARY = "primary"
870
+ MENTIONED = "mentioned"
871
+ LISTED = "listed"
872
+
873
+
874
+ class NewsEventType(str, Enum):
875
+ """Event type slugs for the ``event_types`` / ``exclude_event_types`` filters.
876
+
877
+ :meth:`~laplace.news.NewsClient.get_news_event_types` returns the current
878
+ list with localized names. Slugs not listed here can be passed as strings.
879
+ """
880
+
881
+ FINANCIAL_RESULTS = "financial-results"
882
+ GUIDANCE = "guidance"
883
+ OPERATIONAL_DATA = "operational-data"
884
+ ORDERS_INVESTMENTS = "orders-investments"
885
+ MANAGEMENT_CHANGE = "management-change"
886
+ REGULATION = "regulation"
887
+ LITIGATION = "litigation"
888
+ CREDIT_RATING = "credit-rating"
889
+ DIVIDEND = "dividend"
890
+ ANALYST_REPORT = "analyst-report"
891
+ PRICE_ACTION_TECHNICAL = "price-action-technical"
892
+ OTHER = "other"
893
+
894
+
895
+ class NewsOriginality(str, Enum):
896
+ """Values of :attr:`NewsV2.originality`."""
897
+
898
+ ORIGINAL = "original"
899
+ REWRITE = "rewrite"
850
900
 
851
901
 
852
902
  class NewsLane(str, Enum):
@@ -863,15 +913,40 @@ class NewsLane(str, Enum):
863
913
 
864
914
 
865
915
  class NewsTicker(BaseModel):
916
+ """A company tagged on a news item.
917
+
918
+ ``id`` is empty if the symbol has no listing. ``region`` and
919
+ ``relevance`` are set on v2 and stream items; ``relevance`` holds a
920
+ :class:`NewsTickerRelevance` value, or ``""`` when not classified. Both
921
+ are plain strings so values added later still parse.
922
+ """
923
+
866
924
  id: str
867
925
  name: str
868
926
  symbol: Optional[str] = None
927
+ region: Optional[str] = None
928
+ relevance: Optional[str] = None
929
+
930
+ model_config = {"populate_by_name": True}
931
+
932
+
933
+ class NewsEventTypeInfo(BaseModel):
934
+ """An event type with its localized name.
935
+
936
+ Attached to news items as ``event_type`` and returned by
937
+ :meth:`~laplace.news.NewsClient.get_news_event_types`.
938
+ """
939
+
940
+ slug: str
941
+ name: str
942
+ language: str
869
943
 
870
944
  model_config = {"populate_by_name": True}
871
945
 
946
+
872
947
  class NewsPublisher(BaseModel):
873
948
  name: str
874
- logo_url: Optional[str] = Field(alias="logoUrl")
949
+ logo_url: Optional[str] = Field(alias="logoUrl", default=None)
875
950
 
876
951
  model_config = {"populate_by_name": True}
877
952
 
@@ -965,6 +1040,33 @@ class News(BaseModel):
965
1040
  model_config = {"populate_by_name": True}
966
1041
 
967
1042
  class NewsV2(BaseModel):
1043
+ """A news item from the v2 endpoint and the live news stream.
1044
+
1045
+ Fields added after the first v2 release default to ``None`` / ``False``
1046
+ when a response doesn't carry them.
1047
+
1048
+ Attributes:
1049
+ id: Stable ID; it stays the same when the article is updated or
1050
+ replaced by a higher-trust copy.
1051
+ created_at: Same as ``ingested_at``.
1052
+ timestamp: Deprecated. ``published_at`` if known, else
1053
+ ``ingested_at``. Use ``published_at``.
1054
+ quality_score: 0-10; 0 means not scored yet.
1055
+ published_at: When the source published it; ``None`` when the source
1056
+ gave no usable date.
1057
+ ingested_at: When Laplace first stored it.
1058
+ content_updated_at: Last time the title or text changed; ``None`` if
1059
+ it never changed.
1060
+ updated_at: Last change of any kind. Use it with ``updated_since``.
1061
+ primary_ticker: The one company the article is about, if any.
1062
+ is_list_article: ``True`` for market wraps, rankings and lists.
1063
+ event_type: ``None`` until the article is classified.
1064
+ cluster_id: The story this article belongs to.
1065
+ is_cluster_lead: ``True`` for the first report of the story.
1066
+ cluster_size: How many articles cover the story.
1067
+ originality: A :class:`NewsOriginality` value.
1068
+ """
1069
+
968
1070
  id: str
969
1071
  created_at: datetime = Field(alias="createdAt")
970
1072
  url: str
@@ -982,7 +1084,50 @@ class NewsV2(BaseModel):
982
1084
 
983
1085
  quality_score: int = Field(alias="qualityScore")
984
1086
 
1087
+ published_at: Optional[datetime] = Field(alias="publishedAt", default=None)
1088
+ ingested_at: Optional[datetime] = Field(alias="ingestedAt", default=None)
1089
+ content_updated_at: Optional[datetime] = Field(alias="contentUpdatedAt", default=None)
1090
+ updated_at: Optional[datetime] = Field(alias="updatedAt", default=None)
1091
+ primary_ticker: Optional[str] = Field(alias="primaryTicker", default=None)
1092
+ is_list_article: bool = Field(alias="isListArticle", default=False)
1093
+ event_type: Optional[NewsEventTypeInfo] = Field(alias="eventType", default=None)
1094
+ cluster_id: Optional[str] = Field(alias="clusterId", default=None)
1095
+ is_cluster_lead: bool = Field(alias="isClusterLead", default=False)
1096
+ cluster_size: Optional[int] = Field(alias="clusterSize", default=None)
1097
+ originality: Optional[str] = None
1098
+
1099
+ model_config = {"populate_by_name": True}
1100
+
1101
+
1102
+ class NewsPublisherCap(BaseModel):
1103
+ """How ``max_publisher_share`` was applied to a v2 news result.
1104
+
1105
+ ``achieved_share`` is the largest share any publisher actually has. It
1106
+ can be above ``share`` when only a few publishers cover the query.
1107
+ """
1108
+
1109
+ share: float
1110
+ per_publisher: int = Field(alias="perPublisher")
1111
+ achieved_share: float = Field(alias="achievedShare")
1112
+
985
1113
  model_config = {"populate_by_name": True}
1114
+
1115
+
1116
+ class NewsV2Page(PaginatedResponse[NewsV2]):
1117
+ """A page of v2 news.
1118
+
1119
+ A :class:`PaginatedResponse` subclass, so ``record_count`` and ``items``
1120
+ read as before. ``record_count`` is ``None`` when ``include_total=False``.
1121
+ ``next_cursor`` is ``None`` on the last page; ``publisher_cap`` is set only
1122
+ when ``max_publisher_share`` was sent.
1123
+ """
1124
+
1125
+ record_count: Optional[int] = Field(alias="recordCount", default=None)
1126
+ next_cursor: Optional[str] = Field(alias="nextCursor", default=None)
1127
+ publisher_cap: Optional[NewsPublisherCap] = Field(alias="publisherCap", default=None)
1128
+
1129
+ model_config = {"populate_by_name": True}
1130
+
986
1131
  class NewsHighlight(BaseModel):
987
1132
  """A daily categorized news highlight as returned by /api/v1/news/highlights."""
988
1133
 
@@ -1218,6 +1363,13 @@ class ScreenerStock(BaseModel):
1218
1363
  model_config = {"populate_by_name": True}
1219
1364
 
1220
1365
 
1366
+ class WebsocketUrlResponse(BaseModel):
1367
+ url: str
1368
+ expires_at: datetime = Field(alias="expiresAt")
1369
+
1370
+ model_config = {"populate_by_name": True}
1371
+
1372
+
1221
1373
  class WebsocketMonthlyUsageDataResponse(BaseModel):
1222
1374
  external_user_id: str = Field(alias="externalUserID")
1223
1375
  first_connection_time: datetime = Field(alias="firstConnectionTime")
laplace/news.py CHANGED
@@ -1,7 +1,20 @@
1
1
  import asyncio
2
2
  import json
3
3
  import urllib.parse
4
- from typing import AsyncGenerator, Dict, Generic, List, Optional
4
+ from datetime import datetime, timezone
5
+ from enum import Enum
6
+ from typing import (
7
+ Any,
8
+ AsyncGenerator,
9
+ Dict,
10
+ Generic,
11
+ Iterator,
12
+ List,
13
+ Optional,
14
+ Sequence,
15
+ Tuple,
16
+ Union,
17
+ )
5
18
 
6
19
  import httpx
7
20
 
@@ -13,11 +26,15 @@ from .models import (
13
26
  NewsV2,
14
27
  NewsApiSourceListItem,
15
28
  NewsCategoryListItem,
29
+ NewsEventType,
30
+ NewsEventTypeInfo,
16
31
  NewsHighlight,
17
32
  NewsLane,
18
33
  NewsLaneListItem,
19
34
  NewsOrderBy,
35
+ NewsTickerRelevance,
20
36
  NewsType,
37
+ NewsV2Page,
21
38
  PaginatedResponse,
22
39
  PaginationPageSize,
23
40
  Region,
@@ -26,6 +43,73 @@ from .models import (
26
43
  )
27
44
 
28
45
 
46
+ # Filters that take one or more values accept a list (joined with commas) or a
47
+ # ready-made comma-separated string. Enum members and plain strings can be mixed,
48
+ # so values the SDK doesn't list yet can still be sent.
49
+ StrList = Union[str, Sequence[Union[str, Enum]]]
50
+ TickerRelevanceFilter = Union[str, Sequence[Union[NewsTickerRelevance, str]]]
51
+ EventTypeFilter = Union[str, Sequence[Union[NewsEventType, str]]]
52
+ OrderByField = Union[NewsOrderBy, str]
53
+ # A sort field, or a (field, direction) pair; a direction of None uses the API default (desc).
54
+ NewsOrder = Union[OrderByField, Tuple[OrderByField, Optional[Union[SortDirection, str]]]]
55
+ TimeValue = Union[str, datetime]
56
+
57
+
58
+ def _value(v: Union[str, Enum]) -> str:
59
+ return v.value if isinstance(v, Enum) else str(v)
60
+
61
+
62
+ def _join(values: StrList) -> str:
63
+ if isinstance(values, str):
64
+ return values
65
+ return ",".join(_value(v) for v in values)
66
+
67
+
68
+ def _bool(v: bool) -> str:
69
+ return "true" if v else "false"
70
+
71
+
72
+ def _time(v: TimeValue) -> str:
73
+ if isinstance(v, datetime):
74
+ if v.tzinfo is None:
75
+ v = v.replace(tzinfo=timezone.utc)
76
+ return v.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
77
+ return v
78
+
79
+
80
+ def _order(fields: Sequence[NewsOrder]) -> str:
81
+ parts = []
82
+ for f in fields:
83
+ if isinstance(f, tuple):
84
+ field, direction = f
85
+ parts.append(_value(field) + (f" {_value(direction)}" if direction else ""))
86
+ else:
87
+ parts.append(_value(f))
88
+ return ",".join(parts)
89
+
90
+
91
+ def _content_filter_params(
92
+ ticker_relevance: Optional[TickerRelevanceFilter],
93
+ exclude_list_articles: Optional[bool],
94
+ event_types: Optional[EventTypeFilter],
95
+ exclude_event_types: Optional[EventTypeFilter],
96
+ collapse_clusters: Optional[bool],
97
+ ) -> Dict[str, str]:
98
+ """Query params for the content filters shared by /v2/news and the stream."""
99
+ params: Dict[str, str] = {}
100
+ if ticker_relevance:
101
+ params["tickerRelevance"] = _join(ticker_relevance)
102
+ if exclude_list_articles is not None:
103
+ params["excludeListArticles"] = _bool(exclude_list_articles)
104
+ if event_types:
105
+ params["eventTypes"] = _join(event_types)
106
+ if exclude_event_types:
107
+ params["excludeEventTypes"] = _join(exclude_event_types)
108
+ if collapse_clusters is not None:
109
+ params["collapseClusters"] = _bool(collapse_clusters)
110
+ return params
111
+
112
+
29
113
  class NewsStreamResult(Generic[T]):
30
114
  """Result wrapper for news stream data."""
31
115
 
@@ -52,6 +136,11 @@ class NewsStream:
52
136
  sector_ids: Optional[List[str]] = None,
53
137
  industry_ids: Optional[List[str]] = None,
54
138
  api_sources: Optional[List[str]] = None,
139
+ ticker_relevance: Optional[TickerRelevanceFilter] = None,
140
+ exclude_list_articles: Optional[bool] = None,
141
+ event_types: Optional[EventTypeFilter] = None,
142
+ exclude_event_types: Optional[EventTypeFilter] = None,
143
+ collapse_clusters: Optional[bool] = None,
55
144
  ):
56
145
  self.base_client = base_client
57
146
  self.locale = locale
@@ -62,6 +151,11 @@ class NewsStream:
62
151
  self.sector_ids = sector_ids
63
152
  self.industry_ids = industry_ids
64
153
  self.api_sources = api_sources
154
+ self.ticker_relevance = ticker_relevance
155
+ self.exclude_list_articles = exclude_list_articles
156
+ self.event_types = event_types
157
+ self.exclude_event_types = exclude_event_types
158
+ self.collapse_clusters = collapse_clusters
65
159
  self._task: Optional[asyncio.Task] = None
66
160
  self._queue: Optional[asyncio.Queue[NewsStreamResult[List[NewsV2]]]] = None
67
161
  self._is_closed = False
@@ -125,6 +219,15 @@ class NewsStream:
125
219
  params["industryIds"] = ",".join(self.industry_ids)
126
220
  if self.api_sources:
127
221
  params["apiSource"] = ",".join(self.api_sources)
222
+ params.update(
223
+ _content_filter_params(
224
+ self.ticker_relevance,
225
+ self.exclude_list_articles,
226
+ self.event_types,
227
+ self.exclude_event_types,
228
+ self.collapse_clusters,
229
+ )
230
+ )
128
231
 
129
232
  query_string = urllib.parse.urlencode(params)
130
233
  return f"{url}?{query_string}"
@@ -247,8 +350,10 @@ class NewsClient:
247
350
  industry_ids: Optional comma-separated Laplace industry ids
248
351
  quality_score_min: Optional minimum quality score, inclusive (0-10)
249
352
  quality_score_max: Optional maximum quality score, inclusive (0-10)
250
- timestamp_from: Optional start date, inclusive (YYYY-MM-DD)
251
- timestamp_to: Optional end date, inclusive (YYYY-MM-DD)
353
+ timestamp_from: Optional start date, inclusive (YYYY-MM-DD).
354
+ Deprecated by the API; on v2 use ``published_from``.
355
+ timestamp_to: Optional end date, inclusive (YYYY-MM-DD).
356
+ Deprecated by the API; on v2 use ``published_to``.
252
357
  extra_filters: Optional extra filters (API-specific)
253
358
  page: Page number (default: 0)
254
359
  page_size: Page size enum (default: 10)
@@ -300,22 +405,36 @@ class NewsClient:
300
405
  locale: Locale,
301
406
  region: Region,
302
407
  news_type: Optional[NewsType] = None,
303
- news_order_by: Optional[NewsOrderBy] = None,
408
+ news_order_by: Optional[OrderByField] = None,
304
409
  direction: Optional[SortDirection] = None,
305
410
  lane: Optional[NewsLane] = None,
306
411
  api_source: Optional[str] = None,
307
- symbols: Optional[str] = None,
308
- category_ids: Optional[str] = None,
309
- sector_ids: Optional[str] = None,
310
- industry_ids: Optional[str] = None,
412
+ symbols: Optional[StrList] = None,
413
+ category_ids: Optional[StrList] = None,
414
+ sector_ids: Optional[StrList] = None,
415
+ industry_ids: Optional[StrList] = None,
311
416
  quality_score_min: Optional[int] = None,
312
417
  quality_score_max: Optional[int] = None,
313
418
  timestamp_from: Optional[str] = None,
314
419
  timestamp_to: Optional[str] = None,
315
- page: int = 0,
316
- page_size: PaginationPageSize = PaginationPageSize.PAGE_SIZE_10,
317
- ) -> PaginatedResponse[NewsV2]:
318
- """Retrieve paginated news (v2).
420
+ page: Optional[int] = None,
421
+ page_size: Union[PaginationPageSize, int] = PaginationPageSize.PAGE_SIZE_10,
422
+ *,
423
+ ticker_relevance: Optional[TickerRelevanceFilter] = None,
424
+ exclude_list_articles: Optional[bool] = None,
425
+ event_types: Optional[EventTypeFilter] = None,
426
+ exclude_event_types: Optional[EventTypeFilter] = None,
427
+ collapse_clusters: Optional[bool] = None,
428
+ max_publisher_share: Optional[int] = None,
429
+ published_from: Optional[TimeValue] = None,
430
+ published_to: Optional[TimeValue] = None,
431
+ updated_since: Optional[TimeValue] = None,
432
+ as_of: Optional[TimeValue] = None,
433
+ order_by: Optional[Sequence[NewsOrder]] = None,
434
+ cursor: Optional[str] = None,
435
+ include_total: Optional[bool] = None,
436
+ ) -> NewsV2Page:
437
+ """Retrieve a page of news (v2), newest first by default.
319
438
 
320
439
  Within a single filter, comma-separated values are OR-ed; different
321
440
  filters are AND-ed together (e.g. ``(AAPL OR MSFT) AND category 1``).
@@ -323,55 +442,98 @@ class NewsClient:
323
442
  ids returned by :meth:`get_news_categories`; ``sector_ids`` and
324
443
  ``industry_ids`` take Laplace sector/industry ids.
325
444
 
445
+ Multi-value filters take a list or a comma-separated string. Enum
446
+ values and plain strings are both accepted; the API rejects unknown
447
+ values with a 400 (:class:`~laplace.base.LaplaceAPIError`, message in
448
+ ``error.response["message"]``). Unset filters aren't sent.
449
+
326
450
  Args:
327
451
  locale: Locale code (e.g. "tr", "en")
328
452
  region: Region enum (e.g. Region.TR)
329
453
  news_type: Optional news type filter
330
- news_order_by: Optional sorting field (timestamp, quality_score)
331
- direction: Optional sort direction
454
+ news_order_by: Optional single sorting field (see
455
+ :class:`~laplace.models.NewsOrderBy`)
456
+ direction: Optional sort direction for ``news_order_by``
332
457
  lane: Optional lane filter. Lanes are region-scoped: US lanes are
333
458
  GLOBAL_MACRO and FAST_MOVERS; TR lanes are TR_EKONOMI and BIST.
334
459
  api_source: Optional comma-separated source ids from
335
460
  :meth:`get_news_api_source_names` (e.g. "BBCBusiness,MarketWatch")
336
- symbols: Optional comma-separated ticker symbols (e.g. "AAPL,MSFT")
337
- category_ids: Optional comma-separated numeric category ids (e.g. "1,3")
338
- sector_ids: Optional comma-separated Laplace sector ids
339
- industry_ids: Optional comma-separated Laplace industry ids
340
- quality_score_min: Optional minimum quality score, inclusive (0-10)
461
+ symbols: Optional ticker symbols, up to 50 (e.g. ["AAPL", "MSFT"])
462
+ category_ids: Optional numeric category ids (e.g. "1,3")
463
+ sector_ids: Optional Laplace sector ids
464
+ industry_ids: Optional Laplace industry ids
465
+ quality_score_min: Optional minimum quality score, inclusive
466
+ (0-10). The API default is 3; send 0 to include unscored items.
341
467
  quality_score_max: Optional maximum quality score, inclusive (0-10)
342
- timestamp_from: Optional start date, inclusive (YYYY-MM-DD)
343
- timestamp_to: Optional end date, inclusive (YYYY-MM-DD)
344
- page: Page number (default: 0)
345
- page_size: Page size enum (default: 10)
468
+ timestamp_from: Deprecated; use ``published_from``.
469
+ timestamp_to: Deprecated; use ``published_to``.
470
+ page: Optional page number for offset paging. Can't be combined
471
+ with ``cursor``. Sent as 0 when neither is given, as before.
472
+ page_size: Items per page, 1-100 (int or PaginationPageSize;
473
+ default: 10)
474
+ ticker_relevance: Keep news where a ticker (one of ``symbols``, if
475
+ given) has one of these relevances
476
+ exclude_list_articles: ``True`` drops market wraps, "most traded"
477
+ lists and top-gainer tables
478
+ event_types: Keep only these event types
479
+ exclude_event_types: Drop these event types (unclassified kept)
480
+ collapse_clusters: ``True`` returns each story once
481
+ max_publisher_share: 1-100 (percent); limits how much of the
482
+ result one publisher can take. See ``publisher_cap``.
483
+ published_from: Lower bound on ``published_at`` (RFC3339 string,
484
+ YYYY-MM-DD, or datetime; naive datetimes are read as UTC)
485
+ published_to: Upper bound on ``published_at``; a date includes
486
+ the whole day
487
+ updated_since: Lower bound on ``updated_at``, for incremental
488
+ sync. Changes the default order to updatedAt ascending.
489
+ as_of: Return the result as it was at that time
490
+ order_by: Up to 3 sort fields, each a field or a
491
+ ``(field, direction)`` pair, e.g.
492
+ ``[(NewsOrderBy.QUALITY_SCORE_V2, SortDirection.DESC),
493
+ (NewsOrderBy.PUBLISHED_AT, SortDirection.DESC)]``.
494
+ Replaces ``news_order_by`` / ``direction``. Cursors only work
495
+ with a single field.
496
+ cursor: ``next_cursor`` from the previous page. An empty string
497
+ requests the first page of a cursor run (no ``page`` sent).
498
+ include_total: ``False`` skips counting all matches (faster);
499
+ ``record_count`` is then ``None``
346
500
 
347
501
  Returns:
348
- PaginatedResponse[NewsV2]
502
+ NewsV2Page (a PaginatedResponse[NewsV2] with ``next_cursor`` and
503
+ ``publisher_cap``)
349
504
  """
350
505
  params: Dict[str, object] = {
351
506
  "locale": locale,
352
507
  "region": region.value,
353
- "page": page,
354
- "size": page_size.value,
508
+ "size": int(page_size),
355
509
  }
510
+ if page is not None:
511
+ params["page"] = page
512
+ elif cursor is None:
513
+ # Keep the request unchanged for callers that relied on the old default.
514
+ params["page"] = 0
356
515
 
357
516
  if news_type is not None:
358
517
  params["newsType"] = news_type.value
359
- if news_order_by is not None:
360
- params["orderBy"] = news_order_by.value
361
- if direction is not None:
362
- params["orderByDirection"] = direction.value
518
+ if order_by:
519
+ params["orderBy"] = _order(order_by)
520
+ else:
521
+ if news_order_by is not None:
522
+ params["orderBy"] = _value(news_order_by)
523
+ if direction is not None:
524
+ params["orderByDirection"] = direction.value
363
525
  if lane is not None:
364
526
  params["lane"] = lane.value
365
527
  if api_source:
366
528
  params["apiSource"] = api_source
367
529
  if symbols:
368
- params["symbols"] = symbols
530
+ params["symbols"] = _join(symbols)
369
531
  if category_ids:
370
- params["categoryIds"] = category_ids
532
+ params["categoryIds"] = _join(category_ids)
371
533
  if sector_ids:
372
- params["sectorIds"] = sector_ids
534
+ params["sectorIds"] = _join(sector_ids)
373
535
  if industry_ids:
374
- params["industryIds"] = industry_ids
536
+ params["industryIds"] = _join(industry_ids)
375
537
  if quality_score_min is not None:
376
538
  params["qualityScoreMin"] = quality_score_min
377
539
  if quality_score_max is not None:
@@ -381,8 +543,59 @@ class NewsClient:
381
543
  if timestamp_to:
382
544
  params["timestampTo"] = timestamp_to
383
545
 
546
+ params.update(
547
+ _content_filter_params(
548
+ ticker_relevance,
549
+ exclude_list_articles,
550
+ event_types,
551
+ exclude_event_types,
552
+ collapse_clusters,
553
+ )
554
+ )
555
+ if max_publisher_share is not None:
556
+ params["maxPublisherShare"] = max_publisher_share
557
+ if published_from is not None:
558
+ params["publishedFrom"] = _time(published_from)
559
+ if published_to is not None:
560
+ params["publishedTo"] = _time(published_to)
561
+ if updated_since is not None:
562
+ params["updatedSince"] = _time(updated_since)
563
+ if as_of is not None:
564
+ params["asOf"] = _time(as_of)
565
+ if cursor:
566
+ params["cursor"] = cursor
567
+ if include_total is not None:
568
+ params["includeTotal"] = _bool(include_total)
569
+
384
570
  response = self._client.get("v2/news", params=params)
385
- return PaginatedResponse[NewsV2](**response)
571
+ return NewsV2Page(**response)
572
+
573
+ def iter_news_v2(self, locale: Locale, region: Region, **kwargs: Any) -> Iterator[NewsV2]:
574
+ """Yield every v2 news item matching the filters, following cursors.
575
+
576
+ Takes the same arguments as :meth:`get_news_v2`. Sends
577
+ ``include_total=False`` and keeps every other argument the same
578
+ between pages. Pass ``cursor`` to resume from a saved position.
579
+ ``page`` can't be used, since the API rejects it with a cursor.
580
+ API errors are raised as they happen.
581
+
582
+ Example:
583
+ for item in client.news.iter_news_v2("tr", Region.TR, symbols="THYAO",
584
+ page_size=100):
585
+ handle(item)
586
+ """
587
+ if kwargs.get("page") is not None:
588
+ raise ValueError("iter_news_v2 uses cursor paging; don't pass page")
589
+ kwargs.pop("page", None)
590
+ kwargs["include_total"] = False
591
+ kwargs["cursor"] = kwargs.get("cursor") or ""
592
+
593
+ while True:
594
+ result = self.get_news_v2(locale, region, **kwargs)
595
+ yield from result.items
596
+ if not result.next_cursor:
597
+ return
598
+ kwargs["cursor"] = result.next_cursor
386
599
 
387
600
  def get_news_categories(
388
601
  self,
@@ -410,6 +623,25 @@ class NewsClient:
410
623
  response = self._client.get("v1/news/categories", params=params)
411
624
  return [NewsCategoryListItem(**item) for item in response]
412
625
 
626
+ def get_news_event_types(
627
+ self,
628
+ locale: Optional[Locale] = None,
629
+ ) -> List[NewsEventTypeInfo]:
630
+ """Retrieve the event types accepted by ``event_types`` / ``exclude_event_types``.
631
+
632
+ Args:
633
+ locale: Optional language of the names ("tr", "en"; default "en")
634
+
635
+ Returns:
636
+ List of NewsEventTypeInfo (``slug``, ``name``, ``language``)
637
+ """
638
+ params: Dict[str, object] = {}
639
+ if locale is not None:
640
+ params["locale"] = locale
641
+
642
+ response = self._client.get("v1/news/event-types", params=params)
643
+ return [NewsEventTypeInfo(**item) for item in response]
644
+
413
645
  def get_news_lanes(
414
646
  self,
415
647
  region: Optional[Region] = None,
@@ -515,6 +747,11 @@ class NewsClient:
515
747
  sector_ids: Optional[List[str]] = None,
516
748
  industry_ids: Optional[List[str]] = None,
517
749
  api_sources: Optional[List[str]] = None,
750
+ ticker_relevance: Optional[TickerRelevanceFilter] = None,
751
+ exclude_list_articles: Optional[bool] = None,
752
+ event_types: Optional[EventTypeFilter] = None,
753
+ exclude_event_types: Optional[EventTypeFilter] = None,
754
+ collapse_clusters: Optional[bool] = None,
518
755
  ) -> NewsStream:
519
756
  """Start streaming news updates.
520
757
 
@@ -531,6 +768,11 @@ class NewsClient:
531
768
  api_sources: Optional list of source ids from
532
769
  :meth:`get_news_api_source_names`; only these sources are
533
770
  streamed
771
+ ticker_relevance: Same as on :meth:`get_news_v2`
772
+ exclude_list_articles: Same as on :meth:`get_news_v2`
773
+ event_types: Same as on :meth:`get_news_v2`
774
+ exclude_event_types: Same as on :meth:`get_news_v2`
775
+ collapse_clusters: Same as on :meth:`get_news_v2`
534
776
 
535
777
  Returns:
536
778
  NewsStream for consuming news items
@@ -545,6 +787,11 @@ class NewsClient:
545
787
  sector_ids=sector_ids,
546
788
  industry_ids=industry_ids,
547
789
  api_sources=api_sources,
790
+ ticker_relevance=ticker_relevance,
791
+ exclude_list_articles=exclude_list_articles,
792
+ event_types=event_types,
793
+ exclude_event_types=exclude_event_types,
794
+ collapse_clusters=collapse_clusters,
548
795
  )
549
796
  await stream.subscribe()
550
797
  return stream
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: laplace-python-sdk
3
- Version: 1.7.0
3
+ Version: 2.0.0
4
4
  Summary: Python SDK for Laplace stock data platform
5
5
  Author: Laplace SDK Team
6
6
  License: MIT
@@ -60,6 +60,8 @@ The official Python SDK for the Laplace stock data platform. Get easy access to
60
60
  pip install laplace-python-sdk
61
61
  ```
62
62
 
63
+ > **Upgrading from v1?** v2 changes `client.live_price.get_websocket_url` to return a `WebsocketUrlResponse` (with `url` and `expires_at`) instead of a string. Where you used the result as the URL, use `.url` instead, e.g. `websockets.connect(resp.url)`. The link stops working at `expires_at`; request a new one before then.
64
+
63
65
  ## Quick Start
64
66
 
65
67
  ```python
@@ -182,6 +184,89 @@ holdings = client.politicians.get_politician_holdings_by_symbol(symbol="AAPL")
182
184
  top_holdings = client.politicians.get_top_holdings()
183
185
  ```
184
186
 
187
+ ### News Client
188
+
189
+ `get_news_v2` returns a `NewsV2Page`: a `PaginatedResponse[NewsV2]` with `next_cursor` and `publisher_cap` added. Multi-value filters take a list or a comma-separated string, and enum values and plain strings can be mixed. Filters you don't set aren't sent.
190
+
191
+ ```python
192
+ from laplace.models import NewsEventType, NewsOrderBy, NewsTickerRelevance, Region, SortDirection
193
+
194
+ # News about one company: drop table-only mentions and market wraps,
195
+ # cap any publisher at 25% of the result and show each story once.
196
+ page = client.news.get_news_v2(
197
+ locale="tr",
198
+ region=Region.TR,
199
+ symbols=["THYAO"],
200
+ ticker_relevance=[NewsTickerRelevance.PRIMARY, NewsTickerRelevance.MENTIONED],
201
+ exclude_list_articles=True,
202
+ collapse_clusters=True,
203
+ max_publisher_share=25,
204
+ event_types=[NewsEventType.FINANCIAL_RESULTS, NewsEventType.DIVIDEND],
205
+ order_by=[
206
+ (NewsOrderBy.QUALITY_SCORE_V2, SortDirection.DESC),
207
+ (NewsOrderBy.PUBLISHED_AT, SortDirection.DESC),
208
+ ],
209
+ page_size=50, # any value from 1 to 100
210
+ )
211
+ for item in page.items:
212
+ print(item.primary_ticker, item.content.title, item.event_type, item.cluster_size)
213
+ ```
214
+
215
+ ```python
216
+ # Cursor paging: iter_news_v2 follows next_cursor until the last page and
217
+ # sends include_total=False. It takes the same arguments as get_news_v2,
218
+ # except page.
219
+ for item in client.news.iter_news_v2(
220
+ "tr", Region.TR, symbols="THYAO", page_size=100, published_from="2026-11-01"
221
+ ):
222
+ handle(item)
223
+ ```
224
+
225
+ ```python
226
+ from datetime import timedelta
227
+
228
+ # Incremental sync: upsert by id, then store the largest updated_at minus
229
+ # 5 minutes as the next updated_since. quality_score_min=0 makes articles
230
+ # whose score is later lowered still arrive as updates.
231
+ latest = None
232
+ for item in client.news.iter_news_v2(
233
+ "tr",
234
+ Region.TR,
235
+ updated_since=last_sync, # datetime or RFC3339 string
236
+ quality_score_min=0,
237
+ page_size=100,
238
+ ):
239
+ store.upsert(item.id, item)
240
+ if item.updated_at and (latest is None or item.updated_at > latest):
241
+ latest = item.updated_at
242
+ if latest is not None:
243
+ last_sync = latest - timedelta(minutes=5)
244
+ ```
245
+
246
+ `record_count` is `None` when `include_total=False` (and in `iter_news_v2`). `published_at` and `content_updated_at` are `None` when unknown. `timestamp`, `timestamp_from` and `timestamp_to` are deprecated: use `published_at` and `published_from` / `published_to`.
247
+
248
+ The API rejects unknown values with a `400`, raised as `LaplaceAPIError`. The API's message is in `error.response["message"]`.
249
+
250
+ ```python
251
+ # Lookups
252
+ event_types = client.news.get_news_event_types(locale="tr")
253
+ categories = client.news.get_news_categories(locale="tr") # ids for category_ids
254
+ lanes = client.news.get_news_lanes(region=Region.TR)
255
+
256
+ # Live news with the same content filters
257
+ stream = await client.news.get_news_stream(
258
+ locale="tr",
259
+ region=Region.TR,
260
+ symbols=["THYAO", "GARAN"],
261
+ exclude_list_articles=True,
262
+ event_types=[NewsEventType.FINANCIAL_RESULTS],
263
+ )
264
+ async for result in stream:
265
+ if result.data:
266
+ for item in result.data:
267
+ print(item.primary_ticker, item.published_at)
268
+ ```
269
+
185
270
  ### WebSocket Client (Live Price Data)
186
271
 
187
272
  ```python
@@ -7,17 +7,17 @@ laplace/collections.py,sha256=jhIVxTbn9j1Dpi3OCp3S5vG29xYB6aw2BNoI4v0-b7M,10256
7
7
  laplace/earnings.py,sha256=y1fVgfJUXGl3vOSF9g6ryuoYYygXuxcsfk4VO2SVRjE,2114
8
8
  laplace/financials.py,sha256=QJPlOzd5dhhOC2bdtbGmPfnsHx9bCf9nCM34bVtzYag,3132
9
9
  laplace/funds.py,sha256=o-lmCtXX60ehaoYOuCRayU7P1n9D6oHaZR6N3OXq5kU,3200
10
- laplace/live_price.py,sha256=4l3YhfVjnRv7f_h-EBFLo5m0tGTGYdP5E6BcNrTXegE,16360
11
- laplace/models.py,sha256=qZIPTsLv08Kg0PGCPopBcp9skB6xRxwNujM9wsIDNkI,39067
12
- laplace/news.py,sha256=ekXdxZV5iywCh5JVc1JjdAW-XdDbM9rrKAg_p383GGA,20804
10
+ laplace/live_price.py,sha256=3pbRCVgXaDL8vMIeouRNtcnfObOlN-HaHAtuxgpUWgc,16470
11
+ laplace/models.py,sha256=7cd9rxGvVey404u55IvNxV2K-33XSuuSNacLQg50Iqo,44745
12
+ laplace/news.py,sha256=OClfiVqXKhR1qg8gnX2yJK0ab_lJUb3omQR7ioPGJw0,31267
13
13
  laplace/politician.py,sha256=Llez12RDJZWC8AOwRn4vupT7NZ6mZNk_b6JcNSMJGyA,1778
14
14
  laplace/screener.py,sha256=p4hz8bs0WqTpV1Y4dELTPw-kXjF9R5fecYQIN3pToRw,1994
15
15
  laplace/search.py,sha256=JYsb8Nr5F-UMS53MGaMHL3d6VxJ7M8V3xHnFK22ORMg,1518
16
16
  laplace/state.py,sha256=P2Ky0fToDc_VauBFD7bw91dywVkY3TaIN3mhf0Ms5sg,3417
17
17
  laplace/stocks.py,sha256=ou4k_Kv9n_Nm_9hayYvLxHub1cX0qnjhgJeCM-6epo0,12552
18
18
  laplace/websocket.py,sha256=9VNCA38Y_jznSDDajwybSoRtBz1BoANqcFZMZiUBG88,15603
19
- laplace_python_sdk-1.7.0.dist-info/licenses/LICENSE,sha256=7q_XpeQPP0BLMADuenSz0wqLxttWJtoOei0sYmqly0g,1063
20
- laplace_python_sdk-1.7.0.dist-info/METADATA,sha256=B-NAqpm_xhmRhJ90aVTtNLMb1Ge1XVdo1G2hfZmhYeY,9545
21
- laplace_python_sdk-1.7.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
22
- laplace_python_sdk-1.7.0.dist-info/top_level.txt,sha256=miT6qTaH7MSLy2iNStZCy478rCt72Hij9KP1bRBTGPA,8
23
- laplace_python_sdk-1.7.0.dist-info/RECORD,,
19
+ laplace_python_sdk-2.0.0.dist-info/licenses/LICENSE,sha256=7q_XpeQPP0BLMADuenSz0wqLxttWJtoOei0sYmqly0g,1063
20
+ laplace_python_sdk-2.0.0.dist-info/METADATA,sha256=8CYQxmD5-vA_ms7fz6nWBLz6gbn69ydJN3IjbVfxoVg,12987
21
+ laplace_python_sdk-2.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
22
+ laplace_python_sdk-2.0.0.dist-info/top_level.txt,sha256=miT6qTaH7MSLy2iNStZCy478rCt72Hij9KP1bRBTGPA,8
23
+ laplace_python_sdk-2.0.0.dist-info/RECORD,,