New version version 0.2
[curcy.git] / curcy-update
1 #!/usr/bin/env python3
2
3 import logging
4
5 REFERENCE='EUR'
6
7 def get_yahoo_file():
8     from urllib import request
9     req = request.Request(
10         'http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote;currency=true?view=basic&format=json',
11         headers={'User-Agent': 'curcy'})
12     uo = request.urlopen(req)
13     httpdata = uo.read()
14     uo.close()
15     return httpdata.decode('UTF-8')
16
17 def get_yahoo_raw():
18     import json
19     yahoo_file = get_yahoo_file()
20     #file('curency.json', 'w').write(yahoo_file)
21     #yahoo_file = open('curency.json').read()
22     #print yahoo_file
23     yahoo_file = yahoo_file.replace(',\n]', ']')
24     return json.loads(yahoo_file)
25
26 def parse_yahoo(json_obj):
27     list = json_obj['list']
28     for res in list['resources']:
29         quote = res['resource']['fields']
30         if not quote['name'].startswith('USD/') or len(quote['name']) != 7:
31             logging.debug('Invalid name quote name %s', quote['name'])
32             continue
33         #yield quote['name']
34         yield quote['name'][4:], float(quote['price'])
35
36 def get_yahoo_quotes():
37     quotes = {}
38     for name, value in parse_yahoo(get_yahoo_raw()):
39         quotes[name] = value
40
41     ref_usd = quotes[REFERENCE]
42     for cur in quotes.keys():
43         quotes[cur] /= ref_usd
44     assert len(quotes) > 0
45     quotes['USD'] = 1/ref_usd
46     # add historical european values
47     if REFERENCE == 'EUR':
48         quotes['ATS'] = 0.07267283416785971236
49         quotes['BEF'] = 0.02478935247732393982
50         quotes['DEM'] = 0.51129188119621848524
51         quotes['ESP'] = 0.00601012104383782289
52         quotes['FIM'] = 0.16818792646151103396
53         quotes['FRF'] = 0.15244901723741037903
54         quotes['GRD'] = 0.00293470286133528980
55         quotes['IEP'] = 1.26973807842918162841
56         quotes['ITL'] = 0.00051645689908948648
57         quotes['LUF'] = 0.02478935247732393982
58         quotes['NLG'] = 0.45378021609013890212
59         quotes['PTE'] = 0.00498797897068065961
60         quotes['SIT'] = 0.00417292605575029210
61         quotes['VAL'] = 0.00051645689908948648
62     else:
63         logging.warning('reference must be EUR to get legacy currencies exchange rates.')
64         logging.warning('WARNING: ATS BEF DEM ESP FIM FRF GRD IEP ITL LUF NLG PTE SIT VAL will be unavailable!')
65
66     return quotes
67
68 def main():
69     from optparse import OptionParser
70     parser = OptionParser('%prog [options]')
71     parser.add_option('-v', '--verbose',
72         help='Display informational messages',
73         action='store_true', dest='verbose', default=False)
74     parser.add_option('-l', '--listonly',
75         help='Just list the supported currencies',
76         action='store_true', dest='listonly', default=False)
77     parser.add_option('-a', '--aggressive',
78         help='Deprecaded.',
79         action='store_true', dest='aggressive', default=False)
80     parser.add_option('--target',
81         help='Set target filename. Defaults to %default',
82         dest='target_file', default='/var/currencies')
83     options, args = parser.parse_args()
84     
85     if options.verbose:
86         loglevel = logging.DEBUG
87     else:
88         loglevel = logging.INFO
89     logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s %(message)s')
90
91     target_file = open(options.target_file, 'w')
92     for cur, value in get_yahoo_quotes().items():
93         print(cur, value, file=target_file)
94
95 if __name__ == '__main__':
96     main()
97