前言
最近發現一個功能強大的繪圖工具庫cufflinks,其最吸引我的地方是內置了量化金融繪圖模塊,可以很方便地繪製K線和技術指標圖表。但遺憾的是,在網絡上並沒有找到cufflinks的參考手冊。雖然網絡上有一些介紹cufflinks的博客文章,但都沒有詳細介紹量化繪圖模塊的使用方法。
因此本蒟蒻參照cufflinks的github源碼,對cufflinks量化金融繪圖模塊的使用方法做出簡要的介紹,希望對您有些許幫助。
cufflinks介紹
cufflinks是對Python繪圖庫plotly的進一步封裝,是基於jupyter notebook的交互式繪圖工具,可以很方便地繪製各種交互式圖表,佈局優美,效果炫酷,操作方便,可以和pandas的數據類型無縫銜接。
cufflinks的量化金融繪圖模塊接收的金融交易數據爲,dataframe格式,index爲datetime類型,各列爲open、high、low、close、volume,如下:
使用方法
注意:目前cufflinks只能在jupyter notebook中使用,在其他的IDE中使用可能會無法 編譯執行。
因爲本蒟蒻水平有限,如有錯誤,歡迎批評指正。
筆者的環境:cufflinks 0.17.3、Python3.7 、Jupyter Notebook
更多信息可以參考cufflinks的源碼
安裝cufflinks:
pip install cufflinks
1.繪製基礎K線(蠟燭)圖
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
df=cf.datagen.ohlcv()#cufflinks提供的數據,也可以更改爲自定義數據
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.iplot()
效果圖:
2.添加趨勢線
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_trendline('2015-01-01','2015-04-10',on='close',text='趨勢線',textangle=0)#畫趨勢線,textangle設置文字角度
qf.iplot(up_color='red',down_color='green')
效果圖:
參數介紹(摘自源碼註釋):
"""
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on : string
Indicate the data series in which the
trendline should be based.
'close'
'high'
'low'
'open'
text : string
If passed, then an annotation will be added
to the trendline (at mid point)
kwargs:
from_strfmt : string
Defines the date formating in which
date0 and date1 are stated.
default: '%d%b%y'
to_strfmt : string
Defines the date formatting
to which it should be converted.
This should match the same format as the timeseries index.
default : '%Y-%m-%d'
"""
3.添加支撐線
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_support('2015-01-12',on='close',mode='toend',text='這是支持線')
qf.iplot()
參數介紹:
"""
Parameters:
date0 : string
The support line will be drawn at the 'y' level
value that corresponds to this date.
on : string
Indicate the data series in which the
support line should be based.
'close'
'high'
'low'
'open'
mode : string
Defines how the support/resistance will
be drawn
'starttoened' : (x0,x1)
'fromstart' : (x0,date)
'toend' : (date,x1)
text : string
If passed, then an annotation will be added
to the support line (at mid point)
kwargs:
from_strfmt : string
Defines the date formating in which
date0 and date1 are stated.
default: '%d%b%y'
to_strfmt : string
Defines the date formatting
to which it should be converted.
This should match the same format as the timeseries index.
default : '%Y-%m-%d'
"""
4.添加壓力線
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_resistance('2015-01-12',on='close',mode='fromstart',text='這是壓力線',textangle=30)
qf.iplot()
效果圖:
參數介紹:
與支撐線相似
5.添加註解
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_annotations({'2015-02-01':'我是註解'},fontcolor='red',fontsize=18,textangle=0)
qf.iplot()
效果圖:
"""
Parameters:
annotations : dict or list(dict,)
Annotations can be on the form form of
{'date' : 'text'}
and the text will automatically be placed at the
right level on the chart
or
A Plotly fully defined annotation
kwargs :
fontcolor : str
Text color for annotations
fontsize : int
Text size for annotations
textangle : int
Textt angle
See https://plot.ly/python/reference/#layout-annotations
for a complete list of valid parameters.
"""
6.添加交易量
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_volume()
qf.iplot(up_color='red',down_color='green')#可以設置主題顏色
效果圖:
參數介紹:
"""
Parameters:
colorchange : bool
If True then each volume bar will have a fill color
depending on if 'base' had a positive or negative
change compared to the previous value
If False then each volume bar will have a fill color
depending on if the volume data itself had a positive or negative
change compared to the previous value
column :string
Defines the data column name that contains the volume data.
Default: 'volume'
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs :
base : string
Defines the column which will define the
positive/negative changes (if colorchange=True).
Default = 'close'
up_color : string
Color for positive bars
down_color : string
Color for negative bars
"""
7.添加異同移動平均線MACD
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_macd()
qf.iplot()
效果圖:
參數介紹:
"""
Parameters:
fast_period : int
MACD Fast Period
slow_period : int
MACD Slow Period
signal_period : int
MACD Signal Period
column :string
Defines the data column name that contains the
data over which the study will be applied.
Default: 'close'
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs:
legendgroup : bool
If true, all legend items are grouped into a
single one
All formatting values available on iplot()
"""
8.添加簡單移動均線SMA
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_sma(periods=[10,30],color=['red','blue'])
qf.iplot()
參數介紹:
"""
Parameters:
periods : int or list(int)
Number of periods
column :string
Defines the data column name that contains the
data over which the study will be applied.
Default: 'close'
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs:
legendgroup : bool
If true, all legend items are grouped into a
single one
All formatting values available on iplot()
"""
9.添加EMA
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_ema(periods=[10,20])
qf.iplot()
效果圖:
參數介紹:
"""
Parameters:
periods : int or list(int)
Number of periods
column :string
Defines the data column name that contains the
data over which the study will be applied.
Default: 'close'
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs:
legendgroup : bool
If true, all legend items are grouped into a
single one
All formatting values available on iplot()
"""
10.添加RSI
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_rsi(periods=10)
qf.iplot()
效果圖:
參數介紹:
"""
Parameters:
periods : int or list(int)
Number of periods
rsi_upper : int
bounds [0,100]
Upper (overbought) level
rsi_lower : int
bounds [0,100]
Lower (oversold) level
showbands : boolean
If True, then the rsi_upper and
rsi_lower levels are displayed
column :string
Defines the data column name that contains the
data over which the study will be applied.
Default: 'close'
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs:
legendgroup : bool
If true, all legend items are grouped into a
single one
All formatting values available on iplot()
"""
11.添加布林線
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_bollinger_bands(periods=10)
qf.iplot()
效果圖:
參數介紹:
"""
Parameters:
periods : int or list(int)
Number of periods
boll_std : int
Number of standard deviations for
the bollinger upper and lower bands
fill : boolean
If True, then the innner area of the
bands will filled
column :string
Defines the data column name that contains the
data over which the study will be applied.
Default: 'close'
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs:
legendgroup : bool
If true, all legend items are grouped into a
single one
fillcolor : string
Color to be used for the fill color.
Example:
'rgba(62, 111, 176, .4)'
All formatting values available on iplot()
"""
12.添加順勢指標/商品通道指標CCI
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_cci(periods=[10,20])
qf.iplot()
效果圖:
參數介紹:
"""
Parameters:
periods : int or list(int)
Number of periods
cci_upper : int
Upper bands level
default : 100
cci_lower : int
Lower band level
default : -100
showbands : boolean
If True, then the cci_upper and
cci_lower levels are displayed
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs:
legendgroup : bool
If true, all legend items are grouped into a
single one
All formatting values available on iplot()
"""
13.添加平均趨向指數ADX
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_adx(periods=5)
qf.iplot()
效果圖:
參數介紹:
"""
Parameters:
periods : int or list(int)
Number of periods
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs:
legendgroup : bool
If true, all legend items are grouped into a
single one
All formatting values available on iplot()
"""
14.添加均幅指標ATR
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_atr(periods=5)
qf.iplot()
效果圖:
參數介紹:
"""
Parameters:
periods : int or list(int)
Number of periods
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs:
legendgroup : bool
If true, all legend items are grouped into a
single one
All formatting values available on iplot()
"""
15.添加趨向指標DMI
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_dmi(periods=5)
qf.iplot()
效果圖:
參數介紹:
"""
Parameters:
periods : int or list(int)
Number of periods
name : string
Name given to the study
str : string
Label factory for studies
The following wildcards can be used:
{name} : Name of the column
{study} : Name of the study
{period} : Period used
Examples:
'study: {study} - period: {period}'
kwargs:
legendgroup : bool
If true, all legend items are grouped into a
single one
All formatting values available on iplot()
"""
拓展內容
1.剔除非交易日期
當我們使用自己的數據繪圖時,其默認會把 非交易日也包含在圖中。例如下面從tushare中獲取數據:
import cufflinks as cf
import tushare as ts
cf.set_config_file(offline=True, world_readable=True)
df=ts.get_hist_data('000001',start='2020-04-15',end='2020-05-13')
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.iplot()
效果圖:
可以看到,繪製的圖像包含了非交易日。如果我們想要剔除這些非交易日,需要把代碼修改爲:
import cufflinks as cf
import tushare as ts
cf.set_config_file(offline=True, world_readable=True)
df=ts.get_hist_data('000001',start='2020-04-15',end='2020-05-13')
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
layout = dict(
xaxis=dict(
categoryorder="category ascending",#篩除非交易日
type='category')
)
qf.iplot(layout=layout)
效果圖:
可以看到,在添加了layout後,圖像底部多出了一個選擇橫座標範圍的小條。同時在layout中將xaxis的type設置爲‘category’便可以剔除非交易日了。
2.拋物轉向指標add_ptps報錯
除了上面介紹的方法外,cufflinks還有添加拋物轉向指標add_ptps(),但我測試的時候,該方法一直報錯。
import cufflinks as cf
cf.set_config_file(offline=True, world_readable=True)
df=cf.datagen.ohlcv()
qf=cf.QuantFig(df,title='cufflinks金融繪圖樣例',legend='top',name='QF')
qf.add_ptps()
qf.iplot()
錯誤最終指向:
提示說是計算過程中出現了None。
初步考察,應該是cufflinks的源碼的問題(如果不是還請大佬指出)
打開cufflinks中的ta.py文件
可以看到,在286行,其將某一單元的初值設置爲None,而該單元恰好是在報錯的位置出現的變量。
解決方法:註釋掉286行。