├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE.txt ├── MANIFEST.in ├── README.MD ├── assets ├── 13F_Managers.PNG └── finsec_logo.png ├── finsec ├── __init__.py ├── base.py ├── filing.py └── version.py ├── requirements.txt ├── setup.py └── tests ├── __init__.py └── test_13f.py /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Python package 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - main 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | python-version: ["3.9", "3.10"] 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v4 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | - name: Install dependencies 23 | run: | 24 | pip install --upgrade pip 25 | pip install flake8 pytest 26 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 27 | - name: Lint with flake8 28 | run: | 29 | # stop the build if there are Python syntax errors or undefined names 30 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 31 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 32 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 33 | - name: Test with pytest 34 | run: | 35 | pytest 36 | deploy: 37 | runs-on: ubuntu-latest 38 | needs: build 39 | steps: 40 | - uses: actions/checkout@v2 41 | - name: Set up Python 42 | uses: actions/setup-python@v2 43 | with: 44 | python-version: '3.x' 45 | - name: Install dependencies 46 | run: | 47 | python -m pip install --upgrade pip 48 | pip install setuptools wheel twine 49 | - name: Build and publish 50 | env: 51 | TWINE_USERNAME: ${{ secrets.PYPI_USER }} 52 | TWINE_PASSWORD: ${{ secrets.PYPI_PASS }} 53 | run: | 54 | python setup.py sdist bdist_wheel 55 | twine upload dist/* --verbose -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .pytest_cache 3 | dist 4 | pypi_steps.txt 5 | finsec.egg-info 6 | venv 7 | main.py 8 | *.xlsx -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | # Include the license file 2 | include LICENSE.txt 3 | 4 | # Include the data files 5 | recursive-include data * -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | # finsec 2 | 3 | ## Download historical filing data directly from the United States (U.S.) Securities Exchange Commission (SEC). 4 | 5 | ![finsec_logo](assets/finsec_logo.png) 6 | 7 | > [!IMPORTANT] 8 | > **finsec** is **not** affiliated, endorsed, or vetted by the United. States. Securities Exchange Commission. It's an open-source tool that uses the SEC's publicly available APIs. This tool is intended for research and informational purposes only. It should not be used for making financial decisions. Always consult with a qualified financial advisor for investment guidance. 9 | **You should refer to SEC Edgar's website for more details ([here](https://www.sec.gov/os/accessing-edgar-data))** 10 | 11 | Python version 12 | PyPi version 13 | PyPi status 14 | PyPi downloads 15 | Star this repo 16 | 17 | [![Python package](https://github.com/git-shogg/finsec/actions/workflows/ci.yml/badge.svg)](https://github.com/git-shogg/finsec/actions/workflows/ci.yml) 18 | 19 | ## Blogs 20 | Check out the following blog post for a detailed tutorial on how `finsec` has been used to aid with analysing the performance of some of the world's most prestigious hedge funds: 21 |
[Unravelling investment fund manager strategies through 13f SEC filings](https://medium.com/@stephen.hogg.sh/unravelling-investment-fund-manager-strategies-through-13f-sec-filings-38dc030cf4c6).
22 | 23 | ## Quickstart 24 | ### Review 13F filings for Berkshire Hathaway CIK **0001067983** 25 | 26 | ```python 27 | import finsec 28 | filing = finsec.Filing('0001067983') # Optional declared user variable can be input here (e.g. declared_user="Joe Blog Joe.Blog@gmail.com") 29 | 30 | # Return the latest 13F reported holdings for Berkshire Hathaway. 31 | print(filing.latest_13f_filing) 32 | ``` 33 | **Output:** 34 | | | Name of issuer | Title of class | CUSIP | Share or principal type | Holding value | Share or principal amount count | 35 | |---:|:------------------------|:-----------------|:----------|:--------------------------|----------------:|----------------------------------:| 36 | | 0 | ACTIVISION BLIZZARD INC | COM | 00507V109 | SH | 4470946000 | 60141866 | 37 | | 1 | ALLY FINL INC | COM | 02005N100 | SH | 834901000 | 30000000 | 38 | | 2 | AMAZON COM INC | COM | 023135106 | SH | 1205258000 | 10666000 | 39 | 40 | *Note*: Using the `latest_13f_filing` function will return the the latest "simplified" version of the 13F Information Table, this works well in most instances... However, there are some who may want to have a more detailed breakdown of the filing. Such as, which investment manager was responsible for investing in the security and the voting authority type granted. This can be handled with the function `latest_13f_filing_detailed` (below). 41 | 42 | ```python 43 | # Return the latest detailed 13F reported holdings for Berkshire Hathaway. 44 | print(filing.latest_13f_filing_detailed) 45 | ``` 46 | **Output:** 47 | | | Name of issuer | Title of class | CUSIP | Holding value | Share or principal type | Share or principal amount count | Put or call | Investment discretion | Other manager | Voting authority sole count | Voting authority shared count | Voting authority none count | 48 | |---:|:------------------------|:-----------------|:----------|----------------:|:--------------------------|----------------------------------:|:--------------|:------------------------|:----------------|------------------------------:|--------------------------------:|------------------------------:| 49 | | 0 | ACTIVISION BLIZZARD INC | COM | 00507V109 | 1906458000 | SH | 25645116 | | DFND | 4,8,11 | 25645116 | 0 | 0 | 50 | | 1 | ACTIVISION BLIZZARD INC | COM | 00507V109 | 85095000 | SH | 1144672 | | DFND | 4,10 | 1144672 | 0 | 0 | 51 | | 2 | ACTIVISION BLIZZARD INC | COM | 00507V109 | 2479393000 | SH | 33352078 | | DFND | 4,11 | 33352078 | 0 | 0 | 52 | 53 | ```python 54 | # Return the latest 13F cover page details for Berkshire Hathaway. 55 | filing.latest_13f_filing_cover_page 56 | 57 | #Output 58 | {'filing_manager': 'Berkshire Hathaway Inc', 'business_address': '3555 Farnam Street, Omaha, NE, 68131', 'submission_type': '13F-HR', 'period_of_report': '09-30-2022', 'signature_name': 'Marc D. Hamburg', 'signature_title': 'Senior Vice President', 'signature_phone': '402-346-1400', 'signature_city': 'Omaha', 'signature_state': 'NE', 'signature_date': '11-14-2022', 'portfolio_value': 296096640000, 'count_holdings': 179} 59 | 60 | # Return the attributes of a specific 13F filing for the specified cik. In the below example we are looking to grab the cover page, full holdings table and simplified holdings table for Berkshire for Q2-2022 (Calendar Year). 61 | q2_cover_page, q2_holdings_table, q2_simplified_holdings_table = filing.get_a_13f_filing("Q2-2022") 62 | print(q2_cover_page) 63 | print(q2_holdings_table) 64 | print(q2_simplified_holdings_table) 65 | 66 | # Return the json object containing all 13F filings that are stored as part of the filing object (note this includes everything we've searched for so far). 67 | filing.filings 68 | 69 | # Write filings to excel. Record everything we've looked at to Excel. 70 | filing.filings_to_excel 71 | ``` 72 | 73 | # Installation 74 | Install `finsec` using `pip`: 75 | ``` {.sourceCode .bash} 76 | $ pip install finsec 77 | ``` 78 | 79 | # Requirements 80 | - [Python](https://www.python.org) \>= 3.7+ 81 | - [Pandas](https://github.com/pydata/pandas) \>= 1.3.5 82 | - [lxml](https://pypi.org/project/lxml) \>= 4.8.0 83 | - [requests](http://docs.python-requests.org/en/master) \>= 2.27.1 84 | - [beautifulsoup4](https://pypi.org/project/beautifulsoup4) \>= 4.11.1 85 | 86 | *Note* that the above packages will be downloaded automatically using `pip`. 87 | 88 | # Author 89 | **Stephen Hogg** 90 | 91 | 92 | 94 | 95 | 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 | 151 | -------------------------------------------------------------------------------- /assets/13F_Managers.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/git-shogg/finsec/e64e34a9179f3d7930982c0d6790aeb9456739d9/assets/13F_Managers.PNG -------------------------------------------------------------------------------- /assets/finsec_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/git-shogg/finsec/e64e34a9179f3d7930982c0d6790aeb9456739d9/assets/finsec_logo.png -------------------------------------------------------------------------------- /finsec/__init__.py: -------------------------------------------------------------------------------- 1 | # 13f_py - 2 | 3 | from . import version 4 | from .filing import Filing 5 | 6 | __version__ = version.version 7 | __author__ = "Stephen Hogg" 8 | 9 | __all__ = ['filing'] 10 | -------------------------------------------------------------------------------- /finsec/base.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup as bs 3 | from datetime import datetime 4 | import pandas as pd 5 | import pdb 6 | import os 7 | import time 8 | from io import StringIO 9 | 10 | _BASE_URL_ = 'https://www.sec.gov' 11 | _13F_SEARCH_URL_ = 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK={}&type=13F-HR&count=100' 12 | _REQ_HEADERS_ = { 13 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36', 14 | 'Accept-Encoding': 'gzip, deflate, br', 15 | 'HOST': 'www.sec.gov', 16 | } 17 | 18 | class FilingBase(): 19 | def __init__(self, cik, declared_user=None): 20 | if declared_user is not None: 21 | _REQ_HEADERS_["User-Agent"] = declared_user+";"+_REQ_HEADERS_["User-Agent"] 22 | self.cik = self._validate_cik(cik) 23 | self.manager = None 24 | self._13f_filings = None 25 | self._13f_amendment_filings = None 26 | 27 | self.filings = {} 28 | 29 | def _validate_cik(self, cik:str): 30 | """Check if CIK is 10 digit string.""" 31 | if not (isinstance(cik, str) and len(cik) == 10 and cik.isdigit()): 32 | raise Exception("""Invalid CIK Provided""") 33 | return cik 34 | 35 | def _get_last_100_13f_filings_url(self): 36 | """Searches the last 13F-HR and 13F-HR/A filings. Returns a 13f_filings variable and 13f_amendment_filings variable""" 37 | if self._13f_filings is not None or self._13f_amendment_filings is not None: 38 | return 39 | 40 | webpage = requests.get(_13F_SEARCH_URL_.format(self.cik),headers=_REQ_HEADERS_) 41 | soup = bs(webpage.text,"html.parser") 42 | results_table = soup.find(lambda table: table.has_attr('summary') and table['summary']=="Results") 43 | results_table_df = pd.read_html(StringIO(str(results_table)))[0] 44 | 45 | url_endings = [] 46 | url_link_col = results_table_df.columns.get_loc("Format") 47 | for row in results_table.find_all('tr'): 48 | tds = row.find_all('td') 49 | try: 50 | url_endings.append(tds[url_link_col].find('a')['href']) 51 | except: 52 | pass 53 | results_table_df['url'] = url_endings 54 | # self._last_100_13f_filings_url = list(zip(url_endings, filing_dates, filing_types)) 55 | self._13f_filings = results_table_df[results_table_df['Filings']=="13F-HR"].reset_index(drop=True) 56 | self._13f_amendment_filings = results_table_df[results_table_df['Filings']=="13F-HR/A"].reset_index(drop=True) 57 | 58 | return self._13f_filings, self._13f_amendment_filings 59 | 60 | def _13f_amendment_filings_period_of_filings(self): 61 | """This function finds the actual 'period of report' for the 13f amendment filings (this function needs to open the filing url for each and every 13f amendment identified). This is required to understand which particular report is being amended.""" 62 | def _pandas_apply_func(x): 63 | webpage = requests.get(_BASE_URL_ + x['url'],headers=_REQ_HEADERS_) 64 | soup = bs(webpage.text,"html.parser") 65 | period_of_report_div = soup.find('div', text='Period of Report') 66 | period_of_report_date = period_of_report_div.find_next_sibling('div', class_='info').text 67 | datetime_obj = datetime.strptime(period_of_report_date, '%Y-%m-%d') 68 | release_qtr = datetime_obj.month//3 69 | year = datetime_obj.year 70 | time.sleep(0.2) 71 | return pd.Series([period_of_report_date, "Q{}-{}".format(release_qtr, year)]) 72 | self._13f_amendment_filings[['Period of Report','Period of Report Quarter Year']] = self._13f_amendment_filings.apply(_pandas_apply_func,axis=1) 73 | return self._13f_amendment_filings 74 | 75 | def _get_bs4_text(self, bs4_obj): 76 | try: 77 | return bs4_obj.text 78 | except: 79 | return "N/A" 80 | 81 | def _recent_qtr_year(self, datetime_o:str): 82 | """Function estimates 'period of report' in a Quarter Year format (calendar year) based upon filing date.""" 83 | datetime_obj = datetime.strptime(datetime_o, '%Y-%m-%d') 84 | quarter_dict = {1:4, 2:1, 3:2, 4:3} # Every statement released is for the previous quarter. 85 | release_qtr = quarter_dict[(datetime_obj.month - 1)//3 + 1] 86 | if release_qtr == 4: # If the release quarter is 4 it means that the date of report release is in the new calendar year. 87 | year = datetime_obj.year - 1 88 | else: 89 | year = datetime_obj.year 90 | 91 | return "Q{}-{}".format(release_qtr, year) 92 | 93 | def _qtr_year(self, date:str): 94 | """Function directly converts period of report date string to Quarter Year format (calendar year).""" 95 | datetime_obj = datetime.strptime(date, '%Y-%m-%d') 96 | release_qtr = datetime_obj.month//3 97 | year = datetime_obj.year 98 | return "Q{}-{}".format(release_qtr, year) 99 | 100 | def _parse_13f_url(self, url:str, date:str): 101 | response = requests.get(_BASE_URL_+url, headers=_REQ_HEADERS_) 102 | soup = bs(response.text, "html.parser") 103 | import re 104 | url_primary_html_document = soup.find_all('a', attrs = {'href': re.compile('xml')})[0]['href'] # Html primary doc is 1st int the list, this contains the detail on whether the dollars listed are nearest dollar or thousand dollar. 105 | url_primary_document = soup.find_all('a', attrs = {'href': re.compile('xml')})[1]['href'] # XML Primary doc is always 2nd in the list. 106 | url_list_document = soup.find_all('a', attrs = {'href': re.compile('xml')})[3]['href'] # xml list is always 4th in the list. 107 | 108 | response = requests.get(_BASE_URL_+url_primary_html_document, headers=_REQ_HEADERS_) 109 | primary_html_doc = bs(response.text, "xml") 110 | 111 | response = requests.get(_BASE_URL_+url_primary_document, headers=_REQ_HEADERS_) 112 | primary_doc = bs(response.text, "xml") 113 | 114 | response = requests.get(_BASE_URL_ + url_list_document, headers=_REQ_HEADERS_) 115 | list_doc = bs(response.text, "xml") 116 | 117 | # Check if the documentation is to the nearest dollar or thousand dollars. This new reporting rule came into effect in 2023 (reference: https://www.sec.gov/info/edgar/specifications/form13fxmltechspec) 118 | datetime_obj = datetime.strptime(date, '%Y-%m-%d') 119 | if datetime_obj.year < 2023: 120 | dollar_value_multiplier = 1000 121 | elif datetime_obj.year > 2023: 122 | dollar_value_multiplier = 1 123 | else: 124 | temp_list = primary_html_doc.findAll(text=re.compile('nearest dollar')) 125 | if len(temp_list)>0: 126 | dollar_value_multiplier = 1 127 | else: 128 | dollar_value_multiplier = 1000 129 | 130 | # Get primary doc detail 131 | filing_manager = self._get_bs4_text(primary_doc.find("filingManager").find("name")) 132 | business_address = self._get_bs4_text(primary_doc.find("street1")) + ", " + self._get_bs4_text(primary_doc.find("city")) + ", " + self._get_bs4_text(primary_doc.find("stateOrCountry")) + ", " + self._get_bs4_text(primary_doc.find("zipCode")) 133 | submission_type = self._get_bs4_text(primary_doc.find("submissionType")) 134 | period_of_report = self._get_bs4_text(primary_doc.find("periodOfReport")) 135 | 136 | if self._get_bs4_text(primary_doc.find("amendmentInfo")) != 'N/A': # Check if it is an amendment type filing. 137 | amendment_type = self._get_bs4_text(primary_doc.find("amendmentInfo").find("amendmentType")) 138 | else: 139 | amendment_type = 'N/A' 140 | 141 | signature_name = self._get_bs4_text(primary_doc.find("signatureBlock").find("name")) 142 | signature_title = self._get_bs4_text(primary_doc.find("signatureBlock").find("title")) 143 | signature_phone = self._get_bs4_text(primary_doc.find("signatureBlock").find("phone")) 144 | signature_city = self._get_bs4_text(primary_doc.find("signatureBlock").find("city")) 145 | signature_state = self._get_bs4_text(primary_doc.find("signatureBlock").find("stateOrCountry")) 146 | signature_date = self._get_bs4_text(primary_doc.find("signatureBlock").find("signatureDate")) 147 | 148 | portfolio_value = int(self._get_bs4_text(primary_doc.find("summaryPage").find("tableValueTotal"))) * dollar_value_multiplier 149 | count_holdings = int(self._get_bs4_text(primary_doc.find("summaryPage").find("tableEntryTotal"))) 150 | 151 | filing_cover_page = { 152 | "filing_manager":filing_manager, 153 | "business_address":business_address, 154 | "submission_type":submission_type, 155 | "period_of_report":period_of_report, 156 | "signature_name":signature_name, 157 | "signature_title":signature_title, 158 | "signature_phone":signature_phone, 159 | "signature_city":signature_city, 160 | "signature_state":signature_state, 161 | "signature_date":signature_date, 162 | "amendment_type":amendment_type, 163 | "portfolio_value":portfolio_value, 164 | "count_holdings":count_holdings, 165 | "filing_amended":False # Used to record if this instance of the filing has been amended in any way. 166 | } 167 | 168 | # Get list doc detail 169 | list_of_holdings = list_doc.findAll("infoTable") 170 | result = [] 171 | for each_holding in list_of_holdings: 172 | name_of_issuer = self._get_bs4_text(each_holding.find("nameOfIssuer")) 173 | title_of_class = self._get_bs4_text(each_holding.find("titleOfClass")) 174 | cusip = self._get_bs4_text(each_holding.find("cusip")) 175 | holding_value = int(each_holding.find("value").text) * dollar_value_multiplier 176 | share_or_principal_amount = self._get_bs4_text(each_holding.find("shrsOrPrnAmt").find("sshPrnamtType")) 177 | share_or_principal_amount_count = int(each_holding.find("shrsOrPrnAmt").find("sshPrnamt").text) 178 | # put_or_call = each_holding.find("SOMETHING").text 179 | investment_discretion = self._get_bs4_text(each_holding.find("investmentDiscretion")) 180 | other_manager = self._get_bs4_text(each_holding.find("otherManager")) 181 | voting_authority_share_or_principal_amount_count_sole = int(each_holding.find("votingAuthority").find("Sole").text) 182 | voting_authority_share_or_principal_amount_count_shared = int(each_holding.find("votingAuthority").find("Shared").text) 183 | voting_authority_share_or_principal_amount_count_none = int(each_holding.find("votingAuthority").find("None").text) 184 | 185 | result.append({"Name of issuer":name_of_issuer, "Title of class":title_of_class, "CUSIP":cusip,"Holding value":holding_value,"Share or principal type":share_or_principal_amount,"Share or principal amount count":share_or_principal_amount_count,"Put or call":None, "Investment discretion":investment_discretion, "Other manager":other_manager, "Voting authority sole count":voting_authority_share_or_principal_amount_count_sole, "Voting authority shared count":voting_authority_share_or_principal_amount_count_shared, "Voting authority none count":voting_authority_share_or_principal_amount_count_none}) 186 | 187 | holdings_table = pd.DataFrame.from_dict(result) 188 | 189 | simplified_columns = ['Name of issuer', 'Title of class', 'CUSIP', 'Share or principal type', 'Put or call','Holding value', 'Share or principal amount count'] 190 | holdings_table_dropped_na = holdings_table[simplified_columns].dropna(axis=1) 191 | simplified_holdings_table = holdings_table_dropped_na.groupby(holdings_table_dropped_na.columns[:-2].to_list(), sort=False,as_index=False).sum() 192 | 193 | if self.manager == None: 194 | self.manager = filing_cover_page.get('filing_manager') 195 | 196 | return filing_cover_page, holdings_table, simplified_holdings_table 197 | 198 | def _apply_amendments(self, qtr_year_str:str, original_cover_page:dict, original_holdings_table:pd.DataFrame, original_simplified_holdings_table: pd.DataFrame): 199 | self._13f_amendment_filings_period_of_filings() 200 | select_amendment_filings = self._13f_amendment_filings[self._13f_amendment_filings['Period of Report Quarter Year'] == qtr_year_str].iloc[::-1] # Check for matching amendments and reverse the order of the list so amendments can be made chronologically. 201 | 202 | # Start by setting the output variables, this ensures that if no amendment filings are found, these can be returned as is, unaltered. 203 | output_cover_page = original_cover_page # Set as original cover page to begin with 204 | output_holdings_table = original_holdings_table 205 | output_simplified_holdings_table = original_simplified_holdings_table 206 | 207 | if len(select_amendment_filings) > 0: 208 | for index, row in select_amendment_filings.iterrows(): 209 | a_cover_page, a_holdings_table, a_simplified_holdings_table = self._parse_13f_url(row['url'], row['Filing Date']) 210 | if a_cover_page["amendment_type"] == "NEW HOLDINGS": 211 | 212 | output_cover_page['portfolio_value'] = original_cover_page['portfolio_value'] + a_cover_page['portfolio_value'] 213 | output_cover_page['count_holdings'] = original_cover_page['count_holdings'] + a_cover_page['count_holdings'] 214 | 215 | # original_holdings_table = original_holdings_table.append(a_holdings_table, ignore_index=True) 216 | output_holdings_table = pd.concat([original_holdings_table,a_holdings_table],ignore_index=True) 217 | # original_simplified_holdings_table = original_simplified_holdings_table.append(a_simplified_holdings_table, ignore_index=True) 218 | output_simplified_holdings_table = pd.concat([original_simplified_holdings_table,a_simplified_holdings_table], ignore_index=True) 219 | output_cover_page['filing_amended'] = True 220 | else: # If it is a not a "New Holdings" filing type, simply overwrite the entirety of the previous filing. 221 | output_cover_page = a_cover_page 222 | output_holdings_table = a_holdings_table 223 | output_simplified_holdings_table = a_simplified_holdings_table 224 | output_cover_page['filing_amended'] = True 225 | return output_cover_page, output_holdings_table, output_simplified_holdings_table 226 | 227 | def convert_filings_to_excel(self, simplified:bool = True, inc_cover_page_tabs:bool = False): 228 | """Outputs existing 'self.filings' dictionary to excel. Note that this will overwrite any existing files that may be present.""" 229 | table_type = "Simplified Holdings Table" if simplified == True else "Holdings Table" 230 | if len(self.filings)>0: 231 | if os.path.exists('{}.xlsx'.format(self.cik)): 232 | os.remove('{}.xlsx'.format(self.cik)) 233 | with pd.ExcelWriter('{}.xlsx'.format(self.cik)) as writer: 234 | for qtr_year in self.filings: 235 | if inc_cover_page_tabs == True: 236 | pd.DataFrame.from_dict(self.filings[qtr_year]['Cover Page'],orient='index').to_excel(writer,sheet_name="{}_cover_pg".format(qtr_year)) 237 | pd.read_json(self.filings[qtr_year][table_type]).to_excel(writer,sheet_name="{}_holdings".format(qtr_year)) 238 | return 239 | 240 | def get_latest_13f_filing(self, simplified:bool = True, amend_filing:bool = True): 241 | """Returns the latest 13F-HR filing.""" 242 | self._get_last_100_13f_filings_url() 243 | # Grab latest 13F-HR filing, do not grab amendment filings ("13F-HR/A") 244 | url = self._13f_filings['url'][0] 245 | filing_date = self._13f_filings['Filing Date'][0] 246 | 247 | latest_13f_cover_page, latest_holdings_table, latest_simplified_holdings_table = self._parse_13f_url(url,filing_date) 248 | 249 | qtr_year_str = self._recent_qtr_year(self._13f_filings['Filing Date'][0]) 250 | if amend_filing and len(self._13f_amendment_filings) > 0: 251 | latest_13f_cover_page, latest_holdings_table, latest_simplified_holdings_table = self._apply_amendments(qtr_year_str, latest_13f_cover_page, latest_holdings_table, latest_simplified_holdings_table) 252 | 253 | self.filings.update({ 254 | qtr_year_str:{ 255 | "Cover Page":latest_13f_cover_page, 256 | "Period of Report":latest_13f_cover_page['period_of_report'], 257 | "Holdings Table":latest_holdings_table.to_json(), 258 | "Simplified Holdings Table":latest_simplified_holdings_table.to_json(), 259 | "Fund Value":latest_13f_cover_page['portfolio_value'], 260 | "Holdings Count":latest_13f_cover_page['count_holdings'], 261 | "Simplified Holdings Count":len(latest_simplified_holdings_table), 262 | "Latest 13F":True, 263 | "Amended Filing":amend_filing 264 | }}) 265 | 266 | if simplified==True: 267 | return latest_simplified_holdings_table 268 | else: 269 | return latest_holdings_table 270 | 271 | def get_latest_13f_filing_cover_page(self): 272 | """Returns the latest 13F-HR filing cover page.""" 273 | latest_qtr_year = [x for x in self.filings.keys() if self.filings[x]['Latest 13F']] 274 | if len(latest_qtr_year) >0: 275 | return self.filings[latest_qtr_year[0]]['Cover Page'] 276 | else: 277 | self.get_latest_13f_filing() 278 | latest_qtr_year = [x for x in self.filings.keys() if self.filings[x]['Latest 13F']] 279 | return self.filings[latest_qtr_year[0]]['Cover Page'] 280 | 281 | def get_latest_13f_value(self): 282 | """Returns the latest 13F-HR value of fund value""" 283 | latest_qtr_year = [x for x in self.filings.keys() if self.filings[x]['Latest 13F']] 284 | if len(latest_qtr_year) >0: 285 | return self.filings[latest_qtr_year[0]]['Fund Value'] 286 | else: 287 | self.get_latest_13f_filing() 288 | latest_qtr_year = [x for x in self.filings.keys() if self.filings[x]['Latest 13F']] 289 | return self.filings[latest_qtr_year[0]]['Fund Value'] 290 | 291 | def get_latest_13f_num_holdings(self, holdings_type:str = 'Simplified Holdings Count'): 292 | """Returns the latest 13F-HR number of holdings""" 293 | latest_qtr_year = [x for x in self.filings.keys() if self.filings[x]['Latest 13F']] 294 | if len(latest_qtr_year) >0: 295 | return self.filings[latest_qtr_year[0]][holdings_type] 296 | else: 297 | self.get_latest_13f_filing() 298 | latest_qtr_year = [x for x in self.filings.keys() if self.filings[x]['Latest 13F']] 299 | return self.filings[latest_qtr_year[0]][holdings_type] 300 | 301 | def get_13f_filing(self, cal_qtr_year:str, amend_filing:bool=True): 302 | """Returns the requested 13F-HR filing.""" 303 | self._get_last_100_13f_filings_url() 304 | if len(self.filings) != 0: 305 | if cal_qtr_year in self.filings: 306 | return self.filings[cal_qtr_year]["Cover Page"], pd.read_json(self.filings[cal_qtr_year]["Holdings Table"]), pd.read_json(self.filings[cal_qtr_year]["Simplified Holdings Table"]) 307 | filing_url_date = None 308 | latest_13_f_filing = False 309 | for index, row in self._13f_filings.iterrows(): 310 | datetime_obj = datetime.strptime(row['Filing Date'], '%Y-%m-%d') 311 | quarter_dict = {1:4, 2:1, 3:2, 4:3} # Every statement released is for the previous quarter. 312 | release_qtr = quarter_dict[(datetime_obj.month - 1)//3 + 1] 313 | year = datetime_obj.year 314 | if release_qtr == 4: # Anything released in the previous quarter will have a year of last year (e.g. report is for 31st Dec 2022, yet report was released on the 1st Feb 2023) 315 | year = year - 1 316 | 317 | if "Q{}-{}".format(release_qtr, year) == cal_qtr_year: 318 | filing_url_date = row['Filing Date'] 319 | filing_url = row['url'] 320 | if index == 0: 321 | latest_13_f_filing = True 322 | 323 | 324 | if filing_url_date == None: 325 | raise Exception("No filing could be found for the period {}".format(cal_qtr_year)) 326 | 327 | cover_page, holdings_table, simplified_holdings_table = self._parse_13f_url(filing_url, filing_url_date) 328 | 329 | qtr_year_str = self._recent_qtr_year(filing_url_date) 330 | if amend_filing and len(self._13f_amendment_filings)>0: 331 | cover_page, holdings_table, simplified_holdings_table = self._apply_amendments(qtr_year_str, cover_page, holdings_table, simplified_holdings_table) 332 | 333 | self.filings.update({ 334 | cal_qtr_year:{ 335 | "Cover Page":cover_page, 336 | "Period of Report":cover_page['period_of_report'], 337 | "Holdings Table":holdings_table.to_json(), 338 | "Simplified Holdings Table":simplified_holdings_table.to_json(), 339 | "Fund Value":cover_page['portfolio_value'], 340 | "Holdings Count":cover_page['count_holdings'], 341 | "Simplified Holdings Count":len(simplified_holdings_table), 342 | "Latest 13F":latest_13_f_filing}}) 343 | 344 | return cover_page, holdings_table, simplified_holdings_table 345 | 346 | 347 | -------------------------------------------------------------------------------- /finsec/filing.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup as bs 3 | 4 | from .base import FilingBase 5 | 6 | class Filing(FilingBase): 7 | 8 | def get_a_13f_filing(self, qtr_year:str, amend_filing:bool = True): 9 | return self.get_13f_filing(qtr_year, amend_filing) 10 | 11 | def filings_to_excel(self, simplified:bool = True, inc_cover_page_tabs:bool = False): 12 | return self.convert_filings_to_excel(simplified, inc_cover_page_tabs) 13 | 14 | def latest_13f_filing(self, simplified:bool = True, amend_filing:bool = True): 15 | return self.get_latest_13f_filing(simplified, amend_filing) 16 | 17 | @property 18 | def latest_13f_portfolio_value(self): 19 | return self.get_latest_13f_value() 20 | 21 | @property 22 | def latest_13f_count_holdings(self): 23 | return self.get_latest_13f_num_holdings() 24 | 25 | def latest_13f_filing_detailed(self): 26 | return self.get_latest_13f_filing(simplified=False, amend_filing=True) 27 | 28 | @property 29 | def latest_13f_filing_cover_page(self): 30 | return self.get_latest_13f_filing_cover_page() 31 | -------------------------------------------------------------------------------- /finsec/version.py: -------------------------------------------------------------------------------- 1 | version = "0.0.12" 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4==4.11.1 2 | pandas==2.2.0 3 | requests==2.27.1 4 | lxml==4.8.0 5 | openpyxl==3.0.9 6 | html5lib==1.1 7 | numpy>=1.22.4 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | import io 3 | from os import path 4 | 5 | # Version 6 | version = "unknown" 7 | with open("finsec/version.py") as f: 8 | line = f.read().strip() 9 | version = line.replace("version = ", "").replace('"', '') 10 | 11 | # Long Description (i.e. README file) 12 | here = path.abspath(path.dirname(__file__)) 13 | with io.open(path.join(here, 'README.MD'), encoding='utf-8') as f: 14 | long_description = f.read() 15 | 16 | # Setup 17 | setuptools.setup( 18 | name='finsec', 19 | version=version, 20 | description='Download historical filing data directly from the United States Securities Exchange Commission (SEC)!', 21 | long_description=long_description, 22 | long_description_content_type='text/markdown', 23 | # url='https://github.com/git-shogg/yfinance', 24 | author='Stephen Hogg', 25 | author_email='stephen.hogg.sh@gmail.com', 26 | license='Apache', 27 | classifiers=[ 28 | 'License :: OSI Approved :: Apache Software License', 29 | # 'Development Status :: 3 - Alpha', 30 | 'Development Status :: 4 - Beta', 31 | #'Development Status :: 5 - Production/Stable', 32 | 'Operating System :: OS Independent', 33 | 'Intended Audience :: Developers', 34 | 'Topic :: Office/Business :: Financial', 35 | 'Topic :: Office/Business :: Financial :: Investment', 36 | 'Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator', 37 | 'Topic :: Software Development :: Libraries', 38 | 'Topic :: Software Development :: Libraries :: Python Modules', 39 | 40 | 'Programming Language :: Python :: 3.10', 41 | ], 42 | platforms=['any'], 43 | keywords='pandas, sec, securities exchange commission, finance, pandas datareader', 44 | # packages=find_packages(exclude=['contrib', 'docs', 'tests', 'examples']), 45 | install_requires=['beautifulsoup4>=4.11.1', 46 | 'pandas>=1.3.5', 47 | 'requests>=2.27.1', 48 | 'lxml>=4.8.0', 49 | 'openpyxl>=3.0.9', 50 | ], 51 | 52 | packages=["finsec"] 53 | # entry_points={ 54 | # 'console_scripts': [ 55 | # 'sample=sample:main', 56 | # ], 57 | # }, 58 | ) -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/git-shogg/finsec/e64e34a9179f3d7930982c0d6790aeb9456739d9/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_13f.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests for 13F functionality 3 | """ 4 | 5 | import pandas as pd 6 | import finsec 7 | 8 | 9 | class Test: 10 | def setup_class(self): 11 | self.cik = "0001067983" 12 | self.filing = finsec.Filing(self.cik, declared_user="finsec package finsec@gmail.com") 13 | 14 | def test_cik(self): 15 | assert self.filing.cik == self.cik 16 | 17 | def test_latest_13f_filing(self): 18 | df = self.filing.latest_13f_filing() 19 | assert isinstance(df, pd.DataFrame) 20 | assert len(self.filing.filings) > 0 21 | 22 | def test_latest_13f_filing_detailed(self): 23 | df = self.filing.latest_13f_filing_detailed() 24 | assert isinstance(df, pd.DataFrame) 25 | 26 | def test_latest_13f_filing_cover_page(self): 27 | result = self.filing.latest_13f_filing_cover_page 28 | assert isinstance(result, dict) 29 | 30 | def test_latest_13f_portfolio_value(self): 31 | portfolio_value = self.filing.latest_13f_portfolio_value 32 | assert isinstance(portfolio_value, int) 33 | 34 | def test_latest_13f_count_holdings(self): 35 | holdings_count = self.filing.latest_13f_count_holdings 36 | assert isinstance(holdings_count, int) 37 | 38 | def test_get_a_13f_filing(self): 39 | cover_page, holdings_table, simplified_holdings_table = ( 40 | self.filing.get_a_13f_filing("Q2-2022") 41 | ) 42 | assert isinstance(cover_page, dict) 43 | assert isinstance(holdings_table, pd.DataFrame) 44 | assert isinstance(simplified_holdings_table, pd.DataFrame) 45 | --------------------------------------------------------------------------------