kensho-kfinance 2.1.2__tar.gz → 2.2.2__tar.gz

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.

Potentially problematic release.


This version of kensho-kfinance might be problematic. Click here for more details.

Files changed (73) hide show
  1. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/.gitignore +1 -0
  2. {kensho_kfinance-2.1.2/kensho_kfinance.egg-info → kensho_kfinance-2.2.2}/PKG-INFO +7 -1
  3. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/README.md +2 -0
  4. kensho_kfinance-2.2.2/images/colab_logo_32px.png +0 -0
  5. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/justfile +1 -0
  6. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2/kensho_kfinance.egg-info}/PKG-INFO +7 -1
  7. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kensho_kfinance.egg-info/SOURCES.txt +4 -3
  8. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kensho_kfinance.egg-info/requires.txt +4 -0
  9. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/CHANGELOG.md +9 -0
  10. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/batch_request_handling.py +32 -27
  11. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/constants.py +7 -0
  12. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/fetch.py +22 -0
  13. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/kfinance.py +39 -65
  14. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/meta_classes.py +109 -1
  15. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tests/test_batch_requests.py +33 -1
  16. kensho_kfinance-2.2.2/kfinance/tests/test_example_notebook.py +194 -0
  17. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tests/test_fetch.py +23 -0
  18. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tests/test_objects.py +40 -0
  19. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tests/test_tools.py +12 -34
  20. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/__init__.py +2 -6
  21. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_info_from_identifier.py +1 -1
  22. kensho_kfinance-2.2.2/kfinance/tool_calling/resolve_identifier.py +18 -0
  23. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/version.py +2 -2
  24. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/pyproject.toml +7 -0
  25. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/scripts/lint.sh +2 -0
  26. kensho_kfinance-2.2.2/usage_examples.ipynb +285 -0
  27. kensho_kfinance-2.1.2/kfinance/tool_calling/get_company_id_from_identifier.py +0 -16
  28. kensho_kfinance-2.1.2/kfinance/tool_calling/get_security_id_from_identifier.py +0 -16
  29. kensho_kfinance-2.1.2/kfinance/tool_calling/get_trading_item_id_from_identifier.py +0 -16
  30. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/.coveragerc +0 -0
  31. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/.github/workflows/ci-lint.yml +0 -0
  32. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/.github/workflows/ci-test.yml +0 -0
  33. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/.github/workflows/python-publish.yml +0 -0
  34. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/.readthedocs.yaml +0 -0
  35. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/AUTHORS.md +0 -0
  36. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/CODE_OF_CONDUCT.md +0 -0
  37. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/CONTRIBUTING.md +0 -0
  38. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/LICENSE +0 -0
  39. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/docs/build_tool_calling_documentation.py +0 -0
  40. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/docs/conf.py +0 -0
  41. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/docs/index.rst +0 -0
  42. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/docs/kfinance.rst +0 -0
  43. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/docs/requirements.txt +0 -0
  44. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/docs/templates/apidoc/package.rst_t +0 -0
  45. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/docs/templates/apidoc/toc.rst_t +0 -0
  46. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/docs/tool_calling.rst +0 -0
  47. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kensho_kfinance.egg-info/dependency_links.txt +0 -0
  48. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kensho_kfinance.egg-info/top_level.txt +0 -0
  49. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/__init__.py +0 -0
  50. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/prompt.py +0 -0
  51. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/py.typed +0 -0
  52. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/server_thread.py +0 -0
  53. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tests/__init__.py +0 -0
  54. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tests/conftest.py +0 -0
  55. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tests/test_client.py +0 -0
  56. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tests/test_group_objects.py +0 -0
  57. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/README.md +0 -0
  58. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_business_relationship_from_identifier.py +0 -0
  59. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_capitalization_from_identifier.py +0 -0
  60. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_cusip_from_ticker.py +0 -0
  61. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_earnings_call_datetimes_from_identifier.py +0 -0
  62. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_financial_line_item_from_identifier.py +0 -0
  63. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_financial_statement_from_identifier.py +0 -0
  64. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_history_metadata_from_identifier.py +0 -0
  65. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_isin_from_ticker.py +0 -0
  66. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_latest.py +0 -0
  67. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_n_quarters_ago.py +0 -0
  68. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/get_prices_from_identifier.py +0 -0
  69. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/kfinance/tool_calling/shared_models.py +0 -0
  70. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/scripts/copyright_line_check.sh +0 -0
  71. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/scripts/test.sh +0 -0
  72. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/setup.cfg +0 -0
  73. {kensho_kfinance-2.1.2 → kensho_kfinance-2.2.2}/setup.py +0 -0
@@ -4,6 +4,7 @@ __pycache__/
4
4
  *$py.class
5
5
 
6
6
  # Distribution / packaging
7
+ .python-version
7
8
  .Python
8
9
  build/
9
10
  develop-eggs/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kensho-kfinance
3
- Version: 2.1.2
3
+ Version: 2.2.2
4
4
  Summary: Python CLI for kFinance
5
5
  Author-email: Luke Brown <luke.brown@kensho.com>, Michelle Keoy <michelle.keoy@kensho.com>, Keith Page <keith.page@kensho.com>, Matthew Rosen <matthew.rosen@kensho.com>, Nick Roshdieh <nick.roshdieh@kensho.com>
6
6
  Project-URL: source, https://github.com/kensho-technologies/kfinance
@@ -28,7 +28,11 @@ Requires-Dist: requests<3,>=2.22.0
28
28
  Requires-Dist: urllib3>=1.21.1
29
29
  Provides-Extra: dev
30
30
  Requires-Dist: coverage<8,>=7.6.10; extra == "dev"
31
+ Requires-Dist: ipykernel<7,>=6.29; extra == "dev"
31
32
  Requires-Dist: mypy<2,>=1.15.0; extra == "dev"
33
+ Requires-Dist: nbconvert<8,>=7.16; extra == "dev"
34
+ Requires-Dist: nbformat<6,>5.10; extra == "dev"
35
+ Requires-Dist: nbqa<2,>1.9; extra == "dev"
32
36
  Requires-Dist: pytest<7,>=6.1.2; extra == "dev"
33
37
  Requires-Dist: pytest-cov<7,>=6.0.0; extra == "dev"
34
38
  Requires-Dist: requests_mock<2,>=1.12; extra == "dev"
@@ -57,6 +61,8 @@ To receive access, please email [S&P Global Market Intelligence](market.intellig
57
61
 
58
62
  Once access is obtained, get started using the [Authentication Guide](https://docs.kensho.com/llmreadyapi/kf-authentication) and [Usage Guide](https://docs.kensho.com/llmreadyapi/usage).
59
63
 
64
+ We also provide an [interactive notebook](usage_examples.ipynb) that demonstrates some usage examples.
65
+
60
66
  # Versioning
61
67
  The kFinance uses semantic versioning (major, minor, patch).
62
68
  To bump the version, add a new entry in [CHANGELOG.md](kfinance%2FCHANGELOG.md).
@@ -18,6 +18,8 @@ To receive access, please email [S&P Global Market Intelligence](market.intellig
18
18
 
19
19
  Once access is obtained, get started using the [Authentication Guide](https://docs.kensho.com/llmreadyapi/kf-authentication) and [Usage Guide](https://docs.kensho.com/llmreadyapi/usage).
20
20
 
21
+ We also provide an [interactive notebook](usage_examples.ipynb) that demonstrates some usage examples.
22
+
21
23
  # Versioning
22
24
  The kFinance uses semantic versioning (major, minor, patch).
23
25
  To bump the version, add a new entry in [CHANGELOG.md](kfinance%2FCHANGELOG.md).
@@ -24,6 +24,7 @@ lint *args:
24
24
  # See https://docs.astral.sh/ruff/formatter/#sorting-imports
25
25
  python -m ruff --config pyproject.toml check kfinance --fix {{args}}
26
26
  python -m ruff --config pyproject.toml format kfinance {{args}}
27
+ nbqa mypy usage_examples.ipynb
27
28
 
28
29
  alias t := unit-test
29
30
  # Run unit tests. Use args for optional settings
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kensho-kfinance
3
- Version: 2.1.2
3
+ Version: 2.2.2
4
4
  Summary: Python CLI for kFinance
5
5
  Author-email: Luke Brown <luke.brown@kensho.com>, Michelle Keoy <michelle.keoy@kensho.com>, Keith Page <keith.page@kensho.com>, Matthew Rosen <matthew.rosen@kensho.com>, Nick Roshdieh <nick.roshdieh@kensho.com>
6
6
  Project-URL: source, https://github.com/kensho-technologies/kfinance
@@ -28,7 +28,11 @@ Requires-Dist: requests<3,>=2.22.0
28
28
  Requires-Dist: urllib3>=1.21.1
29
29
  Provides-Extra: dev
30
30
  Requires-Dist: coverage<8,>=7.6.10; extra == "dev"
31
+ Requires-Dist: ipykernel<7,>=6.29; extra == "dev"
31
32
  Requires-Dist: mypy<2,>=1.15.0; extra == "dev"
33
+ Requires-Dist: nbconvert<8,>=7.16; extra == "dev"
34
+ Requires-Dist: nbformat<6,>5.10; extra == "dev"
35
+ Requires-Dist: nbqa<2,>1.9; extra == "dev"
32
36
  Requires-Dist: pytest<7,>=6.1.2; extra == "dev"
33
37
  Requires-Dist: pytest-cov<7,>=6.0.0; extra == "dev"
34
38
  Requires-Dist: requests_mock<2,>=1.12; extra == "dev"
@@ -57,6 +61,8 @@ To receive access, please email [S&P Global Market Intelligence](market.intellig
57
61
 
58
62
  Once access is obtained, get started using the [Authentication Guide](https://docs.kensho.com/llmreadyapi/kf-authentication) and [Usage Guide](https://docs.kensho.com/llmreadyapi/usage).
59
63
 
64
+ We also provide an [interactive notebook](usage_examples.ipynb) that demonstrates some usage examples.
65
+
60
66
  # Versioning
61
67
  The kFinance uses semantic versioning (major, minor, patch).
62
68
  To bump the version, add a new entry in [CHANGELOG.md](kfinance%2FCHANGELOG.md).
@@ -9,6 +9,7 @@ README.md
9
9
  justfile
10
10
  pyproject.toml
11
11
  setup.py
12
+ usage_examples.ipynb
12
13
  .github/workflows/ci-lint.yml
13
14
  .github/workflows/ci-test.yml
14
15
  .github/workflows/python-publish.yml
@@ -20,6 +21,7 @@ docs/requirements.txt
20
21
  docs/tool_calling.rst
21
22
  docs/templates/apidoc/package.rst_t
22
23
  docs/templates/apidoc/toc.rst_t
24
+ images/colab_logo_32px.png
23
25
  kensho_kfinance.egg-info/PKG-INFO
24
26
  kensho_kfinance.egg-info/SOURCES.txt
25
27
  kensho_kfinance.egg-info/dependency_links.txt
@@ -40,6 +42,7 @@ kfinance/tests/__init__.py
40
42
  kfinance/tests/conftest.py
41
43
  kfinance/tests/test_batch_requests.py
42
44
  kfinance/tests/test_client.py
45
+ kfinance/tests/test_example_notebook.py
43
46
  kfinance/tests/test_fetch.py
44
47
  kfinance/tests/test_group_objects.py
45
48
  kfinance/tests/test_objects.py
@@ -48,7 +51,6 @@ kfinance/tool_calling/README.md
48
51
  kfinance/tool_calling/__init__.py
49
52
  kfinance/tool_calling/get_business_relationship_from_identifier.py
50
53
  kfinance/tool_calling/get_capitalization_from_identifier.py
51
- kfinance/tool_calling/get_company_id_from_identifier.py
52
54
  kfinance/tool_calling/get_cusip_from_ticker.py
53
55
  kfinance/tool_calling/get_earnings_call_datetimes_from_identifier.py
54
56
  kfinance/tool_calling/get_financial_line_item_from_identifier.py
@@ -59,8 +61,7 @@ kfinance/tool_calling/get_isin_from_ticker.py
59
61
  kfinance/tool_calling/get_latest.py
60
62
  kfinance/tool_calling/get_n_quarters_ago.py
61
63
  kfinance/tool_calling/get_prices_from_identifier.py
62
- kfinance/tool_calling/get_security_id_from_identifier.py
63
- kfinance/tool_calling/get_trading_item_id_from_identifier.py
64
+ kfinance/tool_calling/resolve_identifier.py
64
65
  kfinance/tool_calling/shared_models.py
65
66
  scripts/copyright_line_check.sh
66
67
  scripts/lint.sh
@@ -15,7 +15,11 @@ urllib3>=1.21.1
15
15
 
16
16
  [dev]
17
17
  coverage<8,>=7.6.10
18
+ ipykernel<7,>=6.29
18
19
  mypy<2,>=1.15.0
20
+ nbconvert<8,>=7.16
21
+ nbformat<6,>5.10
22
+ nbqa<2,>1.9
19
23
  pytest<7,>=6.1.2
20
24
  pytest-cov<7,>=6.0.0
21
25
  requests_mock<2,>=1.12
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## v2.2.2
4
+ - Add segments
5
+
6
+ ## v2.2.1
7
+ - Make number of employees optional to reflect backend changes
8
+
9
+ ## v2.2.0
10
+ - Replace get company id, get security id, get trading item id tools with resolve identifier tool
11
+
3
12
  ## v2.1.2
4
13
  - Allow batch executor to handle multiple requests
5
14
 
@@ -1,4 +1,4 @@
1
- from concurrent.futures import ThreadPoolExecutor
1
+ from concurrent.futures import Future
2
2
  import functools
3
3
  from functools import cached_property
4
4
  import threading
@@ -55,36 +55,26 @@ def add_methods_of_singular_class_to_iterable_class(singular_cls: Type[T]) -> Ca
55
55
  instances of [singular_cls].
56
56
  """
57
57
 
58
- def process_in_thread_pool(
59
- executor: ThreadPoolExecutor, method: Callable, obj: T, *args: Any, **kwargs: Any
60
- ) -> Any:
61
- with throttle:
62
- future = executor.submit(method, obj, *args, **kwargs)
63
- try:
64
- return future.result()
65
- except HTTPError as http_err:
66
- error_code = http_err.response.status_code
67
- if error_code == 404:
68
- return None
69
- else:
70
- raise http_err
71
-
72
58
  def process_in_batch(
73
59
  method: Callable, self: IterableKfinanceClass, *args: Any, **kwargs: Any
74
60
  ) -> dict:
75
- kfinance_api_client = self.kfinance_api_client
76
- with kfinance_api_client.batch_request_header(batch_size=len(self)):
77
- results = dict(
78
- zip(
79
- self,
80
- [
81
- process_in_thread_pool(
82
- kfinance_api_client.thread_pool, method, obj, *args, **kwargs
83
- )
84
- for obj in self
85
- ],
61
+ with self.kfinance_api_client.batch_request_header(batch_size=len(self)):
62
+ futures = []
63
+ for obj in self:
64
+ # Acquire throttle before submitting the task
65
+ throttle.acquire()
66
+ future = self.kfinance_api_client.thread_pool.submit(
67
+ method, obj, *args, **kwargs
86
68
  )
87
- )
69
+ # On success or failure, release the throttle.
70
+ # This releases the throttle before the
71
+ # `resolve_future_with_error_handling` call.
72
+ future.add_done_callback(lambda f: throttle.release())
73
+ futures.append(future)
74
+
75
+ results = {}
76
+ for obj, future in zip(self, futures):
77
+ results[obj] = resolve_future_with_error_handling(future)
88
78
 
89
79
  return results
90
80
 
@@ -135,3 +125,18 @@ def add_methods_of_singular_class_to_iterable_class(singular_cls: Type[T]) -> Ca
135
125
  return iterable_cls
136
126
 
137
127
  return decorator
128
+
129
+
130
+ def resolve_future_with_error_handling(future: Future) -> Any:
131
+ """Return the result of a future with error handling for non-200 status codes.
132
+
133
+ If request returned a 404, return None. Otherwise, raise the error.
134
+ """
135
+ try:
136
+ return future.result()
137
+ except HTTPError as http_err:
138
+ error_code = http_err.response.status_code
139
+ if error_code == 404:
140
+ return None
141
+ else:
142
+ raise http_err
@@ -62,6 +62,13 @@ class StatementType(StrEnum):
62
62
  cf = "cashflow"
63
63
 
64
64
 
65
+ class SegmentType(StrEnum):
66
+ """The type of segment"""
67
+
68
+ business = "business"
69
+ geographic = "geographic"
70
+
71
+
65
72
  class BusinessRelationshipType(StrEnum):
66
73
  """The type of business relationship"""
67
74
 
@@ -15,6 +15,7 @@ from .constants import (
15
15
  Periodicity,
16
16
  PeriodType,
17
17
  Permission,
18
+ SegmentType,
18
19
  )
19
20
 
20
21
 
@@ -305,6 +306,27 @@ class KFinanceApiClient:
305
306
  )
306
307
  return self.fetch(url)
307
308
 
309
+ def fetch_segments(
310
+ self,
311
+ company_id: int,
312
+ segment_type: SegmentType,
313
+ period_type: Optional[PeriodType] = None,
314
+ start_year: Optional[int] = None,
315
+ end_year: Optional[int] = None,
316
+ start_quarter: Optional[int] = None,
317
+ end_quarter: Optional[int] = None,
318
+ ) -> dict:
319
+ """Get a specified segment type for a specified duration."""
320
+ url = (
321
+ f"{self.url_base}segments/{company_id}/{segment_type}/"
322
+ f"{period_type if period_type else 'none'}/"
323
+ f"{start_year if start_year is not None else 'none'}/"
324
+ f"{end_year if end_year is not None else 'none'}/"
325
+ f"{start_quarter if start_quarter is not None else 'none'}/"
326
+ f"{end_quarter if end_quarter is not None else 'none'}"
327
+ )
328
+ return self.fetch(url)
329
+
308
330
  def fetch_price_chart(
309
331
  self,
310
332
  trading_item_id: int,
@@ -262,7 +262,7 @@ class Company(CompanyFunctionsMetaClass):
262
262
  def info(self) -> dict:
263
263
  """Get the company info
264
264
 
265
- :return: a dict with containing: name, status, type, simple industry, number of employees, founding date, webpage, address, city, zip code, state, country, & iso_country
265
+ :return: a dict with containing: name, status, type, simple industry, number of employees (if available), founding date, webpage, address, city, zip code, state, country, & iso_country
266
266
  :rtype: dict
267
267
  """
268
268
  return self.kfinance_api_client.fetch_info(self.company_id)
@@ -304,11 +304,11 @@ class Company(CompanyFunctionsMetaClass):
304
304
  return self.info["simple_industry"]
305
305
 
306
306
  @property
307
- def number_of_employees(self) -> str:
308
- """Get the number of employees the company has
307
+ def number_of_employees(self) -> str | None:
308
+ """Get the number of employees the company has (if available)
309
309
 
310
310
  :return: how many employees the company has
311
- :rtype: str
311
+ :rtype: str | None
312
312
  """
313
313
  return self.info["number_of_employees"]
314
314
 
@@ -537,11 +537,32 @@ class Ticker(DelegatedCompanyFunctionsMetaClass):
537
537
 
538
538
  @property
539
539
  def id_triple(self) -> IdentificationTriple:
540
- """Returns a unique identifier triple for the Ticker object."""
540
+ """Returns a unique identification triple for the Ticker object.
541
+
542
+ :return: an identification triple consisting of company_id, security_id, and trading_item_id
543
+ :rtype: IdentificationTriple
544
+ """
545
+
546
+ if self._company_id is None or self._security_id is None or self._trading_item_id is None:
547
+ if self._identifier is None:
548
+ raise RuntimeError(
549
+ "Fetching the id triple of a Ticker requires an identifier "
550
+ "(ticker, CUSIP, or ISIN)."
551
+ )
552
+ id_triple = self.kfinance_api_client.fetch_id_triple(
553
+ identifier=self._identifier, exchange_code=self.exchange_code
554
+ )
555
+ self._company_id = id_triple["company_id"]
556
+ self._security_id = id_triple["security_id"]
557
+ self._trading_item_id = id_triple["trading_item_id"]
558
+ assert self._company_id
559
+ assert self._security_id
560
+ assert self._trading_item_id
561
+
541
562
  return IdentificationTriple(
542
- company_id=self.company_id,
543
- security_id=self.security_id,
544
- trading_item_id=self.trading_item_id,
563
+ company_id=self._company_id,
564
+ security_id=self._security_id,
565
+ trading_item_id=self._trading_item_id,
545
566
  )
546
567
 
547
568
  def __hash__(self) -> int:
@@ -570,79 +591,32 @@ class Ticker(DelegatedCompanyFunctionsMetaClass):
570
591
 
571
592
  return f"{type(self).__module__}.{type(self).__qualname__} of {', '.join(str_attributes)}"
572
593
 
573
- def set_identification_triple(self) -> None:
574
- """Get & set company_id, security_id, & trading_item_id for ticker with an exchange"""
575
- if self._identifier is None:
576
- raise RuntimeError(
577
- "Ticker.set_identification_triple was called with a identifier set to None"
578
- )
579
- else:
580
- id_triple = self.kfinance_api_client.fetch_id_triple(
581
- self._identifier, self.exchange_code
582
- )
583
- self.company_id = id_triple["company_id"]
584
- self.security_id = id_triple["security_id"]
585
- self.trading_item_id = id_triple["trading_item_id"]
586
-
587
- def set_company_id(self) -> int:
588
- """Set the company id for the object
589
-
590
- :return: the CIQ company id
591
- :rtype: int
592
- """
593
- self.set_identification_triple()
594
- return self.company_id
595
-
596
- def set_security_id(self) -> int:
597
- """Set the security id for the object
598
-
599
- :return: the CIQ security id
600
- :rtype: int
601
- """
602
- self.set_identification_triple()
603
- return self.security_id
604
-
605
- def set_trading_item_id(self) -> int:
606
- """Set the trading item id for the object
607
-
608
- :return: the CIQ trading item id
609
- :rtype: int
610
- """
611
- self.set_identification_triple()
612
- return self.trading_item_id
613
-
614
- @cached_property
594
+ @property
615
595
  def company_id(self) -> int:
616
596
  """Get the company id for the object
617
597
 
618
598
  :return: the CIQ company id
619
599
  :rtype: int
620
600
  """
621
- if self._company_id:
622
- return self._company_id
623
- return self.set_company_id()
601
+ return self.id_triple.company_id
624
602
 
625
- @cached_property
603
+ @property
626
604
  def security_id(self) -> int:
627
605
  """Get the CIQ security id for the object
628
606
 
629
607
  :return: the CIQ security id
630
608
  :rtype: int
631
609
  """
632
- if self._security_id:
633
- return self._security_id
634
- return self.set_security_id()
610
+ return self.id_triple.security_id
635
611
 
636
- @cached_property
612
+ @property
637
613
  def trading_item_id(self) -> int:
638
614
  """Get the CIQ trading item id for the object
639
615
 
640
616
  :return: the CIQ trading item id
641
617
  :rtype: int
642
618
  """
643
- if self._trading_item_id:
644
- return self._trading_item_id
645
- return self.set_trading_item_id()
619
+ return self.id_triple.trading_item_id
646
620
 
647
621
  @cached_property
648
622
  def primary_security(self) -> Security:
@@ -711,7 +685,7 @@ class Ticker(DelegatedCompanyFunctionsMetaClass):
711
685
  def info(self) -> dict:
712
686
  """Get the company info for the ticker
713
687
 
714
- :return: a dict with containing: name, status, type, simple industry, number of employees, founding date, webpage, address, city, zip code, state, country, & iso_country
688
+ :return: a dict with containing: name, status, type, simple industry, number of employees (if available), founding date, webpage, address, city, zip code, state, country, & iso_country
715
689
  :rtype: dict
716
690
  """
717
691
  return self.company.info
@@ -753,11 +727,11 @@ class Ticker(DelegatedCompanyFunctionsMetaClass):
753
727
  return self.company.simple_industry
754
728
 
755
729
  @property
756
- def number_of_employees(self) -> str:
757
- """Get the number of employees the company has
730
+ def number_of_employees(self) -> str | None:
731
+ """Get the number of employees the company has (if available)
758
732
 
759
733
  :return: how many employees the company has
760
- :rtype: str
734
+ :rtype: str | None
761
735
  """
762
736
  return self.company.number_of_employees
763
737
 
@@ -7,7 +7,7 @@ from cachetools import LRUCache, cached
7
7
  import numpy as np
8
8
  import pandas as pd
9
9
 
10
- from .constants import LINE_ITEMS, BusinessRelationshipType, PeriodType
10
+ from .constants import LINE_ITEMS, BusinessRelationshipType, PeriodType, SegmentType
11
11
  from .fetch import KFinanceApiClient
12
12
 
13
13
 
@@ -304,6 +304,114 @@ class CompanyFunctionsMetaClass:
304
304
  )
305
305
  return df.set_index("date")[[column_to_extract]].apply(pd.to_numeric).replace(np.nan, None)
306
306
 
307
+ def _segments(
308
+ self,
309
+ segment_type: SegmentType,
310
+ period_type: Optional[PeriodType] = None,
311
+ start_year: Optional[int] = None,
312
+ end_year: Optional[int] = None,
313
+ start_quarter: Optional[int] = None,
314
+ end_quarter: Optional[int] = None,
315
+ ) -> pd.DataFrame:
316
+ """Get the company's segments"""
317
+ try:
318
+ self.validate_inputs(
319
+ start_year=start_year,
320
+ end_year=end_year,
321
+ start_quarter=start_quarter,
322
+ end_quarter=end_quarter,
323
+ )
324
+ except ValueError:
325
+ return pd.DataFrame()
326
+
327
+ results = self.kfinance_api_client.fetch_segments(
328
+ company_id=self.company_id,
329
+ segment_type=segment_type,
330
+ period_type=period_type,
331
+ start_year=start_year,
332
+ end_year=end_year,
333
+ start_quarter=start_quarter,
334
+ end_quarter=end_quarter,
335
+ )["segments"]
336
+
337
+ period_name = (
338
+ "Year" if (period_type == PeriodType.annual or period_type is None) else "Period"
339
+ )
340
+
341
+ # flatten the nested dictionary and return as a DataFrame
342
+ rows = []
343
+ for period, segments in results.items():
344
+ for segment_name, line_items in segments.items():
345
+ for line_item, value in line_items.items():
346
+ rows.append([period, segment_name, line_item, value])
347
+ return pd.DataFrame(
348
+ rows, columns=[period_name, "Segment Name", "Line Item", "Value"]
349
+ ).replace(np.nan, None)
350
+
351
+ def business_segments(
352
+ self,
353
+ period_type: Optional[PeriodType] = None,
354
+ start_year: Optional[int] = None,
355
+ end_year: Optional[int] = None,
356
+ start_quarter: Optional[int] = None,
357
+ end_quarter: Optional[int] = None,
358
+ ) -> pd.DataFrame:
359
+ """Retrieves the templated line of business segments for a given period_type, start_year, start_quarter, end_year and end_quarter.
360
+
361
+ :param period_type: The period_type requested for. Can be “annual”, “quarterly”, "ytd". Defaults to “annual” when start_quarter and end_quarter are None.
362
+ :type start_year: PeriodType, optional
363
+ :param start_year: The starting calendar year, defaults to None
364
+ :type start_year: int, optional
365
+ :param end_year: The ending calendar year, defaults to None
366
+ :type end_year: int, optional
367
+ :param start_quarter: The starting calendar quarter, defaults to None
368
+ :type start_quarter: int, optional
369
+ :param end_quarter: The ending calendar quarter, defaults to None
370
+ :type end_quarter: int, optional
371
+ :return: A DataFrame with `Year`/`Period`, `Segment Name`, `Line Item` and `Value` column.
372
+ :rtype: pd.DataFrame
373
+ """
374
+ return self._segments(
375
+ segment_type=SegmentType.business,
376
+ period_type=period_type,
377
+ start_year=start_year,
378
+ end_year=end_year,
379
+ start_quarter=start_quarter,
380
+ end_quarter=end_quarter,
381
+ )
382
+
383
+ def geographic_segments(
384
+ self,
385
+ period_type: Optional[PeriodType] = None,
386
+ start_year: Optional[int] = None,
387
+ end_year: Optional[int] = None,
388
+ start_quarter: Optional[int] = None,
389
+ end_quarter: Optional[int] = None,
390
+ ) -> pd.DataFrame:
391
+ """Retrieves the templated geographic segments for a given company for a given period_type, start_year, start_quarter, end_year and end_quarter.
392
+
393
+ :param period_type: The period_type requested for. Can be “annual”, “quarterly”, "ytd". Defaults to “annual” when start_quarter and end_quarter are None.
394
+ :type start_year: PeriodType, optional
395
+ :param start_year: The starting calendar year, defaults to None
396
+ :type start_year: int, optional
397
+ :param end_year: The ending calendar year, defaults to None
398
+ :type end_year: int, optional
399
+ :param start_quarter: The starting calendar quarter, defaults to None
400
+ :type start_quarter: int, optional
401
+ :param end_quarter: The ending calendar quarter, defaults to None
402
+ :type end_quarter: int, optional
403
+ :return: A DataFrame with `Year`/`Period`, `Segment Name`, `Line Item` and `Value` column.
404
+ :rtype: pd.DataFrame
405
+ """
406
+ return self._segments(
407
+ segment_type=SegmentType.geographic,
408
+ period_type=period_type,
409
+ start_year=start_year,
410
+ end_year=end_year,
411
+ start_quarter=start_quarter,
412
+ end_quarter=end_quarter,
413
+ )
414
+
307
415
 
308
416
  for line_item in LINE_ITEMS:
309
417
  line_item_name = line_item["name"]
@@ -1,7 +1,8 @@
1
1
  from concurrent.futures import ThreadPoolExecutor
2
+ import time
2
3
  from typing import Any, Dict
3
4
  from unittest import TestCase
4
- from unittest.mock import patch
5
+ from unittest.mock import PropertyMock, patch
5
6
 
6
7
  import numpy as np
7
8
  import pandas as pd
@@ -9,6 +10,7 @@ import pytest
9
10
  import requests
10
11
  import requests_mock
11
12
 
13
+ from kfinance.batch_request_handling import MAX_WORKERS_CAP
12
14
  from kfinance.fetch import KFinanceApiClient
13
15
  from kfinance.kfinance import Companies, Company, Ticker, TradingItems
14
16
 
@@ -260,3 +262,33 @@ class TestTradingItem(TestCase):
260
262
 
261
263
  expected_id_based_result = {1001: "Mock City A"}
262
264
  self.assertDictEqual(id_based_result, expected_id_based_result)
265
+
266
+ @patch.object(Company, "info", new_callable=PropertyMock)
267
+ def test_batch_requests_processed_in_parallel(self, mock_value: PropertyMock):
268
+ """
269
+ WHEN a batch request gets processed
270
+ THEN the requests are handled in parallel not sequentially.
271
+ """
272
+
273
+ sleep_duration = 0.05
274
+
275
+ def mock_info_with_sleep() -> dict[str, str]:
276
+ """Mock an info call with a short sleep"""
277
+ time.sleep(sleep_duration)
278
+ return {"city": "Cambridge"}
279
+
280
+ mock_value.side_effect = mock_info_with_sleep
281
+
282
+ # Create tasks up to the MAX_WORKERS_CAP (max number of parallel tasks)
283
+ companies = Companies(
284
+ self.kfinance_api_client_with_thread_pool, [i for i in range(MAX_WORKERS_CAP)]
285
+ )
286
+
287
+ start = time.perf_counter()
288
+ result = companies.city
289
+ end = time.perf_counter()
290
+ assert len(result) == MAX_WORKERS_CAP
291
+ # Check that the requests run faster than sequential.
292
+ # In practice, the requests should take barely more than the `sleep_duration` but timing
293
+ # based tests can be flaky, especially in CI.
294
+ assert end - start < MAX_WORKERS_CAP * sleep_duration