| 1 |
|
| 2 |
"""Download all dividends in a particular date interval.""" |
| 3 |
|
| 4 |
__copyright__ = "Copyright (C) 2020 Martin Blais" |
| 5 |
__license__ = "GNU GPLv2" |
| 6 |
|
| 7 |
from datetime import date as Date |
| 8 |
from decimal import Decimal |
| 9 |
from typing import List, Tuple |
| 10 |
import argparse |
| 11 |
import csv |
| 12 |
import datetime |
| 13 |
import io |
| 14 |
import pprint |
| 15 |
|
| 16 |
import dateutil.parser |
| 17 |
import requests |
| 18 |
|
| 19 |
|
| 20 |
def download_dividends( |
| 21 |
instrument: str, start_date: Date, end_date: Date |
| 22 |
) -> List[Tuple[Date, Decimal]]: |
| 23 |
"""Download a list of dividends issued over a time interval.""" |
| 24 |
tim = datetime.time() |
| 25 |
payload = { |
| 26 |
"period1": str(int(datetime.datetime.combine(start_date, tim).timestamp())), |
| 27 |
"period2": str(int(datetime.datetime.combine(end_date, tim).timestamp())), |
| 28 |
"interval": "1d", |
| 29 |
"events": "div", |
| 30 |
"includeAdjustedClose": "true", |
| 31 |
} |
| 32 |
template = " https://query1.finance.yahoo.com/v7/finance/download/{ticker}" |
| 33 |
url = template.format(ticker=instrument) |
| 34 |
resp = requests.get(url, params=payload) |
| 35 |
if not resp.ok: |
| 36 |
raise ValueError("Error fetching dividends: {}".format(resp.text)) |
| 37 |
|
| 38 |
rows = iter(csv.reader(io.StringIO(resp.text))) |
| 39 |
header = next(rows) |
| 40 |
if header != ["Date", "Dividends"]: |
| 41 |
raise ValueError( |
| 42 |
"Error fetching dividends: " "invalid response format: {}".format(header) |
| 43 |
) |
| 44 |
|
| 45 |
dividends = [] |
| 46 |
for row in rows: |
| 47 |
date = datetime.datetime.strptime(row[0], "%Y-%m-%d").date() |
| 48 |
dividend = Decimal(row[1]) |
| 49 |
dividends.append((date, dividend)) |
| 50 |
return dividends |
| 51 |
|
| 52 |
|
| 53 |
def main(): |
| 54 |
"""Top-level function.""" |
| 55 |
today = datetime.date.today() |
| 56 |
parser = argparse.ArgumentParser(description=__doc__.strip()) |
| 57 |
parser.add_argument("instrument", help="Yahoo!Finance code for financial instrument.") |
| 58 |
parser.add_argument( |
| 59 |
"start", |
| 60 |
action="store", |
| 61 |
type=lambda x: dateutil.parser.parse(x).date(), |
| 62 |
default=today.replace(year=today.year - 1), |
| 63 |
help="Start date of interval. Default is one year ago.", |
| 64 |
) |
| 65 |
parser.add_argument( |
| 66 |
"end", |
| 67 |
action="store", |
| 68 |
type=lambda x: dateutil.parser.parse(x).date(), |
| 69 |
default=today, |
| 70 |
help="End date of interval. Default is today ago.", |
| 71 |
) |
| 72 |
|
| 73 |
args = parser.parse_args() |
| 74 |
|
| 75 |
dividends = download_dividends(args.instrument, args.start, args.end) |
| 76 |
pprint.pprint(dividends) |
| 77 |
|
| 78 |
|
| 79 |
if __name__ == "__main__": |
| 80 |
main() |