Fixed database inversion (1/X) !
[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     assert len(quotes) > 10
41     quotes['USD'] = 1
42
43     ref_usd = quotes[REFERENCE]
44     for cur in quotes.keys():
45         quotes[cur] = ref_usd / quotes[cur]
46
47     # add historical european values
48     if REFERENCE == 'EUR':
49         quotes['ATS'] = 0.07267283416785971236
50         quotes['BEF'] = 0.02478935247732393982
51         quotes['DEM'] = 0.51129188119621848524
52         quotes['ESP'] = 0.00601012104383782289
53         quotes['FIM'] = 0.16818792646151103396
54         quotes['FRF'] = 0.15244901723741037903
55         quotes['GRD'] = 0.00293470286133528980
56         quotes['IEP'] = 1.26973807842918162841
57         quotes['ITL'] = 0.00051645689908948648
58         quotes['LUF'] = 0.02478935247732393982
59         quotes['NLG'] = 0.45378021609013890212
60         quotes['PTE'] = 0.00498797897068065961
61         quotes['SIT'] = 0.00417292605575029210
62         quotes['VAL'] = 0.00051645689908948648
63     else:
64         logging.warning('reference must be EUR to get legacy currencies exchange rates.')
65         logging.warning('WARNING: ATS BEF DEM ESP FIM FRF GRD IEP ITL LUF NLG PTE SIT VAL will be unavailable!')
66
67     return quotes
68
69 def main():
70     from optparse import OptionParser
71     parser = OptionParser('%prog [options]')
72     parser.add_option('-v', '--verbose',
73         help='Display informational messages',
74         action='store_true', dest='verbose', default=False)
75     parser.add_option('-l', '--listonly',
76         help='Just list the supported currencies',
77         action='store_true', dest='listonly', default=False)
78     parser.add_option('-a', '--aggressive',
79         help='Deprecaded.',
80         action='store_true', dest='aggressive', default=False)
81     parser.add_option('--target',
82         help='Set target filename. Defaults to %default',
83         dest='target_file', default='/var/currencies')
84     options, args = parser.parse_args()
85     
86     if options.verbose:
87         loglevel = logging.DEBUG
88     else:
89         loglevel = logging.INFO
90     logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s %(message)s')
91
92     target_file = open(options.target_file, 'w')
93     for cur, value in get_yahoo_quotes().items():
94         print(cur, value, file=target_file)
95
96 if __name__ == '__main__':
97     main()
98