Created
August 1, 2017 15:55
-
-
Save CyrusNuevoDia/d92e2c60b3aa51125bd431a96a82cf72 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 os | |
import csv | |
import json | |
import re | |
from datetime import datetime | |
from urllib.request import urlopen | |
from urllib.parse import urlencode | |
os.chdir(os.path.dirname(__file__)) | |
def cryptodata( | |
pair=None, | |
from_date=datetime(2000, 1, 1), | |
to_date=datetime.now(), | |
period=7200): | |
""" | |
pair: "BTC-ETH", "BTC-LTC", "USDT-ETH" | |
from_date: datetime(2012, 1, 1) # defaults to Jan 1, 2000 | |
to_date: datetime(2017, 6, 21) | |
period: 86400 (in seconds; minimum of 7200) | |
""" | |
if not pair: | |
raise TypeError("Expected pair to be a currency pair, got None") | |
match = re.match(r"^([A-Za-z]{1,4}).([A-Za-z]{1,4})$", pair) | |
if match is None: | |
raise ValueError(f"{pair} was not in the proper format") | |
currency_pair = "_".join((match.group(1), match.group(2))).upper() | |
start = datetime.timestamp(from_date) | |
end = datetime.timestamp(to_date) | |
formdata = urlencode({ | |
"command": "returnChartData", | |
"currencyPair": currency_pair, | |
"start": start, | |
"end": end, | |
"period": period | |
}) | |
req = urlopen("https://poloniex.com/public?" + formdata) | |
data = json.load(req) | |
if "error" in data: | |
raise ValueError(data["error"]) | |
return data | |
def data_to_csv(data, filename=None): | |
""" | |
data: from the cryptodata function | |
filename: "BTC_ETH_24h_all_time.csv" | |
""" | |
if not filename: | |
raise TypeError("Expected a filename, got None") | |
cols = list(data[0].keys()) | |
with open(os.path.join(os.getcwd(), filename), "w") as f: | |
w = csv.writer(f) | |
w.writerow(cols) | |
for datum in data: | |
w.writerow([datum[col] for col in cols]) | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment