├── .github └── workflows │ └── main.yml ├── .gitignore ├── DESCRIPTION.rst ├── LICENSE ├── MANIFEST.in ├── README.md ├── fredapi ├── __init__.py ├── fred.py ├── tests │ ├── __init__.py │ ├── test_fred.py │ └── test_with_proxies.py └── version.py ├── requirements.txt └── setup.py /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Python packaging 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | python-version: [3.8, 3.9] 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v2 14 | - name: Set up Python ${{ matrix.python-version }} 15 | uses: actions/setup-python@v2 16 | with: 17 | python-version: ${{ matrix.python-version }} 18 | - name: Caching packages 19 | uses: actions/cache@v2 20 | with: 21 | path: ~/.cache/pip 22 | key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} 23 | restore-keys: | 24 | ${{ runner.os }}-pip- 25 | - name: Install dependencies 26 | run: | 27 | python -m pip install -r requirements.txt 28 | python -m pip install flake8 coverage 29 | - name: Analysing the code with Flake8 30 | continue-on-error: true 31 | run: | 32 | flake8 33 | - name: Running unit tests 34 | continue-on-error: true 35 | run: | 36 | python setup.py test 37 | - name: Running coverage tests 38 | continue-on-error: true 39 | run: | 40 | python setup.py --quiet install 41 | coverage run --source fredapi.fred fredapi/tests/test_fred.py 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | bin/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # Installer logs 26 | pip-log.txt 27 | pip-delete-this-directory.txt 28 | 29 | # Unit test / coverage reports 30 | htmlcov/ 31 | .tox/ 32 | .coverage 33 | .cache 34 | nosetests.xml 35 | coverage.xml 36 | 37 | # Translations 38 | *.mo 39 | 40 | # Mr Developer 41 | .mr.developer.cfg 42 | .project 43 | .pydevproject 44 | 45 | # Rope 46 | .ropeproject 47 | 48 | # Django stuff: 49 | *.log 50 | *.pot 51 | 52 | # Sphinx documentation 53 | docs/_build/ 54 | 55 | # Jetbrains 56 | .idea/* 57 | -------------------------------------------------------------------------------- /DESCRIPTION.rst: -------------------------------------------------------------------------------- 1 | fredapi: Python API for FRED (Federal Reserve Economic Data) 2 | ============================================================ 3 | 4 | ``fredapi`` is a Python API for the 5 | `FRED `__ data provided by the 6 | Federal Reserve Bank of St. Louis. ``fredapi`` provides a wrapper in 7 | python to the `FRED web 8 | service `__, and also provides 9 | several conveninent methods for parsing and analyzing point-in-time data 10 | (i.e. historic data revisions) from 11 | `ALFRED `__ 12 | 13 | ``fredapi`` makes use of ``pandas`` and returns data to you in a 14 | ``pandas`` ``Series`` or ``DataFrame`` 15 | 16 | Installation 17 | ------------ 18 | 19 | .. code:: sh 20 | 21 | pip install fredapi 22 | 23 | Basic Usage 24 | ----------- 25 | 26 | First you need an API key, you can `apply for 27 | one `__ for free on the FRED 28 | website. Once you have your API key, you can set it in one of three 29 | ways: 30 | 31 | - set it to the evironment variable FRED\_API\_KEY 32 | - save it to a file and use the 'api\_key\_file' parameter 33 | - pass it directly as the 'api\_key' parameter 34 | 35 | .. code:: python 36 | 37 | from fredapi import Fred 38 | fred = Fred(api_key='insert api key here') 39 | data = fred.get_series('SP500') 40 | 41 | Working with data revisions 42 | --------------------------- 43 | 44 | Many economic data series contain frequent revisions. ``fredapi`` 45 | provides several convenient methods for handling data revisions and 46 | answering the quesion of what-data-was-known-when. 47 | 48 | In `ALFRED `__ there is the 49 | concept of a *vintage* date. Basically every *observation* can have 50 | three dates associated with it: *date*, *realtime\_start* and 51 | *realtime\_end*. 52 | 53 | - date: the date the value is for 54 | - realtime\_start: the first date the value is valid 55 | - realitime\_end: the last date the value is valid 56 | 57 | For instance, there has been three observations (data points) for the 58 | GDP of 2014 Q1: 59 | 60 | .. code:: xml 61 | 62 | 63 | 64 | 65 | 66 | This means the GDP value for Q1 2014 has been released three times. 67 | First release was on 4/30/2014 for a value of 17149.6, and then there 68 | have been two revisions on 5/29/2014 and 6/25/2014 for revised values of 69 | 17101.3 and 17016.0, respectively. 70 | 71 | Get first data release only (i.e. ignore revisions) 72 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 73 | 74 | .. code:: python 75 | 76 | data = fred.get_series_first_release('GDP') 77 | 78 | Get latest data 79 | ~~~~~~~~~~~~~~~ 80 | 81 | Note that this is the same as simply calling ``get_series()`` 82 | 83 | .. code:: python 84 | 85 | data = fred.get_series_latest_release('GDP') 86 | 87 | Get latest data known on a given date 88 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 89 | 90 | .. code:: python 91 | 92 | fred.get_series_as_of_date('GDP', '6/1/2014') 93 | 94 | Get all data release dates 95 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 96 | 97 | This returns a ``DataFrame`` with all the data from ALFRED 98 | 99 | .. code:: python 100 | 101 | df = fred.get_series_all_releases('GDP') 102 | df.tail() 103 | 104 | Get all vintage dates 105 | ~~~~~~~~~~~~~~~~~~~~~ 106 | 107 | .. code:: python 108 | 109 | vintage_dates = fred.get_series_vintage_dates('GDP') 110 | 111 | Search for data series 112 | ~~~~~~~~~~~~~~~~~~~~~~ 113 | 114 | You can always search for data series on the FRED website. But sometimes 115 | it can be more convenient to search programmatically. ``fredapi`` 116 | provides a ``search()`` method that does a fulltext search and returns a 117 | ``DataFrame`` of results. 118 | 119 | .. code:: python 120 | 121 | fred.search('potential gdp') 122 | 123 | You can also search by release id and category id with various options 124 | 125 | .. code:: python 126 | 127 | df1 = fred.search_by_release(11) 128 | df2 = fred.search_by_category(101, limit=10, order_by='popularity', sort_order='desc') 129 | 130 | Dependencies 131 | ------------ 132 | 133 | - `pandas `__ 134 | 135 | More Examples 136 | ------------- 137 | 138 | - I have a `blog post with more examples `__ written in an `IPython` notebook 139 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.rst 2 | include *.md 3 | include LICENSE 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # fredapi: Python API for FRED (Federal Reserve Economic Data) 3 | 4 | [![Build and test GitHub](https://github.com/mortada/fredapi/actions/workflows/main.yml/badge.svg)](https://github.com/mortada/fredapi/actions) 5 | [![version](https://img.shields.io/badge/version-0.5.1-success.svg)](#) 6 | [![PyPI Latest Release](https://img.shields.io/pypi/v/fredapi.svg)](https://pypi.org/project/fredapi/) 7 | [![Downloads](https://static.pepy.tech/personalized-badge/fredapi?period=total&units=international_system&left_color=grey&right_color=blue&left_text=Downloads)](https://pepy.tech/project/fredapi) 8 | 9 | `fredapi` is a Python API for the [FRED](http://research.stlouisfed.org/fred2/) data provided by the 10 | Federal Reserve Bank of St. Louis. `fredapi` provides a wrapper in python to the 11 | [FRED web service](http://api.stlouisfed.org/docs/fred/), and also provides several convenient methods 12 | for parsing and analyzing point-in-time data (i.e. historic data revisions) from [ALFRED](http://research.stlouisfed.org/tips/alfred/) 13 | 14 | `fredapi` makes use of `pandas` and returns data to you in a `pandas` `Series` or `DataFrame` 15 | 16 | ## Installation 17 | 18 | ```sh 19 | pip install fredapi 20 | ``` 21 | 22 | ## Basic Usage 23 | 24 | First you need an API key, you can [apply for one](http://api.stlouisfed.org/api_key.html) for free on the FRED website. 25 | Once you have your API key, you can set it in one of three ways: 26 | 27 | * set it to the evironment variable FRED_API_KEY 28 | * save it to a file and use the 'api_key_file' parameter 29 | * pass it directly as the 'api_key' parameter 30 | 31 | ```python 32 | from fredapi import Fred 33 | fred = Fred(api_key='insert api key here') 34 | data = fred.get_series('SP500') 35 | ``` 36 | 37 | ## Working with data revisions 38 | Many economic data series contain frequent revisions. `fredapi` provides several convenient methods for handling data revisions and answering the quesion of what-data-was-known-when. 39 | 40 | In [ALFRED](http://research.stlouisfed.org/tips/alfred/) there is the concept of a *vintage* date. Basically every *observation* can have three dates associated with it: *date*, *realtime_start* and *realtime_end*. 41 | 42 | - date: the date the value is for 43 | - realtime_start: the first date the value is valid 44 | - realitime_end: the last date the value is valid 45 | 46 | For instance, there has been three observations (data points) for the GDP of 2014 Q1: 47 | 48 | ```xml 49 | 50 | 51 | 52 | ``` 53 | 54 | This means the GDP value for Q1 2014 has been released three times. First release was on 4/30/2014 for a value of 17149.6, and then there have been two revisions on 5/29/2014 and 6/25/2014 for revised values of 17101.3 and 17016.0, respectively. 55 | 56 | ### Get first data release only (i.e. ignore revisions) 57 | 58 | ```python 59 | data = fred.get_series_first_release('GDP') 60 | data.tail() 61 | ``` 62 | this outputs: 63 | 64 | ```sh 65 | date 66 | 2013-04-01 16633.4 67 | 2013-07-01 16857.6 68 | 2013-10-01 17102.5 69 | 2014-01-01 17149.6 70 | 2014-04-01 17294.7 71 | Name: value, dtype: object 72 | ``` 73 | 74 | ### Get latest data 75 | Note that this is the same as simply calling `get_series()` 76 | ```python 77 | data = fred.get_series_latest_release('GDP') 78 | data.tail() 79 | ``` 80 | this outputs: 81 | ``` 82 | 2013-04-01 16619.2 83 | 2013-07-01 16872.3 84 | 2013-10-01 17078.3 85 | 2014-01-01 17044.0 86 | 2014-04-01 17294.7 87 | dtype: float64 88 | ``` 89 | ### Get latest data known on a given date 90 | 91 | ```python 92 | fred.get_series_as_of_date('GDP', '6/1/2014') 93 | ``` 94 | this outputs: 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 |
daterealtime_startvalue
2237 2013-10-01 00:00:00 2014-01-30 00:00:00 17102.5
2238 2013-10-01 00:00:00 2014-02-28 00:00:00 17080.7
2239 2013-10-01 00:00:00 2014-03-27 00:00:00 17089.6
2241 2014-01-01 00:00:00 2014-04-30 00:00:00 17149.6
2242 2014-01-01 00:00:00 2014-05-29 00:00:00 17101.3
138 | 139 | ### Get all data release dates 140 | This returns a `DataFrame` with all the data from ALFRED 141 | 142 | ```python 143 | df = fred.get_series_all_releases('GDP') 144 | df.tail() 145 | ``` 146 | this outputs: 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 |
daterealtime_startvalue
2236 2013-07-01 00:00:00 2014-07-30 00:00:00 16872.3
2237 2013-10-01 00:00:00 2014-01-30 00:00:00 17102.5
2238 2013-10-01 00:00:00 2014-02-28 00:00:00 17080.7
2239 2013-10-01 00:00:00 2014-03-27 00:00:00 17089.6
2240 2013-10-01 00:00:00 2014-07-30 00:00:00 17078.3
2241 2014-01-01 00:00:00 2014-04-30 00:00:00 17149.6
2242 2014-01-01 00:00:00 2014-05-29 00:00:00 17101.3
2243 2014-01-01 00:00:00 2014-06-25 00:00:00 17016
2244 2014-01-01 00:00:00 2014-07-30 00:00:00 17044
2245 2014-04-01 00:00:00 2014-07-30 00:00:00 17294.7
220 | 221 | ### Get all vintage dates 222 | ```python 223 | from __future__ import print_function 224 | vintage_dates = fred.get_series_vintage_dates('GDP') 225 | for dt in vintage_dates[-5:]: 226 | print(dt.strftime('%Y-%m-%d')) 227 | ``` 228 | this outputs: 229 | ``` 230 | 2014-03-27 231 | 2014-04-30 232 | 2014-05-29 233 | 2014-06-25 234 | 2014-07-30 235 | ``` 236 | 237 | ### Search for data series 238 | 239 | You can always search for data series on the FRED website. But sometimes it can be more convenient to search programmatically. 240 | `fredapi` provides a `search()` method that does a fulltext search and returns a `DataFrame` of results. 241 | 242 | ```python 243 | fred.search('potential gdp').T 244 | ``` 245 | this outputs: 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 |
series idGDPPOTNGDPPOT
frequencyQuarterlyQuarterly
frequency_shortQQ
idGDPPOTNGDPPOT
last_updated2014-02-04 10:06:03-06:002014-02-04 10:06:03-06:00
notes Real potential GDP is the CBO's estimate of the output the economy would produce with a high rate of use of its capital and labor resources. The data is adjusted to remove the effects of inflation.None
observation_end2024-10-01 00:00:002024-10-01 00:00:00
observation_start1949-01-01 00:00:001949-01-01 00:00:00
popularity7261
realtime_end2014-08-23 00:00:002014-08-23 00:00:00
realtime_start2014-08-23 00:00:002014-08-23 00:00:00
seasonal_adjustmentNot Seasonally AdjustedNot Seasonally Adjusted
seasonal_adjustment_shortNSANSA
titleReal Potential Gross Domestic ProductNominal Potential Gross Domestic Product
unitsBillions of Chained 2009 DollarsBillions of Dollars
units_shortBil. of Chn. 2009 $Bil. of $
333 | 334 | ## Dependencies 335 | - [pandas](http://pandas.pydata.org/) 336 | 337 | ## More Examples 338 | - I have a [blog post with more examples](http://mortada.net/python-api-for-fred.html) written in an `IPython` notebook 339 | -------------------------------------------------------------------------------- /fredapi/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from fredapi.version import version as __version__ 3 | from fredapi.fred import Fred 4 | -------------------------------------------------------------------------------- /fredapi/fred.py: -------------------------------------------------------------------------------- 1 | 2 | import os 3 | import sys 4 | import xml.etree.ElementTree as ET 5 | if sys.version_info[0] >= 3: 6 | import urllib.request as url_request 7 | import urllib.parse as url_parse 8 | import urllib.error as url_error 9 | else: 10 | import urllib2 as url_request 11 | import urllib as url_parse 12 | import urllib2 as url_error 13 | 14 | import pandas as pd 15 | 16 | urlopen = url_request.urlopen 17 | quote_plus = url_parse.quote_plus 18 | urlencode = url_parse.urlencode 19 | HTTPError = url_error.HTTPError 20 | 21 | class Fred: 22 | earliest_realtime_start = '1776-07-04' 23 | latest_realtime_end = '9999-12-31' 24 | nan_char = '.' 25 | max_results_per_request = 1000 26 | root_url = 'https://api.stlouisfed.org/fred' 27 | 28 | def __init__(self, 29 | api_key=None, 30 | api_key_file=None, 31 | proxies=None): 32 | """ 33 | Initialize the Fred class that provides useful functions to query the Fred dataset. You need to specify a valid 34 | API key in one of 3 ways: pass the string via api_key, or set api_key_file to a file with the api key in the 35 | first line, or set the environment variable 'FRED_API_KEY' to the value of your api key. 36 | 37 | Parameters 38 | ---------- 39 | api_key : str 40 | API key. A free api key can be obtained on the Fred website at http://research.stlouisfed.org/fred2/. 41 | api_key_file : str 42 | Path to a file containing the api key. 43 | proxies : dict 44 | Proxies specifications: a dictionary mapping protocol names (e.g. 'http', 'https') to proxy URLs. If not provided, environment variables 'HTTP_PROXY', 'HTTPS_PROXY' are used. 45 | 46 | """ 47 | self.api_key = None 48 | if api_key is not None: 49 | self.api_key = api_key 50 | elif api_key_file is not None: 51 | f = open(api_key_file, 'r') 52 | self.api_key = f.readline().strip() 53 | f.close() 54 | else: 55 | self.api_key = os.environ.get('FRED_API_KEY') 56 | 57 | if self.api_key is None: 58 | import textwrap 59 | raise ValueError(textwrap.dedent("""\ 60 | You need to set a valid API key. You can set it in 3 ways: 61 | pass the string with api_key, or set api_key_file to a 62 | file with the api key in the first line, or set the 63 | environment variable 'FRED_API_KEY' to the value of your 64 | api key. You can sign up for a free api key on the Fred 65 | website at http://research.stlouisfed.org/fred2/""")) 66 | 67 | if not proxies: 68 | http_proxy, https_proxy = os.getenv('HTTP_PROXY'), os.getenv('HTTPS_PROXY') 69 | if http_proxy or https_proxy: 70 | proxies = {'http': http_proxy, 'https': https_proxy} 71 | 72 | self.proxies = proxies 73 | 74 | if self.proxies: 75 | opener = url_request.build_opener(url_request.ProxyHandler(self.proxies)) 76 | url_request.install_opener(opener) 77 | 78 | def __fetch_data(self, url): 79 | """ 80 | helper function for fetching data given a request URL 81 | """ 82 | url += '&api_key=' + self.api_key 83 | try: 84 | response = urlopen(url) 85 | root = ET.fromstring(response.read()) 86 | except HTTPError as exc: 87 | root = ET.fromstring(exc.read()) 88 | raise ValueError(root.get('message')) 89 | return root 90 | 91 | def _parse(self, date_str, format='%Y-%m-%d'): 92 | """ 93 | helper function for parsing FRED date string into datetime 94 | """ 95 | rv = pd.to_datetime(date_str, format=format) 96 | if hasattr(rv, 'to_pydatetime'): 97 | rv = rv.to_pydatetime() 98 | return rv 99 | 100 | def get_series_info(self, series_id): 101 | """ 102 | Get information about a series such as its title, frequency, observation start/end dates, units, notes, etc. 103 | 104 | Parameters 105 | ---------- 106 | series_id : str 107 | Fred series id such as 'CPIAUCSL' 108 | 109 | Returns 110 | ------- 111 | info : Series 112 | a pandas Series containing information about the Fred series 113 | """ 114 | url = "%s/series?series_id=%s" % (self.root_url, series_id) 115 | root = self.__fetch_data(url) 116 | if root is None or not len(root): 117 | raise ValueError('No info exists for series id: ' + series_id) 118 | info = pd.Series(list(root)[0].attrib) 119 | return info 120 | 121 | def get_series(self, series_id, observation_start=None, observation_end=None, **kwargs): 122 | """ 123 | Get data for a Fred series id. This fetches the latest known data, and is equivalent to get_series_latest_release() 124 | 125 | Parameters 126 | ---------- 127 | series_id : str 128 | Fred series id such as 'CPIAUCSL' 129 | observation_start : datetime or datetime-like str such as '7/1/2014', optional 130 | earliest observation date 131 | observation_end : datetime or datetime-like str such as '7/1/2014', optional 132 | latest observation date 133 | kwargs : additional parameters 134 | Any additional parameters supported by FRED. You can see https://api.stlouisfed.org/docs/fred/series_observations.html for the full list 135 | 136 | Returns 137 | ------- 138 | data : Series 139 | a Series where each index is the observation date and the value is the data for the Fred series 140 | """ 141 | url = "%s/series/observations?series_id=%s" % (self.root_url, series_id) 142 | if observation_start is not None: 143 | observation_start = pd.to_datetime(observation_start, 144 | errors='raise') 145 | url += '&observation_start=' + observation_start.strftime('%Y-%m-%d') 146 | if observation_end is not None: 147 | observation_end = pd.to_datetime(observation_end, errors='raise') 148 | url += '&observation_end=' + observation_end.strftime('%Y-%m-%d') 149 | if kwargs.keys(): 150 | url += '&' + urlencode(kwargs) 151 | root = self.__fetch_data(url) 152 | if root is None: 153 | raise ValueError('No data exists for series id: ' + series_id) 154 | data = {} 155 | for child in root: 156 | val = child.get('value') 157 | if val == self.nan_char: 158 | val = float('NaN') 159 | else: 160 | val = float(val) 161 | data[self._parse(child.get('date'))] = val 162 | return pd.Series(data) 163 | 164 | def get_series_latest_release(self, series_id): 165 | """ 166 | Get data for a Fred series id. This fetches the latest known data, and is equivalent to get_series() 167 | 168 | Parameters 169 | ---------- 170 | series_id : str 171 | Fred series id such as 'CPIAUCSL' 172 | 173 | Returns 174 | ------- 175 | info : Series 176 | a Series where each index is the observation date and the value is the data for the Fred series 177 | """ 178 | return self.get_series(series_id) 179 | 180 | def get_series_first_release(self, series_id): 181 | """ 182 | Get first-release data for a Fred series id. This ignores any revision to the data series. For instance, 183 | The US GDP for Q1 2014 was first released to be 17149.6, and then later revised to 17101.3, and 17016.0. 184 | This will ignore revisions after the first release. 185 | 186 | Parameters 187 | ---------- 188 | series_id : str 189 | Fred series id such as 'GDP' 190 | 191 | Returns 192 | ------- 193 | data : Series 194 | a Series where each index is the observation date and the value is the data for the Fred series 195 | """ 196 | df = self.get_series_all_releases(series_id) 197 | first_release = df.groupby('date').head(1) 198 | data = first_release.set_index('date')['value'] 199 | return data 200 | 201 | def get_series_as_of_date(self, series_id, as_of_date): 202 | """ 203 | Get latest data for a Fred series id as known on a particular date. This includes any revision to the data series 204 | before or on as_of_date, but ignores any revision on dates after as_of_date. 205 | 206 | Parameters 207 | ---------- 208 | series_id : str 209 | Fred series id such as 'GDP' 210 | as_of_date : datetime, or datetime-like str such as '10/25/2014' 211 | Include data revisions on or before this date, and ignore revisions afterwards 212 | 213 | Returns 214 | ------- 215 | data : Series 216 | a Series where each index is the observation date and the value is the data for the Fred series 217 | """ 218 | as_of_date = pd.to_datetime(as_of_date) 219 | df = self.get_series_all_releases(series_id) 220 | data = df[df['realtime_start'] <= as_of_date] 221 | return data 222 | 223 | def get_series_all_releases(self, series_id, realtime_start=None, realtime_end=None): 224 | """ 225 | Get all data for a Fred series id including first releases and all revisions. This returns a DataFrame 226 | with three columns: 'date', 'realtime_start', and 'value'. For instance, the US GDP for Q4 2013 was first released 227 | to be 17102.5 on 2014-01-30, and then revised to 17080.7 on 2014-02-28, and then revised to 17089.6 on 228 | 2014-03-27. You will therefore get three rows with the same 'date' (observation date) of 2013-10-01 but three 229 | different 'realtime_start' of 2014-01-30, 2014-02-28, and 2014-03-27 with corresponding 'value' of 17102.5, 17080.7 230 | and 17089.6 231 | 232 | Parameters 233 | ---------- 234 | series_id : str 235 | Fred series id such as 'GDP' 236 | realtime_start : str, optional 237 | specifies the realtime_start value used in the query, defaults to the earliest possible start date allowed by Fred 238 | realtime_end : str, optional 239 | specifies the realtime_end value used in the query, defaults to the latest possible end date allowed by Fred 240 | 241 | Returns 242 | ------- 243 | data : DataFrame 244 | a DataFrame with columns 'date', 'realtime_start' and 'value' where 'date' is the observation period and 'realtime_start' 245 | is when the corresponding value (either first release or revision) is reported. 246 | """ 247 | if realtime_start is None: 248 | realtime_start = self.earliest_realtime_start 249 | if realtime_end is None: 250 | realtime_end = self.latest_realtime_end 251 | url = "%s/series/observations?series_id=%s&realtime_start=%s&realtime_end=%s" % (self.root_url, 252 | series_id, 253 | realtime_start, 254 | realtime_end) 255 | root = self.__fetch_data(url) 256 | if root is None: 257 | raise ValueError('No data exists for series id: ' + series_id) 258 | data = {} 259 | i = 0 260 | for child in root: 261 | val = child.get('value') 262 | if val == self.nan_char: 263 | val = float('NaN') 264 | else: 265 | val = float(val) 266 | realtime_start = self._parse(child.get('realtime_start')) 267 | # realtime_end = self._parse(child.get('realtime_end')) 268 | date = self._parse(child.get('date')) 269 | 270 | data[i] = {'realtime_start': realtime_start, 271 | # 'realtime_end': realtime_end, 272 | 'date': date, 273 | 'value': val} 274 | i += 1 275 | data = pd.DataFrame(data).T 276 | return data 277 | 278 | def get_series_vintage_dates(self, series_id): 279 | """ 280 | Get a list of vintage dates for a series. Vintage dates are the dates in history when a 281 | series' data values were revised or new data values were released. 282 | 283 | Parameters 284 | ---------- 285 | series_id : str 286 | Fred series id such as 'CPIAUCSL' 287 | 288 | Returns 289 | ------- 290 | dates : list 291 | list of vintage dates 292 | """ 293 | url = "%s/series/vintagedates?series_id=%s" % (self.root_url, series_id) 294 | root = self.__fetch_data(url) 295 | if root is None: 296 | raise ValueError('No vintage date exists for series id: ' + series_id) 297 | dates = [] 298 | for child in root: 299 | dates.append(self._parse(child.text)) 300 | return dates 301 | 302 | def __do_series_search(self, url): 303 | """ 304 | helper function for making one HTTP request for data, and parsing the returned results into a DataFrame 305 | """ 306 | root = self.__fetch_data(url) 307 | 308 | series_ids = [] 309 | data = {} 310 | 311 | num_results_returned = 0 # number of results returned in this HTTP request 312 | num_results_total = int(root.get('count')) # total number of results, this can be larger than number of results returned 313 | for child in root: 314 | num_results_returned += 1 315 | series_id = child.get('id') 316 | series_ids.append(series_id) 317 | data[series_id] = {"id": series_id} 318 | fields = ["realtime_start", "realtime_end", "title", "observation_start", "observation_end", 319 | "frequency", "frequency_short", "units", "units_short", "seasonal_adjustment", 320 | "seasonal_adjustment_short", "last_updated", "popularity", "notes"] 321 | for field in fields: 322 | data[series_id][field] = child.get(field) 323 | 324 | if num_results_returned > 0: 325 | data = pd.DataFrame(data, columns=series_ids).T 326 | # parse datetime columns 327 | for field in ["realtime_start", "realtime_end", "observation_start", "observation_end", "last_updated"]: 328 | data[field] = data[field].apply(self._parse, format=None) 329 | # set index name 330 | data.index.name = 'series id' 331 | else: 332 | data = None 333 | return data, num_results_total 334 | 335 | def __get_search_results(self, url, limit, order_by, sort_order, filter): 336 | """ 337 | helper function for getting search results up to specified limit on the number of results. The Fred HTTP API 338 | truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data. 339 | """ 340 | 341 | order_by_options = ['search_rank', 'series_id', 'title', 'units', 'frequency', 342 | 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 343 | 'observation_start', 'observation_end', 'popularity'] 344 | if order_by is not None: 345 | if order_by in order_by_options: 346 | url = url + '&order_by=' + order_by 347 | else: 348 | raise ValueError('%s is not in the valid list of order_by options: %s' % (order_by, str(order_by_options))) 349 | 350 | if filter is not None: 351 | if len(filter) == 2: 352 | url = url + '&filter_variable=%s&filter_value=%s' % (filter[0], filter[1]) 353 | else: 354 | raise ValueError('Filter should be a 2 item tuple like (filter_variable, filter_value)') 355 | 356 | sort_order_options = ['asc', 'desc'] 357 | if sort_order is not None: 358 | if sort_order in sort_order_options: 359 | url = url + '&sort_order=' + sort_order 360 | else: 361 | raise ValueError('%s is not in the valid list of sort_order options: %s' % (sort_order, str(sort_order_options))) 362 | 363 | data, num_results_total = self.__do_series_search(url) 364 | if data is None: 365 | return data 366 | 367 | if limit == 0: 368 | max_results_needed = num_results_total 369 | else: 370 | max_results_needed = limit 371 | 372 | if max_results_needed > self.max_results_per_request: 373 | for i in range(1, max_results_needed // self.max_results_per_request + 1): 374 | offset = i * self.max_results_per_request 375 | next_data, _ = self.__do_series_search(url + '&offset=' + str(offset)) 376 | data = pd.concat([data, next_data]) 377 | return data.head(max_results_needed) 378 | 379 | def search(self, text, limit=1000, order_by=None, sort_order=None, filter=None): 380 | """ 381 | Do a fulltext search for series in the Fred dataset. Returns information about matching series in a DataFrame. 382 | 383 | Parameters 384 | ---------- 385 | text : str 386 | text to do fulltext search on, e.g., 'Real GDP' 387 | limit : int, optional 388 | limit the number of results to this value. If limit is 0, it means fetching all results without limit. 389 | order_by : str, optional 390 | order the results by a criterion. Valid options are 'search_rank', 'series_id', 'title', 'units', 'frequency', 391 | 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 'observation_start', 'observation_end', 392 | 'popularity' 393 | sort_order : str, optional 394 | sort the results by ascending or descending order. Valid options are 'asc' or 'desc' 395 | filter : tuple, optional 396 | filters the results. Expects a tuple like (filter_variable, filter_value). 397 | Valid filter_variable values are 'frequency', 'units', and 'seasonal_adjustment' 398 | 399 | Returns 400 | ------- 401 | info : DataFrame 402 | a DataFrame containing information about the matching Fred series 403 | """ 404 | url = "%s/series/search?search_text=%s&" % (self.root_url, 405 | quote_plus(text)) 406 | info = self.__get_search_results(url, limit, order_by, sort_order, filter) 407 | return info 408 | 409 | def search_by_release(self, release_id, limit=0, order_by=None, sort_order=None, filter=None): 410 | """ 411 | Search for series that belongs to a release id. Returns information about matching series in a DataFrame. 412 | 413 | Parameters 414 | ---------- 415 | release_id : int 416 | release id, e.g., 151 417 | limit : int, optional 418 | limit the number of results to this value. If limit is 0, it means fetching all results without limit. 419 | order_by : str, optional 420 | order the results by a criterion. Valid options are 'search_rank', 'series_id', 'title', 'units', 'frequency', 421 | 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 'observation_start', 'observation_end', 422 | 'popularity' 423 | sort_order : str, optional 424 | sort the results by ascending or descending order. Valid options are 'asc' or 'desc' 425 | filter : tuple, optional 426 | filters the results. Expects a tuple like (filter_variable, filter_value). 427 | Valid filter_variable values are 'frequency', 'units', and 'seasonal_adjustment' 428 | 429 | Returns 430 | ------- 431 | info : DataFrame 432 | a DataFrame containing information about the matching Fred series 433 | """ 434 | url = "%s/release/series?release_id=%d" % (self.root_url, release_id) 435 | info = self.__get_search_results(url, limit, order_by, sort_order, filter) 436 | if info is None: 437 | raise ValueError('No series exists for release id: ' + str(release_id)) 438 | return info 439 | 440 | def search_by_category(self, category_id, limit=0, order_by=None, sort_order=None, filter=None): 441 | """ 442 | Search for series that belongs to a category id. Returns information about matching series in a DataFrame. 443 | 444 | Parameters 445 | ---------- 446 | category_id : int 447 | category id, e.g., 32145 448 | limit : int, optional 449 | limit the number of results to this value. If limit is 0, it means fetching all results without limit. 450 | order_by : str, optional 451 | order the results by a criterion. Valid options are 'search_rank', 'series_id', 'title', 'units', 'frequency', 452 | 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 'observation_start', 'observation_end', 453 | 'popularity' 454 | sort_order : str, optional 455 | sort the results by ascending or descending order. Valid options are 'asc' or 'desc' 456 | filter : tuple, optional 457 | filters the results. Expects a tuple like (filter_variable, filter_value). 458 | Valid filter_variable values are 'frequency', 'units', and 'seasonal_adjustment' 459 | 460 | Returns 461 | ------- 462 | info : DataFrame 463 | a DataFrame containing information about the matching Fred series 464 | """ 465 | url = "%s/category/series?category_id=%d&" % (self.root_url, 466 | category_id) 467 | info = self.__get_search_results(url, limit, order_by, sort_order, filter) 468 | if info is None: 469 | raise ValueError('No series exists for category id: ' + str(category_id)) 470 | return info 471 | -------------------------------------------------------------------------------- /fredapi/tests/__init__.py: -------------------------------------------------------------------------------- 1 | """ this file is needed for python to consider this directory a module """ 2 | -------------------------------------------------------------------------------- /fredapi/tests/test_fred.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | import sys 3 | if sys.version_info[0] >= 3: 4 | unicode = str 5 | 6 | import io 7 | import unittest 8 | if sys.version_info < (3, 3): 9 | import mock # pylint: disable=import-error 10 | else: 11 | from unittest import mock # pylint: disable=import-error 12 | import textwrap 13 | import fredapi 14 | import fredapi.fred 15 | 16 | 17 | # Change here if you want to make actual calls to Fred 18 | # (https://api.stlouisfed.org/fred...) 19 | # Make sure you FRED_API_KEY is set up and internet works. 20 | fake_fred_call = True 21 | fred_api_key = 'secret' 22 | if not fake_fred_call: 23 | fred_api_key = fredapi.Fred().api_key 24 | 25 | 26 | class HTTPCall: 27 | """Encapsulates faked Fred call data.""" 28 | 29 | root_url = fredapi.Fred.root_url 30 | 31 | def __init__(self, rel_url, response=None, side_effect=None): 32 | """Construct HTTPCall from argument. 33 | 34 | Parameters: 35 | ----------- 36 | rel_url: relative url to the root url for the call. 37 | response: response to the call if any. 38 | side_effect: side_effect to the call if any. 39 | 40 | """ 41 | self.url = '{}/{}&api_key={}'.format(self.root_url, rel_url, 42 | fred_api_key) 43 | self.response = response 44 | self.side_effect = side_effect 45 | 46 | 47 | sp500_obs_call = HTTPCall('series/observations?series_id=SP500&{}&{}'. 48 | format('observation_start=2014-09-02', 49 | 'observation_end=2014-09-05'), 50 | response=textwrap.dedent('''\ 51 | 52 | 58 | 60 | 62 | 64 | 66 | ''')) 67 | search_call = HTTPCall('release/series?release_id=175&' + 68 | 'order_by=series_id&sort_order=asc', 69 | response=textwrap.dedent('''\ 70 | 71 | 74 | 81 | 88 | 95 | 96 | 97 | ''')) 98 | payems_info_call = HTTPCall('series?series_id=PAYEMS', 99 | response=textwrap.dedent('''\ 100 | 101 | 102 | 114 | ''')) 115 | 116 | 117 | class TestFred(unittest.TestCase): 118 | 119 | """Test fredapi.Fred class. 120 | 121 | See setUp() to configure the tests to make internent requests or fake. 122 | 123 | """ 124 | 125 | root_url = fredapi.Fred.root_url 126 | 127 | def setUp(self): 128 | """Set up test. 129 | 130 | If the FRED_API_KEY env variable is defined, we use it in the url to 131 | help with quick checks between what's expected and what's returned by 132 | Fred. 133 | 134 | Only go against Fred during tests if fake_fred_call variable is True. 135 | 136 | as results are subject to change and the tests should be runnable 137 | without an internet connection or a FRED api key so they can be 138 | run as part of automated continuous integration (e.g. travis-ci.org). 139 | 140 | """ 141 | self.fred = fredapi.Fred(api_key=fred_api_key, proxies=None) 142 | self.fake_fred_call = fake_fred_call 143 | self.__original_urlopen = fredapi.fred.urlopen 144 | 145 | def tearDown(self): 146 | """Cleanup.""" 147 | pass 148 | 149 | def prepare_urlopen(self, urlopen, http_response=None, side_effect=None): 150 | """Set urlopen to return http_response or the regular call.""" 151 | if self.fake_fred_call: 152 | if http_response: 153 | urlopen.return_value.read.return_value = http_response 154 | elif side_effect: 155 | urlopen.return_value.read.side_effect = side_effect 156 | else: 157 | urlopen.side_effect = self.__original_urlopen 158 | 159 | @mock.patch('fredapi.fred.urlopen') 160 | def test_get_series(self, urlopen): 161 | """Test retrieval of series for SP500.""" 162 | self.prepare_urlopen(urlopen, 163 | http_response=sp500_obs_call.response) 164 | serie = self.fred.get_series('SP500', observation_start='9/2/2014', 165 | observation_end='9/5/2014') 166 | urlopen.assert_called_with(sp500_obs_call.url) 167 | self.assertEqual(serie.loc['9/2/2014'], 2002.28) 168 | self.assertEqual(len(serie), 4) 169 | 170 | @mock.patch('fredapi.fred.urlopen') 171 | def test_get_series_info_payem(self, urlopen): 172 | """Test retrieval of get_series_info for PAYEMS.""" 173 | url = payems_info_call.url 174 | http_response = payems_info_call.response 175 | self.prepare_urlopen(urlopen, http_response=http_response) 176 | info = self.fred.get_series_info('PAYEMS') 177 | urlopen.assert_called_with(url) 178 | self.assertEqual(info['title'], 'All Employees: Total Nonfarm Payrolls') 179 | self.assertEqual(info['frequency'], 'Monthly') 180 | self.assertEqual(info['frequency_short'], 'M') 181 | 182 | @mock.patch('fredapi.fred.urlopen') 183 | def test_invalid_id_in_get_series(self, urlopen): 184 | """Test invalid series id in get_series.""" 185 | url = ('{}/series/observations?series_id=invalid&api_key={}'. 186 | format(self.root_url, fred_api_key)) 187 | # some of the argument cannot be mocked easily. 188 | error = textwrap.dedent('''\ 189 | 190 | \n\n\n\n 192 | ''') 193 | fp = io.StringIO(unicode(error)) 194 | side_effect = fredapi.fred.HTTPError(url, 400, '', '', fp) 195 | self.prepare_urlopen(urlopen, side_effect=side_effect) 196 | with self.assertRaises(ValueError): 197 | self.fred.get_series('invalid') 198 | urlopen.assert_called_with(url) 199 | 200 | @mock.patch('fredapi.fred.urlopen') 201 | def test_invalid_id_in_get_series_info(self, urlopen): 202 | """Test invalid series id in get_series_info.""" 203 | url = '{}/series?series_id=invalid&api_key={}'.format(self.root_url, 204 | fred_api_key) 205 | error_msg = 'Bad Request. The series does not exist.' 206 | # some of the argument cannot be mocked easily. 207 | xml_error = textwrap.dedent('''\ 208 | 209 | \n\n\n 210 | '''.format(error_msg)) 211 | fp = io.StringIO(unicode(xml_error)) 212 | side_effect = fredapi.fred.HTTPError(url, 400, 'Bad Request', '', fp) 213 | self.prepare_urlopen(urlopen, side_effect=side_effect) 214 | with self.assertRaises(ValueError) as context: 215 | self.fred.get_series_info('invalid') 216 | self.assertEqual(unicode(context.exception), error_msg) 217 | urlopen.assert_called_with(url) 218 | 219 | @mock.patch('fredapi.fred.urlopen') 220 | def test_invalid_kwarg_in_get_series(self, urlopen): 221 | """Test invalid keyword argument in call to get_series.""" 222 | url = '{}/series?series_id=invalid&api_key={}'.format(self.root_url, 223 | fred_api_key) 224 | side_effect = fredapi.fred.HTTPError(url, 400, '', '', sys.stderr) 225 | self.prepare_urlopen(urlopen, side_effect=side_effect) 226 | with self.assertRaises(ValueError) as context: 227 | self.fred.get_series('SP500', 228 | observation_start='invalid-datetime-str') 229 | self.assertFalse(urlopen.called) 230 | 231 | @unittest.skip('Not sure why this crashes in some environments, skipping') 232 | @mock.patch('fredapi.fred.urlopen') 233 | def test_search(self, urlopen): 234 | """Simple test to check retrieval of series info.""" 235 | self.prepare_urlopen(urlopen, http_response=search_call.response) 236 | pi_series = self.fred.search_by_release(175, limit=3, 237 | order_by='series_id', 238 | sort_order='asc') 239 | urlopen.assert_called_with(search_call.url) 240 | actual = str(pi_series[['popularity', 'observation_start', 241 | 'seasonal_adjustment_short']]) 242 | expected = textwrap.dedent('''\ 243 | popularity observation_start seasonal_adjustment_short 244 | series id 245 | PCPI01001 0 1969-01-01 NSA 246 | PCPI01003 0 1969-01-01 NSA 247 | PCPI01005 0 1969-01-01 NSA''') 248 | for aline, eline in zip(actual.split('\n'), expected.split('\n')): 249 | self.assertEqual(aline.strip(), eline.strip()) 250 | 251 | 252 | if __name__ == '__main__': 253 | unittest.main() 254 | -------------------------------------------------------------------------------- /fredapi/tests/test_with_proxies.py: -------------------------------------------------------------------------------- 1 | """ Created on 15/04/2024:: 2 | ------------- test_with_proxies.py ------------- 3 | 4 | **Authors**: L. Mingarelli 5 | """ 6 | import os 7 | import fredapi 8 | PROXIES = {'http': 'xxx', 9 | 'https': 'xxx'} 10 | 11 | fred = fredapi.Fred(api_key=os.environ['FRED_API_KEY'], proxies=PROXIES) 12 | 13 | data = fred.get_series('SP500') 14 | 15 | -------------------------------------------------------------------------------- /fredapi/version.py: -------------------------------------------------------------------------------- 1 | 2 | version = '0.5.2' 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pandas>=0.15 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from setuptools import setup 3 | version_str = open('fredapi/version.py').read().strip().split('=')[-1].strip(" '") 4 | 5 | requires = ['pandas'] 6 | 7 | # README = open('README.rst').read() 8 | # CHANGELOG = open('docs/changelog.rst').read() 9 | LONG_DESCRIPTION = open('DESCRIPTION.rst').read() 10 | 11 | setup( 12 | name="fredapi", 13 | version=version_str, 14 | url='https://github.com/mortada/fredapi', 15 | author='Mortada Mehyar', 16 | # author_email='', 17 | description="Python API for Federal Reserve Economic Data (FRED) from St. Louis Fed", 18 | long_description=LONG_DESCRIPTION, 19 | test_suite='fredapi.tests.test_fred', 20 | packages=['fredapi'], 21 | platforms=["Any"], 22 | install_requires=requires, 23 | classifiers=[ 24 | 'Development Status :: 4 - Beta', 25 | 'Environment :: Console', 26 | 'Operating System :: OS Independent', 27 | 'Intended Audience :: Science/Research', 28 | 'Programming Language :: Python', 29 | 'Programming Language :: Python :: 2', 30 | 'Programming Language :: Python :: 3', 31 | 'Programming Language :: Python :: 2.6', 32 | 'Programming Language :: Python :: 2.7', 33 | 'Programming Language :: Python :: 3.4', 34 | 'Programming Language :: Python :: 3.5', 35 | 'Programming Language :: Python :: 3.6', 36 | 'Topic :: Internet :: WWW/HTTP', 37 | 'Topic :: Software Development :: Libraries :: Python Modules', 38 | ], 39 | ) 40 | --------------------------------------------------------------------------------