#!/usr/bin/env python3 # Fetch stock market data from stockdio.com import csv import requests def _print_err(x): print('[ERROR] ' + x) def read_csv_data(filename='depot.csv'): """Return a list of dictionaries for each row of a CSV file.""" dict_list = [] with open(filename, mode='r') as csv_file: # Avoid comments, lines with trailing '#' input_csv = csv.DictReader( filter(lambda row: not row.startswith('#'), csv_file)) for line in input_csv: dict_list.append(line) return dict_list def _stockdio_jdata2dict(j_data, exchange): output = {} for i in j_data['data']['prices']['values']: symbol = i[0] if exchange == 'FOREX': symbol = symbol[:3] quote = float(i[2]) if quote <= 0: _print_err('API quote ' + symbol + ' ' + str(quote)) raise ValueError() output[symbol] = quote return output def stockdio_prices(exchange='FOREX', symbols='USD/EUR;CHF/EUR'): """Query stockdio.com API getlatestprices. Return dictionary.""" apikey = 'YOURAPIKEY' apiurl = 'https://api.stockdio.com/' apipath = 'data/financial/prices/v1/getlatestprices?' stockdio_s = requests.Session() stockdio_s.params = {'app-key': apikey, 'stockExchange': exchange, 'symbols': symbols} response = stockdio_s.get(apiurl + apipath) if response.ok: return _stockdio_jdata2dict(response.json(), exchange) else: _print_err('API prices ' + exchange + ' ' + symbols) response.raise_for_status() def _get_fx(list): fx_str = '' for row in list: if row['Currency'] not in fx_str and row['Currency'] != 'EUR': fx_str += row['Currency'] + '/EUR;' fx_str = fx_str[:-1] fx_response = stockdio_prices('FOREX', fx_str) fx_response['EUR'] = 1 return fx_response def _get_quotes(list): quotes = {} exchanges = [] for row in list: if row['Exchange'] not in exchanges: exchanges.append(row['Exchange']) for ex in exchanges: symbols = [] for row in list: if row['Exchange'] == ex and row['Symbol'] not in symbols: symbols.append(row['Symbol']) symbol_str = ';'.join(symbols) quotes_response = stockdio_prices(ex, symbol_str) quotes.update(quotes_response) return quotes def get_depot_sums(list): fx = _get_fx(list) quotes = _get_quotes(list) sum_s = 0 sum_d = 0 print('symbol,quote,amount,fx') for row in list: amount = float(row['Amount']) print(row['Symbol'], quotes[row['Symbol']], amount, fx[row['Currency']], sep=',') val_eur = amount * quotes[row['Symbol']] * fx[row['Currency']] if row['Depot'] == 'S': sum_s += val_eur elif row['Depot'] == 'D': sum_d += val_eur return sum_s, sum_d def _ft2str(ft_input): return format(round(ft_input), ',d').replace(',', '.') def main(): csv = read_csv_data() depot_s, depot_d = get_depot_sums(csv) depot_total = depot_s + depot_d message_left = _ft2str(depot_d) message_right = _ft2str(depot_s) message_center = _ft2str(depot_total) print('Sum', message_left, message_right, message_center) if __name__ == '__main__': main()