Metadata-Version: 2.1
Name: finagg
Version: 1.0.1
Summary: Data aggregation with popular and free financial APIs.
Author: Andrew B.
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Repository, https://github.com/theOGognf/finagg
Project-URL: Documentation, https://theogognf.github.io/finagg/
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: POSIX
Classifier: Operating System :: Unix
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Software Development
Classifier: Topic :: Scientific/Engineering
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: beautifulsoup4==4.*
Requires-Dist: click==8.*
Requires-Dist: pandas==2.*
Requires-Dist: pandas-stubs==2.*
Requires-Dist: python-dotenv==0.21.*
Requires-Dist: requests==2.*
Requires-Dist: requests-cache==0.9.*
Requires-Dist: SQLAlchemy==2.*
Requires-Dist: tqdm==4.*
Requires-Dist: types-requests==2.*
Requires-Dist: typing-extensions==4.*
Requires-Dist: yfinance<0.2.29
Provides-Extra: dev
Requires-Dist: build[virtualenv]; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: pre-commit; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: pytest-xdist; extra == "dev"
Requires-Dist: pytest-randomly; extra == "dev"
Requires-Dist: sphinx; extra == "dev"
Requires-Dist: tox; extra == "dev"
Requires-Dist: virtualenv; extra == "dev"

# finagg: Financial Aggregation for Python

![PyPI Downloads](https://img.shields.io/pypi/dm/finagg)
![PyPI Version](https://img.shields.io/pypi/v/finagg)
![Python Versions](https://img.shields.io/pypi/pyversions/finagg)

**finagg** is a Python package that provides implementations of popular and free
financial APIs, tools for aggregating historical data from those APIs into SQL
databases, and tools for transforming aggregated data into features useful for
analysis and AI/ML.

* **Documentation**: https://theogognf.github.io/finagg/
* **PyPI**: https://pypi.org/project/finagg/
* **Repository**: https://github.com/theOGognf/finagg

# Quick Start

## Installation

Install with pip for the latest stable version.

```console
pip install finagg
```

Install from GitHub for the latest unstable version.

```console
git clone https://github.com/theOGognf/finagg.git
pip install ./finagg/
```

Optionally install the recommended datasets (economic data, company
financials, stock histories, etc.) from 3rd party APIs into a local SQL
database.

```console
finagg install -ss economic -ts indices -z -r
```

The installation will point you where to get free API keys for each API that
requires one and will write those API keys to a local ``.env`` file for storage.
Run ``finagg install --help`` for more installation options and details.

## Basic Usage

These are just **finagg** usage samples. See the [documentation][4] for all the
supported APIs and features.

### Explore the APIs directly

*These methods require internet access and API keys/user agent declarations.*

Get Bureau of Economic Analysis (BEA) data.

```pycon
>>> finagg.bea.api.gdp_by_industry.get(year=[2019]).head(5)
   table_id freq  year quarter industry                         industry_description ...
0         1    Q  2019       1       11  Agriculture, forestry, fishing, and hunting ...
1         1    Q  2019       1    111CA                                        Farms ...
2         1    Q  2019       1    113FF    Forestry, fishing, and related activities ...
3         1    Q  2019       1       21                                       Mining ...
4         1    Q  2019       1      211                       Oil and gas extraction ...
```

Get Federal Reserve Economic Data (FRED).

```pycon
>>> finagg.fred.api.series.observations.get(
...   "CPIAUCNS",
...   realtime_start=0,
...   realtime_end=-1,
...   output_type=4
... ).head(5)
  realtime_start realtime_end        date  value series_id
0     1949-04-22   1953-02-26  1949-03-01  169.5  CPIAUCNS
1     1949-05-23   1953-02-26  1949-04-01  169.7  CPIAUCNS
2     1949-06-24   1953-02-26  1949-05-01  169.2  CPIAUCNS
3     1949-07-22   1953-02-26  1949-06-01  169.6  CPIAUCNS
4     1949-08-26   1953-02-26  1949-07-01  168.5  CPIAUCNS
```

Get Securities and Exchange Commission (SEC) filings.

```pycon
>>> finagg.sec.api.company_facts.get(ticker="AAPL").head(5)
          end        value                  accn    fy  fp    form       filed ...
0  2009-06-27  895816758.0  0001193125-09-153165  2009  Q3    10-Q  2009-07-22 ...
1  2009-10-16  900678473.0  0001193125-09-214859  2009  FY    10-K  2009-10-27 ...
2  2009-10-16  900678473.0  0001193125-10-012091  2009  FY  10-K/A  2010-01-25 ...
3  2010-01-15  906794589.0  0001193125-10-012085  2010  Q1    10-Q  2010-01-25 ...
4  2010-04-09  909938383.0  0001193125-10-088957  2010  Q2    10-Q  2010-04-21 ...
```

### Use installed raw data for exploring the most popular features

*These methods require internet access, API keys/user agent declarations, and
downloading and installing raw data through the* ``finagg install`` *or*
``finagg <api/subpackage> install`` *commands.*

Get the most popular FRED features all in one dataframe.

```pycon
>>> finagg.fred.feat.economic.from_raw().head(5)
            CIVPART  LOG_CHANGE(CPIAUCNS)  LOG_CHANGE(CSUSHPINSA)  FEDFUNDS ...
date                                                                        ...
2014-10-06     62.8                   0.0                     0.0      0.09 ...
2014-10-08     62.8                   0.0                     0.0      0.09 ...
2014-10-13     62.8                   0.0                     0.0      0.09 ...
2014-10-15     62.8                   0.0                     0.0      0.09 ...
2014-10-20     62.8                   0.0                     0.0      0.09 ...
```

Get quarterly report features from SEC data.

```pycon
>>> finagg.sec.feat.quarterly.from_raw("AAPL").head(5)
                    LOG_CHANGE(Assets)  LOG_CHANGE(AssetsCurrent) ...
fy   fp filed                                                     ...
2010 Q1 2010-01-25            0.182629                  -0.023676 ...
     Q2 2010-04-21            0.000000                   0.000000 ...
     Q3 2010-07-21            0.000000                   0.000000 ...
2011 Q1 2011-01-19            0.459174                   0.278241 ...
     Q2 2011-04-21            0.000000                   0.000000 ...
```

Get an aggregation of quarterly and daily features for a particular ticker.

```pycon
>>> finagg.fundam.feat.fundam.from_raw("AAPL").head(5)
            PriceBookRatio  PriceEarningsRatio
date
2010-01-25        0.175061            2.423509
2010-01-26        0.178035            2.464678
2010-01-27        0.178813            2.475448
2010-01-28        0.177154            2.452471
2010-01-29        0.173825            2.406396
```

### Use installed features for exploring refined aggregations of raw data

*These methods require installing refined data through the* ``finagg install``
*or* ``finagg <api/subpackage> install`` *commands.*

Get a ticker's industry's averaged quarterly report features.

```pycon
>>> finagg.sec.feat.quarterly.industry.from_refined(ticker="AAPL").head(5)
                                 mean                           ...
name               AssetCoverageRatio BookRatio DebtEquityRatio ...
fy   fp filed                                                   ...
2014 Q1 2014-05-15          10.731301  9.448954        0.158318 ...
     Q2 2014-08-14          10.731301  9.448954        0.158318 ...
     Q3 2014-11-14          10.731301  9.448954        0.158318 ...
2015 Q1 2015-05-15          16.738972  9.269250        0.294238 ...
     Q2 2015-08-13          16.738972  9.269250        0.294238 ...
```

Get a ticker's industry-averaged quarterly report features.

```pycon
>>> finagg.sec.feat.quarterly.normalized.from_refined("AAPL").head(5)
                    NORM(LOG_CHANGE(Assets))  NORM(LOG_CHANGE(AssetsCurrent)) ...
fy   fp filed                                                                 ...
2010 Q2 2010-04-21                  0.000000                         0.000000 ...
     Q3 2010-07-21                  0.000000                         0.000000 ...
2011 Q1 2011-01-19                  0.978816                         0.074032 ...
     Q2 2011-04-21                  0.000000                         0.000000 ...
     Q3 2011-07-20                 -0.353553                        -0.353553 ...
```

Get tickers sorted by an industry-averaged quarterly report feature.

```pycon
>>> finagg.sec.feat.quarterly.normalized.get_tickers_sorted_by(
...   "NORM(EarningsPerShareBasic)",
...   year=2019
... )[:5]
['XRAY', 'TSLA', 'SYY', 'WHR', 'KMB']
```

Get tickers sorted by an industry-averaged fundamental feature.

```pycon
>>> finagg.fundam.feat.fundam.normalized.get_tickers_sorted_by(
...   "NORM(PriceEarningsRatio)",
...   date="2019-01-04"
... )[:5]
['AMD', 'TRGP', 'HPE', 'CZR', 'TSLA']
```

# Configuration

## API Keys and User Agents

API keys and user agent declarations are required for most of the APIs.
You can set environment variables to expose your API keys and user agents
to **finagg**, or you can pass your API keys and user agents to the implemented
APIs programmatically. The following environment variables are used for
configuring API keys and user agents:

* ``BEA_API_KEY`` is for the Bureau of Economic Analysis's API key. You can get
  a free API key from the [BEA API site][3].
* ``FRED_API_KEY`` is for the Federal Reserve Economic Data API key. You can get
  a free API key from the [FRED API site][8].
* ``INDICES_API_USER_AGENT`` is for scraping popular indices' compositions from
  Wikipedia and should be equivalent to a browser's user agent declaration.
  This defaults to a hardcoded value, but it may not always work.
* ``SEC_API_USER_AGENT`` is for the Securities and Exchange Commission's API. This
  should be of the format ``FIRST_NAME LAST_NAME E_MAIL``.

## Data Locations

**finagg**'s root path, HTTP cache path, and database path are all configurable
through environment variables. By default, all data related to **finagg** is put
in a ``./findata`` directory relative to a root directory. You can change these
locations by modifying the respective environment variables:

* ``FINAGG_ROOT_PATH`` points to the parent directory of the ``./findata`` directory.
  Defaults to your current working directory.
* ``FINAGG_HTTP_CACHE_PATH`` points to the HTTP requests cache SQLite storage.
  Defaults to ``./findata/http_cache.sqlite``.
* ``FINAGG_DATABASE_URL`` points to the **finagg** data storage. Defaults to
  ``./findata/finagg.sqlite``.

# Dependencies

* [pandas][11] for fast, flexible, and expressive representations of relational data.
* [requests][12] for HTTP requests to 3rd party APIs.
* [requests-cache][13] for caching HTTP requests to avoid getting throttled by 3rd
  party API servers.
* [SQLAlchemy][17] for a SQL Python interface.
* [yfinance][18] for historical stock data from Yahoo! Finance.

# API References

* The [BEA API][1] and the [BEA API key registration link][2].
* The [FRED API][6] and the [FRED API key registration link][7].
* The [SEC API][14].

# Related Projects

* [FinRL][5] is a collection of financial reinforcement learning environments
  and tools.
* [fredapi][9] is an implementation of the FRED API.
* [OpenBBTerminal][10] is an open-source version of the Bloomberg Terminal.
* [sec-edgar][15] is an implementation of a file-based SEC EDGAR parser.
* [sec-edgar-api][16] is an implementation of the SEC EDGAR REST API.

# Frequently Asked Questions

## Where should I start?

Aggregate some data, create some analysis notebooks, or create some RL
environments using the implemented data features and SQL tables. This
project was originally created to make RL environments for financial
applications but has since focused its purpose to just aggregating financial
data and features. That being said, all the implemented features are
defined in such a way to make it very easy to develop financial AI/ML,
so we encourage you to do just that!

## Why aren't features being installed for a specific ticker or economic data series?

Implemented APIs may be relatively new and simply may not provide data for a
particular ticker or economic data series. For example, earnings per share may
not be accessible for all companies through the SEC EDGAR API. In some cases,
APIs may raise an HTTP error, causing installations to skip the ticker or
series. Additionally, not all tickers and economic data series contain
sufficient data for feature normalization. If a ticker or series only has one
data point, that data point could be dropped when computing a feature (such as
percent change), causing no data to be installed.

## What Python versions are supported?

Python 3.10 and up are supported. We don't plan on supporting lower versions
because 3.10 introduces some nice quality of life updates that are used
throughout the package.

## What operating systems are supported?

The package is developed and tested on both Linux and Windows, but we recommend
using Linux or WSL in practice. The package performs a good amount of I/O and
interprocess operations that could result in a noticeable performance
degradation on Windows.

[1]: https://apps.bea.gov/api/signup/
[2]: https://apps.bea.gov/API/signup/
[3]: https://apps.bea.gov/API/signup/
[4]: https://theogognf.github.io/finagg/
[5]: https://github.com/AI4Finance-Foundation/FinRL
[6]: https://fred.stlouisfed.org/docs/api/fred/
[7]: https://fredaccount.stlouisfed.org/login/secure/
[8]: https://fredaccount.stlouisfed.org/login/secure/
[9]: https://github.com/mortada/fredapi
[10]: https://github.com/OpenBB-finance/OpenBBTerminal
[11]: https://pandas.pydata.org/
[12]: https://requests.readthedocs.io/en/latest/
[13]: https://requests-cache.readthedocs.io/en/stable/
[14]: https://www.sec.gov/edgar/sec-api-documentation
[15]: https://github.com/sec-edgar/sec-edgar
[16]: https://github.com/jadchaar/sec-edgar-api
[17]: https://www.sqlalchemy.org/
[18]: https://github.com/ranaroussi/yfinance
