Created
August 24, 2019 23:00
-
-
Save janlukasschroeder/de8a603fd8dbcecb55869c04776f5e06 to your computer and use it in GitHub Desktop.
Insider Trading Tutorial - 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import xml.etree.ElementTree as ET | |
import re | |
import time | |
# Download the XML version of the filing. If it fails wait for 5, 10, 15, ... seconds and try again. | |
def download_xml (url, tries = 1): | |
try: | |
response = urllib.request.urlopen(url) | |
except: | |
print('Something went wrong. Wait for 5 seconds and try again.', tries) | |
if tries < 5: | |
time.sleep(5 * tries) | |
download_xml(url, tries + 1) | |
else: | |
# decode the response into a string | |
data = response.read().decode('utf-8') | |
# set up the regular expression extractoer in order to get the relevant part of the filing | |
matcher = re.compile('<\?xml.*ownershipDocument>', flags=re.MULTILINE|re.DOTALL) | |
matches = matcher.search(data) | |
# the first matching group is the extracted XML of interest | |
xml = matches.group(0) | |
# instantiate the XML object | |
root = ET.fromstring(xml) | |
print(url) | |
return root | |
# Calculate the total transaction amount in $ of a giving form 4 in XML | |
def calculate_transaction_amount (xml): | |
total = 0 | |
if xml is None: | |
return total | |
nonDerivativeTransactions = xml.findall("./nonDerivativeTable/nonDerivativeTransaction") | |
for t in nonDerivativeTransactions: | |
# D for disposed or A for acquired | |
action = t.find('./transactionAmounts/transactionAcquiredDisposedCode/value').text | |
# number of shares disposed/acquired | |
shares = t.find('./transactionAmounts/transactionShares/value').text | |
# price | |
priceRaw = t.find('./transactionAmounts/transactionPricePerShare/value') | |
price = 0 if priceRaw is None else priceRaw.text | |
# set prefix to -1 if derivatives were disposed. set prefix to 1 if derivates were acquired. | |
prefix = -1 if action == 'D' else 1 | |
# calculate transaction amount in $ | |
amount = prefix * float(shares) * float(price) | |
total += amount | |
return round(total, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment