#!/usr/bin/env python # Fetch stock market data from alphavantage.co import requests import csv import time import string import random def _print_err(x): print('[ERROR] ' + x) def key_generator(size=16, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def api_timing(sleeptime=12.1): # free API key allows up to 5 requests per minute, # 500 requests per day # so we sleep for 12.1 sec to avoid errors time.sleep(sleeptime) def get_av_quote(symbol): apikey = key_generator() apiurl = 'https://www.alphavantage.co/query?' apifunction = 'GLOBAL_QUOTE' payload = {'function': apifunction, 'symbol': symbol, 'apikey': apikey} my_response = requests.get(apiurl, params=payload) quote = False if (my_response.ok): j_data = my_response.json() if 'Global Quote' in j_data: quote = float(j_data['Global Quote']['05. price']) api_timing() return quote def get_av_fx(from_currency, to_currency='EUR'): apikey = key_generator() apiurl = 'https://www.alphavantage.co/query?' apifunction = 'CURRENCY_EXCHANGE_RATE' payload = {'function': apifunction, 'from_currency': from_currency, 'to_currency': to_currency, 'apikey': apikey} my_response = requests.get(apiurl, params=payload) fx_rate = False if (my_response.ok): j_data = my_response.json() if 'Realtime Currency Exchange Rate' in j_data: fx_rate = float( j_data['Realtime Currency Exchange Rate']['5. Exchange Rate']) api_timing() return fx_rate def get_share_data(depot): worth = 0 with open('depot.csv', mode='r') as csv_file: input_csv = csv.DictReader(csv_file, delimiter=';') for row in input_csv: if row['Depot'] == depot: share_quote = get_av_quote(row['Code']) if share_quote: if row['Currency'] == 'EUR': fx_factor = 1 else: fx_factor = get_av_fx(row['Currency']) worth += share_quote * fx_factor * float(row['Amount']) else: _print_err('fetching ' + row['Company']) return(False) return(worth) def main(): depot_o = get_share_data('O') depot_s = get_share_data('S') depot_d = get_share_data('U') if depot_o and depot_s and depot_d: depot_total = depot_o + depot_s + depot_d print(round(depot_total), 2) else: _print_err('API failed') if __name__ == '__main__': main()