Last active
August 31, 2018 01:53
-
-
Save psiofxt/a4592cfd2c89a2e991acea9fb7dc9249 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import aiohttp | |
import aiofiles | |
import json | |
from datetime import datetime, timedelta | |
async def fetch(url): | |
async with aiohttp.ClientSession() as session: | |
async with session.get(url) as response: | |
return await response.json() | |
async def open_file(filename): | |
async with aiofiles.open(filename, mode='r') as f: | |
return await f.read() | |
def date_generator(from_date, to_date): | |
curr = from_date | |
while curr <= to_date: | |
yield curr | |
curr += timedelta(days=1) | |
async def price_writer(currency, fiat): | |
pair = fiat + '_' + currency | |
response = await fetch( | |
'https://min-api.cryptocompare.com/' | |
'data/histoday?fsym={}&tsym={}&allData=true'.format(currency, fiat) | |
) | |
price_data = response['Data'] | |
sorted_data = [ | |
{ | |
datetime.utcfromtimestamp(data['time']).strftime('%Y-%m-%d'): | |
data for data in price_data | |
} | |
] | |
async with aiofiles.open('{}.json'.format(pair), mode='w') as f: | |
await f.write(json.dumps(sorted_data, sort_keys=True, indent=4)) | |
print("Wrote data for pair {}_{}".format(currency, fiat)) | |
async def price_getter(currency, fiat, from_date, to_date): | |
pair = fiat + '_' + currency | |
price_list = await (open_file('{}.json'.format(pair))) | |
price_data = json.loads(price_list) | |
try: | |
prices = [price_data[0][d.strftime('%Y-%m-%d')] | |
for d in date_generator(datetime.utcfromtimestamp(from_date), | |
datetime.utcfromtimestamp(to_date))] | |
except ValueError: | |
return [] | |
except KeyError: | |
return [] | |
return prices | |
async def run(): | |
currencies = ['ETH', 'BTC'] | |
fiats = ['USD', 'AUD', 'JPY'] | |
for currency in currencies: | |
for fiat in fiats: | |
await price_writer(currency, fiat) | |
prices = await price_getter('ETH', 'USD', 1535328000, 1535328000) | |
print(prices) | |
if __name__ == '__main__': | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(run()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment