In [1]:
from os import sys
sys.version
Out[1]:
'3.4.3 |Anaconda 2.3.0 (64-bit)| (default, Mar  6 2015, 12:06:10) [MSC v.1600 64 bit (AMD64)]'

从BitcoinChars.com获取coinbase的数据

In [5]:
import pandas as pd
import io
import requests

url = 'http://api.bitcoincharts.com/v1/trades.csv?symbol=coinbaseUSD'

raw = requests.get(url).content

data = pd.read_csv(io.StringIO(raw.decode('utf-8')), names=['price', 'amount'], index_col=0)
data.index = pd.to_datetime((data.index.values * 1e9).astype(int))

data.head()
Out[5]:
price amount
1970-01-01 00:00:01.453394389 407.20 0.049590
1970-01-01 00:00:01.453394389 407.16 0.010410
1970-01-01 00:00:01.453394389 407.06 0.340000
1970-01-01 00:00:01.453394389 407.06 0.010000
1970-01-01 00:00:01.453394388 407.22 0.070668

Bollinger Bands指标,需要收盘价作为输入参数。由于比特币是24小时,没有开市闭市的概念,所以这里使用每十分钟作为一个周期,计算开拍,最高,最低和收盘价:

In [3]:
dt = data['price'].resample('10Min',how='ohlc')
dt.head()
Out[3]:
open high low close
1969-12-31 23:50:00 404.49 425.1 403.37 404.88

载入talib,计算Bollinger Bands,参数设置:

In [4]:
import talib
from talib import MA_Type
bbands = talib.BBANDS(dt['close'].values,20,2,2, matype=MA_Type.SMA)
bbands  = pd.DataFrame({'upper':bbands[0], 'middle': bbands[1], 'lower': bbands[2]}, index=dt.index)
bbands.tail()
Out[4]:
lower middle upper
2016-01-03 22:20:00 425.441851 428.3050 431.168149
2016-01-03 22:30:00 425.406062 428.3585 431.310938
2016-01-03 22:40:00 425.422706 428.6150 431.807294
2016-01-03 22:50:00 425.752549 428.8590 431.965451
2016-01-03 23:00:00 425.787460 428.9445 432.101540
In [5]:
import cufflinks as cf
from plotly.graph_objs import *
import plotly.plotly as py


cf.set_config_file(world_readable=True,offline=False, theme='ggplot')
figure = dt.iplot(kind='candle', asFigure = True )
cf.datagen.lines(1)
upper_line = Scatter(
    x = bbands.index,
    y = bbands.upper,
    name = 'upper',
    marker= dict(
        color='rgba(50, 171, 96, 1.0)'  
    )
)

middle_line = Scatter(
    x = bbands.index,
    y = bbands.middle,
    name = 'middle',
    marker= dict(
        color='rgba(55, 128, 191, 1.0)'
    )
)

lower_line = Scatter(
    x = bbands.index,
    y = bbands.lower,
    name = 'lower',
    marker= dict(
        color='rgba(255, 153, 51, 1.0)'
    )
)

figure['data'].extend([upper_line, middle_line, lower_line])
_ = py.iplot(figure, filename='talib/BBANDS')

Plotly会把javascript代码插入到notebook中,导致文件10+K增大到10+M,所以这段代码只是把绘制出来但不显示,同时上传到Plot.ly。

Increasing, Decreasing, upper, middle, lower