In [59]:
%matplotlib inline
from datetime import datetime, timedelta
from pandas import Index
from pandas.io.data import DataReader
from pandas.io.parsers import read_csv
import matplotlib.pyplot as plt
import requests
FIN_SERVICE_PROVIDER = 'yahoo'
PAST_DAYS = 60
# SYMBOL = ['IBM', 'AAPL']
SYMBOL = ['USD', 'EUR']
# today
t1 = datetime.now()
# two months later
t2 = t1 - timedelta(days=PAST_DAYS)
df1 = DataReader(SYMBOL[0], FIN_SERVICE_PROVIDER , t2, t1)
df2 = DataReader(SYMBOL[1], FIN_SERVICE_PROVIDER , t2, t1)
from datetime import datetime
print('Today {}'.format(datetime.now()))
In [60]:
df1.head()
Out[60]:
In [61]:
df2.head()
Out[61]:
In [62]:
plt.figure(1)
plt.subplot(211)
plt.title(SYMBOL[0])
plt.xlabel('days')
plt.ylabel('close val.')
plt.plot(df1['Close'])
plt.figure(2)
plt.subplot(211)
plt.title(SYMBOL[1])
plt.xlabel('days')
plt.ylabel('close val.')
plt.plot(df2['Close'])
Out[62]:
In [63]:
BIT_COIN_CSV_URL = 'http://www.quandl.com/api/v1/datasets/BCHARTS/KRAKENEUR.csv'
bcdf = read_csv(BIT_COIN_CSV_URL)
bcdf = bcdf[bcdf['Date']> t2.strftime("%Y-%m-%d")]
#bcdf = bcdf.iloc[::-1]
bcdf = bcdf.sort(['Date'], ascending=[True])
# reindexing
bcdf.index = Index(range(0, len(bcdf)))
In [64]:
bcdf.tail()
Out[64]:
In [65]:
plt.title("BitCoin")
plt.xlabel('days')
plt.ylabel('close val.(EUR)')
# mean line.
plt.axhline(bcdf['Close'].mean(), color='green', linewidth=1)
plt.axhline(bcdf['Close'].max(), color='red', linewidth=1)
plt.plot(bcdf['Close'])
Out[65]:
In [66]:
bcdf['Close'].mean()
Out[66]:
In [67]:
bcdf['Close'].var()
Out[67]:
In [68]:
fig = plt.figure()
ax1 = fig.add_subplot(1,3,1)
ax1.set_title(SYMBOL[0])
# ax1.title(SYMBOL[0])
ax1 = df1.boxplot(column='Close', return_type='axes')
ax2 = fig.add_subplot(1,3,2)
# ax2.plt.title(SYMBOL[1])
ax2.set_title(SYMBOL[1])
ax2 = df2.boxplot(column='Close', return_type='axes')
ax3 = fig.add_subplot(1,3,3)
# ax3.plt.title(SYMBOL[1])
ax3.set_title('Bit Coin')
ax3 = bcdf.boxplot(column='Close', return_type='axes')
In [69]:
REAL_TIME_VALE_API = 'http://api.coindesk.com/v1/bpi/currentprice.json'
# REAL_TIME_VALE_API = "http://btc.blockr.io/api/v1/coin/info"
r = requests.get(REAL_TIME_VALE_API)
cur_value = 1
if r.status_code == 200:
_j = r.json()['bpi']['EUR']
cur_value = float(_j['rate'])
print("Real time value {} {}".format(_j['rate'], _j['symbol']))
Price per coin: €208.87 This is the value in Euro I invested in bitcoin.
In [70]:
price_x_coin = 208.87
gain= float(cur_value) - float(price_x_coin)
print("Gain {}".format(gain))
print("{}%".format(gain*100/price_x_coin))
In [71]:
X = [ [x] for x in bcdf.index]
y = bcdf['Close']
from sklearn.neighbors import KNeighborsRegressor
neigh = KNeighborsRegressor(n_neighbors=5)
neigh.fit(X, list(y.values))
Y = [list(neigh.predict([[i]]))[0] for i in range(len(X))]
plt.title("Predicted BitCoin value")
plt.xlabel('days')
plt.ylabel('close val.(EUR)')
plt.plot(Y)
Out[71]:
In [72]:
errors = [ Yi-yi for Yi, yi in zip(Y, y)]
plt.plot(errors)
Out[72]:
In [73]:
import numpy as np
print("Error mean: {} ".format(np.mean(errors)))
In [74]:
print("Tomorrow's predicted closing value {}".format(neigh.predict([[60]])))
In [75]:
def trend(row):
if row.Open > row.Close:
return '-'
elif row.Open < row.Close:
return '+'
return '='
bcdf['Trend'] = bcdf.apply(trend, axis=1)
bcdf.tail()
Out[75]:
In [76]:
from __future__ import division
bcdf['Sma'] = 0
PERIOD_NUM = -20
bcdf_small = bcdf[PERIOD_NUM:]
bcdf_small.Sma = [sum(bcdf_small['Close'][0:i+1]) /(i+1) for i,_ in enumerate(bcdf_small.Close)]
In [77]:
bcdf_small.tail(10)
Out[77]:
In [78]:
plt.title("Simple Moving Avarage")
plt.xlabel('period(days)')
plt.plot(bcdf_small['Sma'], label='Sma')
plt.plot(bcdf_small['Close'], label='Close')
plt.legend()
Out[78]:
In [ ]:
In [ ]: