import csv
import requests
import datetime
import pandas as pd
import seaborn
import matplotlib.pyplot as plt
import numpy as np
import math
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing, cross_validation, svm
# Pretty print the JSON
import uuid
from IPython.display import display_javascript, display_html, display
import json
class RenderJSON(object):
def __init__(self, json_data):
if isinstance(json_data, dict):
self.json_str = json.dumps(json_data)
else:
self.json_str = json_data
self.uuid = str(uuid.uuid4())
def _ipython_display_(self):
display_html('<div id="{}" style="height: 600px; width:100%;"></div>'.format(self.uuid), raw=True)
display_javascript("""
require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
document.getElementById('%s').appendChild(renderjson(%s))
});
""" % (self.uuid, self.json_str), raw=True)
#Defining Price Data From Crypto cryptocompare.com
def price(symbol, comparison_symbols=['BTC'], exchange=''):
url = 'https://min-api.cryptocompare.com/data/price?fsym={}&tsyms={}'\
.format(symbol.upper(), ','.join(comparison_symbols).upper())
if exchange:
url += '&e={}'.format(exchange)
page = requests.get(url)
data = page.json()
return data
# Displaying Currency
price('LTC', exchange='binance')
# Pulling Historical Minute Data From cryptocompare.com API
def minute_price_historical(symbol, comparison_symbol, limit, aggregate, exchange=''):
url = 'https://min-api.cryptocompare.com/data/histominute?fsym={}&tsym={}&limit={}&aggregate={}'\
.format(symbol.upper(), comparison_symbol.upper(), limit, aggregate)
if exchange:
url += '&e={}'.format(exchange)
page = requests.get(url)
data = page.json()['Data']
df = pd.DataFrame(data)
df['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time]
return df
time_delta = 1 # Bar width in minutes
df = minute_price_historical('BTC', 'USD', 9999, time_delta)
df = df[['close','high','low','open','time','volumefrom','volumeto']]
#print('Max length = %s' % len(df))
#print('Max time = %s' % (df.timestamp.max() - df.timestamp.min()))
time_delta = 1 # Bar width in minutes
ts = minute_price_historical('BTC', 'USD', 9999, time_delta)
ts = ts[['close','high','low','open','time','volumefrom','volumeto','timestamp']]
#print('Max length = %s' % len(df))
#print('Max time = %s' % (df.timestamp.max() - df.timestamp.min()))
# Plotting Pulled Data
plt.title('BTC vs USD')
plt.xlabel('Time')
plt.ylabel('Price')
plt.plot(ts.timestamp, df.close)
plt.xticks(rotation=45)
plt.show()
#df.to_csv('btc_minute.csv')
# Displaying Data
df.tail()
#forecast_out = int(30) # predicting 21 minutes into future
forecast_out = int(math.ceil(0.01*len(df)))
df['Prediction'] = df[['close']].shift(-forecast_out) # label column with data shifted 21 units up
#df.to_csv('prediction')
X = np.array(df.drop(['Prediction'], 1))
X = preprocessing.scale(X)
X_forecast = X[-forecast_out:] # set X_forecast equal to last 21
X = X[:-forecast_out] # remove last 21 from X
y = np.array(df['Prediction'])
y = y[:-forecast_out]
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size = 0.2)
# Training
clf = LinearRegression()
clf.fit(X_train,y_train)
# Testing
confidence = clf.score(X_test, y_test)
print("confidence: ", confidence)
forecast_prediction = clf.predict(X_forecast)
forecast_prediction
pre = pd.DataFrame(forecast_prediction)
pre.columns = ['prediction']
# Date magic for our dataframe
now = datetime.datetime.now()
time = pd.date_range(now,periods=21, freq='1min')
time
minute = pd.DataFrame(time)
#start = pre.index.min().date()
#end = pre.index.max().date() + pd.Timedelta(1, 'D')
#pre.reindex(pd.date_range(start, end, freq='T', closed='left')).fillna(method='ffill')
pre.tail()
#date = pd.date_range(start='4/1/2018', end='4/1/2018', freq='m')
#date = pd.DataFrame(date)
#date.columns = ['date']
#date
minute.tail()
prediction = pd.concat([pre,minute], axis=1)
prediction.columns = ['prediction','time']
sell = prediction.prediction.max()
prediction.tail()
#buy = prediction.prediction.min()
#signal =(buy,sell)
#signal
#stuff = pd.concat([buy,sell], axis=1)
#stuff
#gains = sell/buy
#gains
confidence
plt.suptitle('21 Minute Future Prediction BTC vs USD',fontsize=17)
#plt.title('Potential Gains %s' % gains, fontsize=10)
plt.xlabel('Time')
plt.ylabel('Price')
plt.plot(prediction.time, prediction.prediction)
plt.xticks(rotation=45)
plt.show()
time_delta = 1 # Line width in minutes
ts = minute_price_historical('BTC', 'USD', 9999, time_delta)
ts = ts[['close','high','low','open','time','volumefrom','volumeto','timestamp']]
ts = ts.tail(19)
plt.title('Past BTC vs USD Data', fontsize=17)
plt.xlabel('Time')
plt.ylabel('Price')
plt.plot(ts.timestamp, ts.close)
plt.xticks(rotation=45)
plt.show()