iql 1.8.5__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.
iql-1.8.5/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2024, Iqmo Corporation
4
+
5
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
6
+
7
+ Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
8
+
9
+ Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
10
+
11
+ Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
12
+
13
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
iql-1.8.5/PKG-INFO ADDED
@@ -0,0 +1,458 @@
1
+ Metadata-Version: 2.1
2
+ Name: iql
3
+ Version: 1.8.5
4
+ Summary: I* Query Language
5
+ Home-page: https://github.com/iqmo-org/iql
6
+ Keywords: iql,query language,duckdb,bql,blpapi
7
+ Author: Paul T
8
+ Author-email: paul@iqmo.com
9
+ Maintainer: Paul T
10
+ Maintainer-email: paul@iqmo.com
11
+ Requires-Python: >=3.11,<4.0
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Dist: duckdb (>=0.10.3,<0.11.0)
16
+ Requires-Dist: pandas (>=2.2.2,<3.0.0)
17
+ Requires-Dist: poetry (>=1.8.3,<2.0.0)
18
+ Requires-Dist: poetry-core (>=1.9.0,<2.0.0)
19
+ Requires-Dist: poetry-dynamic-versioning[plugin] (>=1.3.0,<2.0.0)
20
+ Requires-Dist: pyarrow (>=16.1.0,<17.0.0)
21
+ Requires-Dist: sqlparse (>=0.5.0,<0.6.0)
22
+ Project-URL: Issues, https://github.com/iqmo-org/iql/issues
23
+ Project-URL: Repository, https://github.com/iqmo-org/iql
24
+ Description-Content-Type: text/markdown
25
+
26
+ [![PyPI Version](https://badge.fury.io/py/iql.svg)](https://pypi.python.org/pypi/iql)
27
+
28
+ <!--[![Anaconda-Server Badge](https://anaconda.org/conda-forge/iql/badges/version.svg)](https://anaconda.org/conda-forge/iql)-->
29
+
30
+ [![BuildRelease](https://github.com/iqmo-org/iql/actions/workflows/build_release.yml/badge.svg)](https://github.com/iqmo-org/iql/actions/workflows/build_release.yml)
31
+ [![Tests](https://github.com/iqmo-org/iql/actions/workflows/test_coverage.yml/badge.svg)](https://github.com/iqmo-org/iql/actions/workflows/test_coverage.yml)
32
+ [![Coverage badge](https://github.com/iqmo-org/iql/raw/python-coverage-comment-action-data/badge.svg)](https://github.com/iqmo-org/iql/tree/python-coverage-comment-action-data)
33
+
34
+ # I\* Query Language (IQL)
35
+
36
+ IQL is a framework and a collection of Python-based extensions for financial data acquisition.
37
+
38
+ ## Disclaimers
39
+
40
+ THIS PROJECT IS NOT AFFILIATED WITH, SUPPORTED BY, ENDORSED BY OR CONNECTED TO ANY OF THE COMPANIES, PRODUCTS OR SERVICES BELOW.
41
+
42
+ # Installation
43
+
44
+ ```
45
+ # Install
46
+ %pip install iql --upgrade
47
+
48
+ # Load Magics to enable %iql and %%iql for VScode and Jupyter
49
+ %load_ext iql
50
+ ```
51
+
52
+ # Usage
53
+
54
+ Python API
55
+
56
+ ```
57
+ import iql
58
+ df1 = iql.execute(f"select * from ...")
59
+ ```
60
+
61
+ Cell Magic
62
+
63
+ ```
64
+ %%iql -o df1
65
+ select * from ...
66
+ ```
67
+
68
+ Line Magic
69
+
70
+ ```
71
+ df1 = %iql select * from ...
72
+ ```
73
+
74
+ # About IQL
75
+
76
+ IQL serves two purposes: a framework for adding lightweight extensions to data pipelines through declarative SQL queries, and a collection of useful extensions.
77
+
78
+ ## IQL: The Framework
79
+
80
+ IQL allows python functions to be registered and executed inline with SQL. These functions take parameters and can return DataFrames, Parquet Files, or CSVs.
81
+
82
+ ```
83
+ SELECT * FROM myextension(param='abc', param2='def')
84
+ ```
85
+
86
+ In this simple example, IQL extracts and preprocesses myextension. The SQL is rewritten to replace myextension, and the DataFrame is registered with the database. The exact mechanism depends on the database: for DuckDB (default database), the dataframes can be queried on the fly without loading explicitly to the database.
87
+
88
+ ## IQL: The Extensions
89
+
90
+ IQL works out of the box, allowing you to execute SQL statements over your dataframes and external data sources with no configuration.
91
+
92
+ - Bloomberg Query Language (BQL)
93
+
94
+ ```sql
95
+ select * from bql("get(px_last) for(['IBM US Equity']) with(dates=range(-90D, 0D), fill=prev)") order by value desc limit 3
96
+ ```
97
+
98
+ - Bloomberg BLPAPI
99
+ ```sql
100
+ select * from blpapi(fields=("PX_LAST","PX_OPEN", "BID"), historical=False, securities=("IBM US Equity","SPX Index"))
101
+ ```
102
+ - Pandas operations
103
+ ```sql
104
+ SELECT * FROM pandas(table=xyz, pivot=('col1', 'col2', 'values'))
105
+ ```
106
+
107
+ ## Why?
108
+
109
+ SQL is a powerful declarative language, capable of expressing complex data manipulations and enabling efficient optimized processing. Often, interaction with external data is required, making it difficult to build interactive systems leveraging declarative data structures. Combining SQL with a pre-processing framework to externalize data load within the context of a SQL query makes many workflows simpler.
110
+
111
+ Modern analytical databases, such as [DuckDB](https://github.com/duckdb), provide many powerful tools to allow more to be done within SQL and eliminating the back and forth required for data loading and manipulation. IQL is intended to extend the power of these platforms without being tied to a single platform: through the use of pre-processed extensions.
112
+
113
+ ### Native Formats
114
+
115
+ After preprocessing of the IQL Extension queries, the database engine will execute a native query unmodified. This minimizes the dependency on specific databases and database versions.
116
+
117
+ The native SQL format of the database engine is supported: the SQL runs unmodified except for replacement of the IQL SubQueries.
118
+
119
+ The native SubQuery syntax is preserved. Bloomberg BQL queries run without modification. REST API calls can be called via URLs directly. etc.
120
+
121
+ ### Simplicity and Performance
122
+
123
+ Multiple transformations, aggregations and operations can be expressed in a single statement. This reduces the amount of code we need to write, eliminates long chains of Pandas operations, and often leads to significant performance increases.
124
+
125
+ IQL's default database is a higly efficient in-memory OLAP database called DuckDB, which requires zero configuration or administration. You may use a transient database per query, or create a long-lived database and reuse across queries. [DuckDB Performance vs Pandas](https://duckdb.org/2021/05/14/sql-on-pandas.html)
126
+
127
+ ### All in One Place and Extensible
128
+
129
+ You can query REST APIs as if they were database tables. You can add custom business logic to control how certain files are retrieved, cached or pre-processed.
130
+
131
+ IQL is portable across DB environments. DuckDB is shipped by default, but can be replaced by other databases.
132
+
133
+ ### How Does It Work
134
+
135
+ How does it work? IQL iterates over SQL statements (if multiple statements are used), and extracts IQL SubQuerys (ie: fred(...)). Each SubQuery is executed and stored (as a DataFrame or local file). The SQL query is modified to reference the results of the SubQuery instead of the SubQuery itself, and the database engine runs the modified SQL query.
136
+
137
+ For example, given the following query:
138
+
139
+ ```
140
+ %%iql
141
+ SELECT *
142
+ FROM fred('query1') as q1
143
+ JOIN fred('query2') as q2
144
+ ON q1.id=q2.id
145
+ ```
146
+
147
+ In pseudocode (this is logically but not literally what happens):
148
+
149
+ ```
150
+ # pseudocode
151
+ df_q1 = iql.execute("fred('query1")")
152
+ df_q2 = iql.execute("fred('query2")")
153
+
154
+ db.execute("SELECT * FROM df_q1 JOIN df_q2 on df_q1.id = df_q2.id")
155
+ ```
156
+
157
+ Or, using the %iql cell magic:
158
+
159
+ # Extensions:
160
+
161
+ - [Bloomberg BQL](BLOOMBERG_BQL_README.md)
162
+
163
+ - [Bloomberg BLPAPI](https://www.bloomberg.com/professional/support/api-library/)
164
+ - [Pandas](https://pandas.pydata.org/): Allows Pandas operations to be executed within the SQL statement. Not all Pandas operations are available.
165
+
166
+ See the examples/ folder for complete examples.
167
+
168
+ ## Syntax
169
+
170
+ IQL extensions are executed as functional subqueries. Each extension is registered with a unique name.
171
+
172
+ ```
173
+ SELECT \*
174
+ FROM
175
+ bql("get (...) for (...)") q1
176
+ JOIN
177
+ bql("get (...) for (...)") q2
178
+ ON
179
+ q1.id = q2.id
180
+ ```
181
+
182
+ See the example notebooks for more interesting examples.
183
+
184
+ ## SQL Syntax
185
+
186
+ IQL uses a superset of the underlying database language. DuckDB is the default database, with a dialect similar/consistent with PostgreSQL's:
187
+ [DuckDB SQL Introduction](https://duckdb.org/docs/sql/introduction.html)
188
+ [DuckDB SQL Statements](https://duckdb.org/docs/sql/introduction)
189
+
190
+ ## Quoting Strings
191
+
192
+ Strings must be properly quoted and/or escaped, according to normal Python rules. The SubQuery requires a quoted string, be careful to use different quote types for the entire SQL string and the SubQuery string.
193
+
194
+ Triple quotes are convenient, since SQL queries tend to be long and multi-line. Note the three levels of quotes: triple """, single " and single '.
195
+
196
+ ```
197
+ import iql
198
+
199
+ bql_str = "get (...) for ('XYZ')"
200
+ sql_str = f"""
201
+ -- This uses a Python f-string, which allows us to use the {bql_str} variable
202
+ SELECT *
203
+ FROM
204
+ -- bql() is an IQL extension. Note the quotes around the BQL statement.
205
+ -- if the BQL statement contains double quotes,
206
+ bql("{bql_str}")
207
+ """
208
+
209
+ iql.execute(sql_str)
210
+ ```
211
+
212
+ In Notebooks, this is a little simpler, since the outer quotes aren't needed:
213
+
214
+ ```
215
+ %%iql -o bql_df
216
+
217
+ SELECT * FROM bql("get(px_last) for ([`IBM US Equity`])")
218
+ ```
219
+
220
+ # Pandas Extension
221
+
222
+ The pandas options are available in every extension, but sometimes its better to run after the data has been first populated in an earlier query.
223
+
224
+ The syntax is:
225
+
226
+ ```
227
+ iql.execute("""SELECT \* FROM pandas(table=xyz, pivot=('col1', 'col2', 'values'))"""
228
+ ```
229
+
230
+ These operations may also be used in each of the extensions:
231
+
232
+ - fillna_pre='string': Before pivoting, replaces only in a single column: DataFrame["value"].fillna(val)
233
+ - dropna_pre=True | str | list[str]: Before pivoting, If True, DataFrame.dropna(). Else, DataFrame.dropna(subset=[value])
234
+ - pivot=(index,columns,values): DataFrame.pivot(index=index, columns=columns, values=values)
235
+ - fillna=val: DataFrame.fillna(val)
236
+ - dropna=True | str | list[str]: If True, DataFrame.dropna(). Else, DataFrame.dropna(subset=[value])
237
+
238
+ Note: While still in development, [DuckDB's Pivot and Unpivot](https://github.com/duckdb/duckdb/pull/6387) may change how we handle pivoting.
239
+
240
+ # Operations available to all IQL SubQueries:
241
+
242
+ # IQL extension for Bloomberg BQL
243
+
244
+ See [IQL Extension for Bloomberg BQL Readme](BLOOMBERG_BQL_README.md) for more information.
245
+
246
+ ## Troubleshooting: If you see an initialization failure, verify that BQL is available and working.
247
+
248
+ ```
249
+ import bql
250
+ bq = bql.Service()
251
+ bq.execute("get(name) for('IBM US Equity')")
252
+ ```
253
+
254
+ If this fails, you are probably not running in BQuant.
255
+
256
+ # Database
257
+
258
+ ## Database Lifecycle
259
+
260
+ ### Default: In-Memory Database for each iql.execute()
261
+
262
+ By default, a series of iql.execute() calls will create and close an in-memory DuckDB connection for each request.
263
+
264
+ ### Option 1: Keep Database Open
265
+
266
+ Use the iql default connection setting (in-memory only), but leave the connection open:
267
+
268
+ ```
269
+ con = iql.IQL.get_dbconnector().get_connection()
270
+ try:
271
+ iql.execute("CREATE TABLE abc as SELECT * FROM (values(1),(2),(3))", con=con)
272
+ df=iql.execute("SELECT * FROM abc", con=con)
273
+ display(df)
274
+ finally:
275
+ con.close()
276
+ ```
277
+
278
+ SQL statements separated by semicolons. The entire set will be run sequentially against a single database, so side effects will be maintained.
279
+
280
+ ### Option 2: Create Database Externally
281
+
282
+ With this method, you can use a file-based persistent database along with other connectivity options.
283
+
284
+ Or, create a DuckDB Connection [duckdb.connect()](https://duckdb.org/docs/api/python/overview), such as for a file-based persistent database.
285
+
286
+ ```
287
+ df=iql.execute("SELECT * FROM abc", con=con)
288
+ ```
289
+
290
+ # FAQ
291
+
292
+ ## How can I simplify my SQL?
293
+
294
+ There are several approaches to using IQL SubQueries:
295
+
296
+ ### Inline
297
+
298
+ ```
299
+ SELECT fields
300
+ FROM table1
301
+ JOIN table2
302
+ on table1.id=table2.id
303
+ JOIN bql(".....") as k3
304
+ on k3.dates < table2.dates
305
+ WHERE k3.something is true
306
+ ```
307
+
308
+ ### Common Table Expressions (WITH clause)
309
+
310
+ CTEs are necessary when the same subquery will be transformed multiple times within a single query. CTEs are also helpful syntactic sugar: the declaration of a subquery is separate from its use, making the SELECT statement simpler.
311
+
312
+ ```
313
+ WITH k3 as (select * from bql(".....") WHERE something is true)
314
+ SELECT fields
315
+ FROM table1
316
+ JOIN table2
317
+ on table1.id=table2.id
318
+ JOIN k3
319
+ on k3.dates < table2.dates
320
+ ```
321
+
322
+ ### Storing the Data in Tables
323
+
324
+ When data will be accessed by multiple queries, store the data first via CREATE TABLE / CREATE TEMP TABLE instead of running the same IQL SubQueries multiple times. IQL's caching is helpful, if enabled, but storing the data in tables provides more flexibility.
325
+
326
+ ```
327
+ CREATE [TEMP] TABLE k3 as (SELECT * FROM bql(".....") WHERE something is true);
328
+ SELECT fields
329
+ FROM table2
330
+ on table1.id=table2.id
331
+ JOIN k3
332
+ on k3.dates < table2.dates
333
+ ```
334
+
335
+ ## Why DuckDB as the default?
336
+
337
+ We chose [DuckDB](https://duckdb.org/) as the default database module for a few reasons:
338
+
339
+ - DuckDB is awesome and [fast](https://duckdb.org/2021/05/14/sql-on-pandas.html), with vectorized columnar operations.
340
+ - It runs with no setup
341
+ - It runs fully in memory and has support for a variety of data sources
342
+ - DuckDB's SQL language is standard
343
+ - DuckDB has extensive support for the Python ecosystem, including Pandas, PyArrow and Polars
344
+
345
+ ## Why not a DuckDB Extensions?
346
+
347
+ We didn't implement IQL as an extension for a few reasons:
348
+
349
+ - Portability: DuckDB is great, but it's not the only game in town. Engines like SnowFlake are important.
350
+ - Speed of development: Native Python is easy to develop, easy to debug, and convenient to modify and extend.
351
+ - Performance: In our workflows, there was little performance to be gained. Runtime was dominated by external data transfer.
352
+
353
+ We may still implement DuckDB extension(s) to eliminate the extra preprocess/rewrite step.
354
+
355
+ ## Other Databases Engines
356
+
357
+ Any database can be supported by implementing a database module. IQL was written in a syntax neutral method. The key step that's dependent on the database engine is registering (or loading) the SubQuery dataframes to the database engine prior to executing the queries.
358
+
359
+ Modules could be added to support other engines and formats:
360
+
361
+ - [SQLDF](https://pypi.org/project/sqldf/) and [PandaSQL](https://pypi.org/project/pandasql/): Local-only databases that can connect to in-memory Pandas dataframes
362
+ - PyArrow (w/ PySpark/Dask): SubQuery dataframes would be loaded via [pyarrow.Table.from_pandas()](https://arrow.apache.org/docs/python/pandas.html)
363
+ - SnowFlake: During registration step, the Pandas dataframes need to be loaded via the [SnowFlake Pandas Connector](https://docs.snowflake.com/en/user-guide/python-connector-pandas)
364
+ - Other Pandas-centric engines, such as SQLDF and PandaSQL
365
+
366
+ ## Design Principles
367
+
368
+ - Extensibility: Extensions and Database Connectors can be easily modified, replaced, or extended.
369
+ - KISS: Keep it simple. Don't add complexity.
370
+ - REST APIs, such as FRED: Use the complete URL, rather than building yet-another-Python-API
371
+ - Bloomberg BQL: Use native BQL queries without modification
372
+ - Minimal dependencies: Extensions are loaded on-demand. Unused dependencies are not required.
373
+
374
+ # Footnotes
375
+
376
+ ## Useful DuckDB Features
377
+
378
+ ### CTEs
379
+
380
+ ```
381
+ import iql
382
+ df = iql.execute("""
383
+ WITH c AS keyword("..."),
384
+ idx AS keyword("...")
385
+ SELECT c.*, idx.*
386
+ FROM c
387
+ JOIN idx
388
+ ON c.idx=idx.id""")
389
+ display(df)
390
+ ```
391
+
392
+ ### Accessing Global DataFrames:
393
+
394
+ ```
395
+ import iql
396
+ import pandas as pd
397
+
398
+ fun = pd.DataFrame([{'id': 'Someone', 'fun_level': 'High'}])
399
+ iql.execute("""SELECT * FROM fun""")
400
+ ```
401
+
402
+ ### Copy (query) to 'file'
403
+
404
+ ```
405
+ import iql
406
+ iql.execute("""COPY (query) TO 'somefile.parquet'""")
407
+ ```
408
+
409
+ ## Copy to Parquet
410
+
411
+ - Copy to parquet:
412
+ https://duckdb.org/docs/guides/import/parquet_export.html#:~:text=To%20export%20the%20data%20from,exported%20to%20a%20Parquet%20file.
413
+
414
+ # Futures and Ideas
415
+
416
+ ## SQL ReWrite
417
+
418
+ Instead of modifying the SQL in a single step, we could introduce an intermediate statement that has the same logical flow as the code today. This would make it easier to debug, allowing the user to view and debug each step.
419
+
420
+ ```
421
+ SELECT * FROM fred() a JOIN fred() b on a.id=b.id
422
+ ```
423
+
424
+ could be transformed first into:
425
+
426
+ ```
427
+ a=fred();
428
+ b=fred();
429
+ SELECT * FROM a JOIN b
430
+ ```
431
+
432
+ One decision needed here is how to express the first two statements: would we use a CREATE TEMP TABLE or COPY TO to store the SubQuery results, or do we introduce something like CREATE DF.
433
+
434
+ ## Simplifying Parsing
435
+
436
+ We didn't implement a grammar, because each grammar is very platform dependent. Each database has its own product-specific grammar.
437
+
438
+ The current IQL implementation first parses the SQL to extract the named functions, using the sqlparse library, then extracts the IQL subquerys by their named keywords. The SubQueries are then parsed via an AST to extract the parameters and values. Any parsing introduces risks and fragility:
439
+
440
+ - It's possible that sqlparse will fail to parse certain database specific language features. We haven't encountered this yet, but it's something we're thinking about
441
+ - It's also possible that our extraction will fail to recognize proper subqueries, due to how sqlparse extracts the tokens. The code here is not as robust as we'd like, and more testing is needed.
442
+
443
+ There's a few ways to improve this:
444
+
445
+ - Direct string extraction: identify subquery() blocks and extract them directly as strings, rather than parsing the entire SQL file. This would have to properly account for commenting, quoting, and nesting.
446
+ - DuckDB (or whatever platform) extensions: use a lightweight extension to allow the database to externally call the IQL layer, rather than having IQL act as an intermediate step. Or, use a table function, which is not yet supported in SQL, only in relational API.
447
+
448
+ ## Caching
449
+
450
+ The default in-memory cache will grow unbounded within each kernel session. The expiration is only used to invalid data, but expired results are not evicted from memory if not accessed.
451
+
452
+ IQL doesn't provide a default implementation, but the QueryCacheBase is intended to be extended to provide file or S3 caching for large, expensive operations along with more sophisticated caching rules.
453
+
454
+ # Footer
455
+
456
+ Copyright (C) 2024, IQMO Corporation [info@iqmo.com]
457
+ All Rights Reserved
458
+