usaspending-orm 0.6.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.
Files changed (71) hide show
  1. usaspending/__init__.py +144 -0
  2. usaspending/cli/__init__.py +2 -0
  3. usaspending/cli/download_award.py +113 -0
  4. usaspending/client.py +550 -0
  5. usaspending/config.py +119 -0
  6. usaspending/download/__init__.py +8 -0
  7. usaspending/download/job.py +219 -0
  8. usaspending/download/manager.py +140 -0
  9. usaspending/exceptions.py +71 -0
  10. usaspending/logging_config.py +310 -0
  11. usaspending/models/__init__.py +86 -0
  12. usaspending/models/agency.py +631 -0
  13. usaspending/models/award.py +933 -0
  14. usaspending/models/award_factory.py +72 -0
  15. usaspending/models/award_types.py +114 -0
  16. usaspending/models/base_model.py +214 -0
  17. usaspending/models/contract.py +147 -0
  18. usaspending/models/district_spending.py +70 -0
  19. usaspending/models/download.py +74 -0
  20. usaspending/models/funding.py +182 -0
  21. usaspending/models/grant.py +147 -0
  22. usaspending/models/idv.py +165 -0
  23. usaspending/models/lazy_record.py +82 -0
  24. usaspending/models/loan.py +85 -0
  25. usaspending/models/location.py +125 -0
  26. usaspending/models/period_of_performance.py +43 -0
  27. usaspending/models/recipient.py +204 -0
  28. usaspending/models/recipient_business_categories.py +364 -0
  29. usaspending/models/recipient_spending.py +58 -0
  30. usaspending/models/spending.py +70 -0
  31. usaspending/models/state_spending.py +43 -0
  32. usaspending/models/subaward.py +270 -0
  33. usaspending/models/subtier_agency.py +98 -0
  34. usaspending/models/transaction.py +89 -0
  35. usaspending/queries/__init__.py +87 -0
  36. usaspending/queries/agencies_search.py +196 -0
  37. usaspending/queries/agency_award_summary.py +134 -0
  38. usaspending/queries/agency_query.py +102 -0
  39. usaspending/queries/award_query.py +40 -0
  40. usaspending/queries/awarding_agencies_search.py +16 -0
  41. usaspending/queries/awards_search.py +602 -0
  42. usaspending/queries/filters.py +437 -0
  43. usaspending/queries/funding_agencies_search.py +20 -0
  44. usaspending/queries/funding_search.py +180 -0
  45. usaspending/queries/query_builder.py +1430 -0
  46. usaspending/queries/recipient_query.py +66 -0
  47. usaspending/queries/recipients_search.py +167 -0
  48. usaspending/queries/single_resource_base.py +83 -0
  49. usaspending/queries/spending_search.py +261 -0
  50. usaspending/queries/sub_agency_query.py +177 -0
  51. usaspending/queries/subawards_search.py +196 -0
  52. usaspending/queries/transactions_search.py +213 -0
  53. usaspending/resources/__init__.py +17 -0
  54. usaspending/resources/agency_resource.py +105 -0
  55. usaspending/resources/award_resource.py +119 -0
  56. usaspending/resources/base_resource.py +31 -0
  57. usaspending/resources/download_resource.py +102 -0
  58. usaspending/resources/funding_resource.py +41 -0
  59. usaspending/resources/recipients_resource.py +104 -0
  60. usaspending/resources/spending_resource.py +45 -0
  61. usaspending/resources/subawards_resource.py +68 -0
  62. usaspending/resources/transactions_resource.py +39 -0
  63. usaspending/utils/__init__.py +6 -0
  64. usaspending/utils/formatter.py +550 -0
  65. usaspending/utils/rate_limit.py +135 -0
  66. usaspending/utils/retry.py +257 -0
  67. usaspending/utils/special_cases.yaml +155 -0
  68. usaspending_orm-0.6.0.dist-info/LICENSE +18 -0
  69. usaspending_orm-0.6.0.dist-info/METADATA +324 -0
  70. usaspending_orm-0.6.0.dist-info/RECORD +71 -0
  71. usaspending_orm-0.6.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,270 @@
1
+ from __future__ import annotations
2
+ from typing import Dict, Any, Optional, TYPE_CHECKING
3
+ from datetime import date
4
+ from functools import cached_property
5
+ from decimal import Decimal
6
+ from ..utils.formatter import (
7
+ contracts_titlecase,
8
+ smart_sentence_case,
9
+ to_decimal,
10
+ to_date,
11
+ )
12
+ from .base_model import ClientAwareModel
13
+ from .recipient import Recipient
14
+ from .location import Location
15
+ from .award import Award
16
+
17
+ if TYPE_CHECKING:
18
+ from ..client import USASpendingClient
19
+
20
+
21
+ class SubAward(ClientAwareModel):
22
+ """Model representing a subaward from USASpending data.
23
+
24
+ Subawards are secondary awards issued by prime recipients of federal contracts
25
+ or grants to other entities (subrecipients) to carry out part of the federal
26
+ program or project. They represent the flow of federal funds from prime
27
+ recipients to subrecipients.
28
+
29
+ Key characteristics:
30
+ - Issued by prime recipients, not directly by federal agencies
31
+ - Subject to federal regulations and oversight requirements
32
+ - Must be reported when exceeding $30,000 (per FFATA requirements)
33
+ - Include both contract subawards (subcontracts) and grant subawards
34
+
35
+ Subawards enable prime recipients to delegate portions of work while
36
+ maintaining overall responsibility for the federal award's success.
37
+ They extend the reach of federal funding through multiple tiers of
38
+ organizations.
39
+
40
+ Example:
41
+ >>> # Find subawards for a specific prime award
42
+ >>> subawards = client.subawards.search()
43
+ ... .for_prime_award_piid("80NSSC21C0123")
44
+ ... .limit(10)
45
+ >>> for subaward in subawards:
46
+ ... print(f"{subaward.sub_awardee_name}: ${subaward.sub_award_amount:,.2f}")
47
+ """
48
+
49
+ def __init__(
50
+ self, data: Dict[str, Any], client: Optional[USASpendingClient] = None
51
+ ):
52
+ super().__init__(data, client)
53
+
54
+ # Contract Subaward fields
55
+ CONTRACT_SUBAWARD_FIELDS = [
56
+ "Awarding Agency",
57
+ "Awarding Sub Agency",
58
+ "NAICS",
59
+ "Prime Award ID",
60
+ "prime_award_recipient_id",
61
+ "Prime Award Recipient UEI",
62
+ "Prime Recipient Name",
63
+ "PSC",
64
+ "Sub-Award Amount",
65
+ "Sub-Award Date",
66
+ "Sub-Award Description",
67
+ "Sub-Award ID",
68
+ "Sub-Award Primary Place of Performance",
69
+ "sub_award_recipient_id",
70
+ "Sub-Award Type",
71
+ "Sub-Awardee Name",
72
+ "Sub-Recipient Location",
73
+ "Sub-Recipient UEI",
74
+ "prime_award_generated_internal_id",
75
+ "prime_award_internal_id",
76
+ "internal_id",
77
+ "subaward_description_sorted",
78
+ ]
79
+
80
+ # Grant Subaward fields
81
+ GRANT_SUBAWARD_FIELDS = [
82
+ "Assistance Listing",
83
+ "Awarding Agency",
84
+ "Awarding Sub Agency",
85
+ "Prime Award ID",
86
+ "prime_award_recipient_id",
87
+ "Prime Award Recipient UEI",
88
+ "Prime Recipient Name",
89
+ "Sub-Award Amount",
90
+ "Sub-Award Date",
91
+ "Sub-Award Description",
92
+ "Sub-Award ID",
93
+ "Sub-Award Primary Place of Performance",
94
+ "sub_award_recipient_id",
95
+ "Sub-Award Type",
96
+ "Sub-Awardee Name",
97
+ "Sub-Recipient Location",
98
+ "Sub-Recipient UEI",
99
+ "prime_award_generated_internal_id",
100
+ "prime_award_internal_id",
101
+ "internal_id",
102
+ "subaward_description_sorted",
103
+ ]
104
+
105
+ @cached_property
106
+ def place_of_performance(self) -> Optional[Location]:
107
+ """Place of performance details for the subaward."""
108
+ pop_data = self.raw.get("Sub-Award Primary Place of Performance")
109
+ if pop_data:
110
+ return Location(pop_data)
111
+ else:
112
+ return None
113
+
114
+ @cached_property
115
+ def recipient(self) -> Optional[Recipient]:
116
+ """Sub-award recipient and location."""
117
+ recipient = Recipient(
118
+ {
119
+ "recipient_name": self.get_value(["Sub-Awardee Name"]),
120
+ "recipient_unique_id": self.get_value(["sub_award_recipient_id"]),
121
+ "recipient_uei": self.get_value(["Sub-Recipient UEI"]),
122
+ },
123
+ client=self._client,
124
+ )
125
+
126
+ # Add location if available to avoid separate API call
127
+ if isinstance(self.get_value(["Sub-Recipient Location"]), dict):
128
+ location_data = self._data.get("Sub-Recipient Location")
129
+ recipient_location = Location(location_data) if location_data else None
130
+ recipient.location = recipient_location
131
+
132
+ return recipient
133
+
134
+ @cached_property
135
+ def parent_award(self) -> Optional[Award]:
136
+ if self.prime_award_generated_internal_id:
137
+ return Award(
138
+ {"generated_unique_award_id": self.prime_award_generated_internal_id},
139
+ client=self._client,
140
+ )
141
+ else:
142
+ return None
143
+
144
+ @property
145
+ def id(self) -> Optional[str]:
146
+ """Internal subaward identifier."""
147
+ return self.raw.get("internal_id")
148
+
149
+ @property
150
+ def sub_award_id(self) -> Optional[str]:
151
+ """Subaward identifier."""
152
+ return self.raw.get("Sub-Award ID")
153
+
154
+ @property
155
+ def sub_award_type(self) -> Optional[str]:
156
+ """Type of subaward (e.g., sub-contract, sub-grant)."""
157
+ return self.raw.get("Sub-Award Type")
158
+
159
+ @property
160
+ def sub_awardee_name(self) -> Optional[str]:
161
+ """Name of the subaward recipient."""
162
+ name = self.raw.get("Sub-Awardee Name")
163
+ return contracts_titlecase(name) if name else None
164
+
165
+ @property
166
+ def sub_award_date(self) -> Optional[date]:
167
+ """Date the subaward was issued."""
168
+ return to_date(self.raw.get("Sub-Award Date"))
169
+
170
+ @property
171
+ def sub_award_amount(self) -> Optional[Decimal]:
172
+ """Amount of the subaward."""
173
+ return to_decimal(self.raw.get("Sub-Award Amount"))
174
+
175
+ @property
176
+ def awarding_agency(self) -> Optional[str]:
177
+ """Name of the awarding agency."""
178
+ return self.raw.get("Awarding Agency")
179
+
180
+ @property
181
+ def awarding_sub_agency(self) -> Optional[str]:
182
+ """Name of the awarding sub-agency."""
183
+ return self.raw.get("Awarding Sub Agency")
184
+
185
+ @property
186
+ def prime_award_id(self) -> Optional[str]:
187
+ """Prime award identifier (PIID/FAIN/URI)."""
188
+ return self.raw.get("Prime Award ID")
189
+
190
+ @property
191
+ def prime_recipient_name(self) -> Optional[str]:
192
+ """Name of the prime award recipient."""
193
+ name = self.raw.get("Prime Recipient Name")
194
+ return contracts_titlecase(name) if name else None
195
+
196
+ @property
197
+ def prime_award_recipient_id(self) -> Optional[str]:
198
+ """Prime award recipient identifier."""
199
+ return self.raw.get("prime_award_recipient_id")
200
+
201
+ @property
202
+ def sub_award_description(self) -> Optional[str]:
203
+ """Description of the subaward."""
204
+ desc = self.raw.get("Sub-Award Description")
205
+ return smart_sentence_case(desc) if desc else None
206
+
207
+ @property
208
+ def subaward_description_sorted(self) -> Optional[str]:
209
+ """Sorted version of the subaward description for API internal use."""
210
+ return self.raw.get("subaward_description_sorted")
211
+
212
+ @property
213
+ def sub_recipient_uei(self) -> Optional[str]:
214
+ """Sub-recipient Unique Entity Identifier."""
215
+ return self.raw.get("Sub-Recipient UEI")
216
+
217
+ @property
218
+ def prime_award_recipient_uei(self) -> Optional[str]:
219
+ """Prime award recipient Unique Entity Identifier."""
220
+ return self.raw.get("Prime Award Recipient UEI")
221
+
222
+ @property
223
+ def prime_award_generated_internal_id(self) -> Optional[str]:
224
+ """USASpending-generated unique identifier for the prime award."""
225
+ return self.raw.get("prime_award_generated_internal_id")
226
+
227
+ @property
228
+ def prime_award_internal_id(self) -> Optional[int]:
229
+ """Internal database ID for the prime award."""
230
+ val = self.raw.get("prime_award_internal_id")
231
+ return int(val) if val is not None else None
232
+
233
+ @property
234
+ def naics(self) -> Optional[str]:
235
+ """NAICS code for contract subawards."""
236
+ return self.raw.get("NAICS")
237
+
238
+ @property
239
+ def psc(self) -> Optional[str]:
240
+ """Product Service Code for contract subawards."""
241
+ return self.raw.get("PSC")
242
+
243
+ @property
244
+ def assistance_listing(self) -> Optional[str]:
245
+ """Assistance listing for grant subawards."""
246
+ return self.raw.get("Assistance Listing")
247
+
248
+ def __repr__(self) -> str:
249
+ """String representation of SubAward."""
250
+ return f"<SubAward {self.sub_award_id or '?'} {self.sub_awardee_name or '?'} ${self.sub_award_amount or 0:,.2f}>"
251
+
252
+ @property
253
+ def name(self) -> Optional[str]:
254
+ """Alias for sub_awardee_name."""
255
+ return self.sub_awardee_name
256
+
257
+ @property
258
+ def amount(self) -> Optional[float]:
259
+ """Alias for sub_award_amount."""
260
+ return self.sub_award_amount
261
+
262
+ @property
263
+ def description(self) -> Optional[str]:
264
+ """Alias for sub_award_description."""
265
+ return self.sub_award_description
266
+
267
+ @property
268
+ def award_date(self) -> Optional[date]:
269
+ """Alias for sub_award_date."""
270
+ return self.sub_award_date
@@ -0,0 +1,98 @@
1
+ """SubTier Agency model for USASpending sub-agency data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional, List, TYPE_CHECKING, Dict, Any
6
+ from decimal import Decimal
7
+ from ..utils.formatter import to_decimal, to_int, contracts_titlecase
8
+ from .base_model import BaseModel
9
+
10
+ if TYPE_CHECKING:
11
+ from ..client import USASpendingClient
12
+
13
+
14
+ class SubTierAgency(BaseModel):
15
+ """Rich wrapper around a USAspending subtier agency record.
16
+
17
+ This model represents a subtier agency with its essential properties,
18
+ including nested office information.
19
+ """
20
+
21
+ def __init__(
22
+ self, data: Dict[str, Any], client: Optional["USASpendingClient"] = None
23
+ ):
24
+ """Initialize SubTierAgency model.
25
+
26
+ Args:
27
+ data: Raw sub-agency data from API
28
+ client: USASpendingClient client instance
29
+ """
30
+ # Check if this data includes office_agency_name (from award context)
31
+ office_agency_name = data.get("office_agency_name")
32
+ if office_agency_name and "children" not in data:
33
+ # Create a synthetic child office from office_agency_name
34
+ office_child = {"name": contracts_titlecase(office_agency_name)}
35
+ # Create a copy of data with the office child
36
+ data = data.copy()
37
+ data["children"] = [office_child]
38
+
39
+ super().__init__(data)
40
+ self._client = client
41
+
42
+ @property
43
+ def name(self) -> Optional[str]:
44
+ """Name of the subtier agency."""
45
+ return contracts_titlecase(self.get_value("name"))
46
+
47
+ @property
48
+ def code(self) -> Optional[str]:
49
+ """Code of the subtier agency."""
50
+ return self.get_value("code")
51
+
52
+ @property
53
+ def abbreviation(self) -> Optional[str]:
54
+ """Abbreviation of the subtier agency."""
55
+ return self.get_value("abbreviation")
56
+
57
+ @property
58
+ def total_obligations(self) -> Optional[Decimal]:
59
+ """Total obligations for this subtier agency."""
60
+ obligations = self.get_value("total_obligations")
61
+ return to_decimal(obligations)
62
+
63
+ @property
64
+ def transaction_count(self) -> Optional[int]:
65
+ """Number of transactions for this subtier agency."""
66
+ count = self.get_value("transaction_count")
67
+ return to_int(count)
68
+
69
+ @property
70
+ def new_award_count(self) -> Optional[int]:
71
+ """Number of new awards for this subtier agency."""
72
+ count = self.get_value("new_award_count")
73
+ return to_int(count)
74
+
75
+ @property
76
+ def offices(self) -> List["SubTierAgency"]:
77
+ """List of offices under this subtier agency.
78
+
79
+ Returns:
80
+ List of SubTierAgency instances representing offices
81
+ """
82
+ children_data = self.get_value("children", default=[])
83
+ if not isinstance(children_data, list):
84
+ return []
85
+
86
+ offices = []
87
+ for office_data in children_data:
88
+ if isinstance(office_data, dict):
89
+ office = SubTierAgency(office_data, self._client)
90
+ offices.append(office)
91
+
92
+ return offices
93
+
94
+ def __repr__(self) -> str:
95
+ """String representation of SubTierAgency."""
96
+ name = self.name or "?"
97
+ code = self.code or "?"
98
+ return f"<SubTierAgency {code}: {name}>"
@@ -0,0 +1,89 @@
1
+ from .base_model import BaseModel
2
+ from dataclasses import dataclass
3
+ from datetime import date
4
+ from typing import Dict, Any, Optional
5
+ from decimal import Decimal
6
+ from ..utils.formatter import to_decimal, smart_sentence_case, to_date
7
+
8
+
9
+ @dataclass
10
+ class Transaction(BaseModel):
11
+ def __init__(self, data: Dict[str, Any]):
12
+ super().__init__(data)
13
+
14
+ @property
15
+ def amt(self) -> Optional[Decimal]:
16
+ """Get the transaction amount."""
17
+ amt = (
18
+ self.federal_action_obligation
19
+ or self.face_value_loan_guarantee
20
+ or self.original_loan_subsidy_cost
21
+ or None
22
+ )
23
+
24
+ return to_decimal(amt)
25
+
26
+ @property
27
+ def id(self) -> Optional[str]:
28
+ return self.raw.get("id")
29
+
30
+ @property
31
+ def type(self) -> Optional[str]:
32
+ """
33
+ Return the transaction type from the underlying raw data.
34
+
35
+ Returns:
36
+ Optional[str]: The transaction type string, or None if not present.
37
+ """
38
+ return self.raw.get("type")
39
+
40
+ @property
41
+ def type_description(self) -> Optional[str]:
42
+ return self.raw.get("type_description")
43
+
44
+ @property
45
+ def action_date(self) -> Optional[date]:
46
+ """
47
+ Return the transaction's action date parsed as a date object.
48
+
49
+ Returns:
50
+ Optional[date]: A date representing the action date, or None
51
+ when no valid date is available.
52
+ """
53
+
54
+ return to_date(self.raw.get("action_date"))
55
+
56
+ @property
57
+ def action_type(self) -> Optional[str]:
58
+ return self.raw.get("action_type")
59
+
60
+ @property
61
+ def action_type_description(self) -> Optional[str]:
62
+ return self.raw.get("action_type_description")
63
+
64
+ @property
65
+ def modification_number(self) -> Optional[str]:
66
+ return self.raw.get("modification_number")
67
+
68
+ @property
69
+ def award_description(self) -> Optional[str]:
70
+ return smart_sentence_case(self.raw.get("description", ""))
71
+
72
+ @property
73
+ def federal_action_obligation(self) -> Optional[Decimal]:
74
+ return to_decimal(self.raw.get("federal_action_obligation"))
75
+
76
+ @property
77
+ def face_value_loan_guarantee(self) -> Optional[Decimal]:
78
+ return to_decimal(self.raw.get("face_value_loan_guarantee"))
79
+
80
+ @property
81
+ def original_loan_subsidy_cost(self) -> Optional[Decimal]:
82
+ return to_decimal(self.raw.get("original_loan_subsidy_cost"))
83
+
84
+ @property
85
+ def cfda_number(self) -> Optional[str]:
86
+ return self.raw.get("cfda_number")
87
+
88
+ def __repr__(self) -> str:
89
+ return f"<Txn {self.id or '?'} {str(self.action_date) or '?'} {self.amt}>"
@@ -0,0 +1,87 @@
1
+ """Query builders for USASpending API operations.
2
+
3
+ This module provides query builders for constructing complex API requests
4
+ with filtering, pagination, and result transformation capabilities.
5
+
6
+ Base Classes:
7
+ QueryBuilder: Abstract base class for chainable query operations
8
+
9
+ Award Queries:
10
+ AwardQuery: Single award retrieval operations
11
+ AwardsSearch: Complex award search with filtering and chaining
12
+
13
+ Agency Queries:
14
+ AgencyQuery: Single agency retrieval operations
15
+ AgencyAwardSummary: Agency award summary data retrieval
16
+
17
+ Recipient Queries:
18
+ SpendingByRecipientsSearch: Recipient search with filtering and chaining
19
+
20
+ Example:
21
+ >>> from ..client import USASpendingClient
22
+ >>> client = USASpending()
23
+ >>>
24
+ >>> # Single award retrieval
25
+ >>> award = client.awards.find_by_generated_id("CONT_AWD_123")
26
+ >>>
27
+ >>> # Complex award search
28
+ >>> awards = client.awards.search()\\
29
+ ... .agency("NASA")\\
30
+ ... .in_state("TX")\\
31
+ ... .fiscal_years(2023, 2024)\\
32
+ ... .limit(50)
33
+ >>>
34
+ >>> for award in awards:
35
+ ... print(f"{award.recipient_name}: ${award.amount:,.2f}")
36
+ """
37
+
38
+ # Import custom exceptions to make them available package-wide
39
+ from ..exceptions import (
40
+ USASpendingError,
41
+ APIError,
42
+ HTTPError,
43
+ ValidationError,
44
+ RateLimitError,
45
+ ConfigurationError,
46
+ )
47
+
48
+ from .query_builder import QueryBuilder
49
+ from .award_query import AwardQuery
50
+ from .awards_search import AwardsSearch
51
+ from .agency_query import AgencyQuery
52
+ from .agencies_search import AgenciesSearch
53
+ from .funding_agencies_search import FundingAgenciesSearch
54
+ from .awarding_agencies_search import AwardingAgenciesSearch
55
+ from .agency_award_summary import AgencyAwardSummary
56
+ from .sub_agency_query import SubAgencyQuery
57
+ from .recipient_query import RecipientQuery
58
+ from .recipients_search import RecipientsSearch
59
+ from .transactions_search import TransactionsSearch
60
+ from .funding_search import FundingSearch
61
+ from .spending_search import SpendingSearch
62
+ from .subawards_search import SubAwardsSearch
63
+
64
+ __all__ = [
65
+ # Core query classes
66
+ "QueryBuilder",
67
+ "AwardQuery",
68
+ "AwardsSearch",
69
+ "AgencyQuery",
70
+ "AgenciesSearch",
71
+ "FundingAgenciesSearch",
72
+ "AwardingAgenciesSearch",
73
+ "AgencyAwardSummary",
74
+ "SubAgencyQuery",
75
+ "RecipientQuery",
76
+ "RecipientsSearch",
77
+ "TransactionsSearch",
78
+ "FundingSearch",
79
+ "SpendingSearch",
80
+ "SubAwardsSearch",
81
+ "USASpendingError",
82
+ "APIError",
83
+ "HTTPError",
84
+ "ValidationError",
85
+ "RateLimitError",
86
+ "ConfigurationError",
87
+ ]