量化投资之路 之 可视化

可视化部分

《量化交易》阿布@著 笔记

Matplotlib seaborn

# 子图
plt.subplots(nrows=2,ncols=2,figsize(14,10))
# 蜡烛图
from mpl_finance import mpl_finance as mpf
import matplotlib.pyplot as plt

import matplotlib.dates as dates
from abupy import ABuSymbolPd
tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)
tsla_part_df=tsla_df[:30]
fig,ax=plt.subplots(figsize=(14,7))
qutotes=[]
for index,(d,o,c,h,l) in enumerate(zip(tsla_part_df.index,tsla_part_df.open,tsla_part_df.close,
                                       tsla_part_df.high,tsla_part_df.low)):

    d=dates.date2num(d)
    val=(d,o,c,h,l)
    qutotes.append(val)
mpf.candlestick_ochl(ax,qutotes,width=0.6,colorup='red',colordown='green')
ax.autoscale_view()

ax.xaxis_date()
for label in ax.get_xticklabels():
            label.set_rotation(90)
            label.set_horizontalalignment('right')
plt.show()

Bokeh

https://blog.csdn.net/tichimi3375/article/details/82458845

使用pandas可视化数据

# 收益与波动情况
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates
import pandas as pd
from abupy import ABuSymbolPd
tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)


tsla_df_copy=tsla_df.copy()
tsla_df_copy['return']=np.log(tsla_df['close']/tsla_df['close']).shift(1)
# tsla_df_copy['mov_std']=pd.rolling_std(tsla_df_copy['return'],window=20,center=False)*np.sqrt(20)
tsla_df_copy['mov_std']=tsla_df_copy['return'].rolling(20).std()*np.sqrt(20)

tsla_df_copy['std_ewm']=tsla_df_copy['return'].ewm(span=20,min_periods=20,adjust=True).std()*np.sqrt(20)
tsla_df_copy[['close','mov_std','std_ewm','return']].plot(subplots=True,grid=True)

plt.show()

均线绘制


import matplotlib.pyplot as plt
from abupy import ABuSymbolPd

tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)
tsla_df.close.plot()
tsla_df.close.rolling(20).mean().plot()
tsla_df.close.rolling(60).mean().plot()
tsla_df.close.rolling(90).mean().plot()

plt.legend(['close','30 mv','60 mv','90 mv'],loc='best')
plt.show()


统计图形

# 各种统计图形
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates
from abupy import ABuSymbolPd
tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)

low_to_high_df=tsla_df.iloc[tsla_df[(tsla_df.close>tsla_df.open ) & (tsla_df.key != tsla_df.shape[0]-1)].key.values+1]
change_ceil_floor=np.where(low_to_high_df['p_change']>0,np.ceil(low_to_high_df['p_change']),np.floor(low_to_high_df['p_change']))
change_ceil_floor=pd.Series(change_ceil_floor)
_,axs=plt.subplots(nrows=2,ncols=2,figsize=(12,10))
change_ceil_floor.value_counts().plot(kind='bar',ax=axs[0][0])# 竖直柱状图
change_ceil_floor.value_counts().plot(kind='barh',ax=axs[0][1])#水平柱状图
change_ceil_floor.value_counts().plot(kind='kde',ax=axs[1][0])# 概率密度图
change_ceil_floor.value_counts().plot(kind='pie',ax=axs[1][1])# 饼图
plt.show()

Seaborn可视化数据

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates
import seaborn as sns
from abupy import ABuSymbolPd
tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)
#直方图 概率密度图
sns.distplot(tsla_df.p_change,bins=80)
# 箱型图
sns.boxplot(x='date_week',y='p_change',data=tsla_df)
# 相关性及概率密度分布
sns.jointplot(tsla_df.high,tsla_df.low)
# 热力图
#sns.heatmap()
plt.show()

可视化量化策略的交易区间和卖出原因

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates
from abupy import ABuSymbolPd
tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)

def plot_demo(axs=None,just_series=False):
    drawer=plt if axs is None else axs
    if not just_series:
        # 绿色
        drawer.plot(tsla_df.close.index,tsla_df.close.values+10,c='g')
        drawer.plot(tsla_df.close.index.to_list(),(tsla_df.close.values+20).to_list(),c='b')
    plt.xlabel('time')
    plt.ylabel('close')
    plt.title('TSLA CLOSE')
    plt.grid(True)


def plot_trade(buy_date,sell_date):
    # 画出交易区间
    start=tsla_df[tsla_df.index == buy_date].key.values[0] # 开始
    end=tsla_df[tsla_df.index == sell_date].key.values[0] # 结束
    plot_demo(just_series=True)
    # alpha 透明度
    plt.fill_between(tsla_df.index,0,tsla_df['close'],color='blue',alpha=0.08)
    if tsla_df['close'][end]< tsla_df['close'][start]:
        # 赔钱显示绿色
        plt.fill_between(tsla_df.index[start:end], 0, tsla_df['close'][start:end], color='green', alpha=0.38)
        is_win=False
    else:
		# 赚钱显示红色
        plt.fill_between(tsla_df.index[start:end],0,tsla_df['close'][start:end],color='red',alpha=0.38)
        is_win=True
    # 设置y轴的显示范围
    plt.ylim(np.min(tsla_df['close'])-5,np.max(tsla_df['close'])+5)
    plt.legend(['close'],loc='best')
    return is_win


# plot_trade('2018-7-2','2018-09-05')
# plt.show()
def plot_trade_with_annotate(buy_date,sell_date,annotate):
    # 卖出原因
    is_win=plot_trade(buy_date,sell_date)
    plt.annotate(annotate,xy=(sell_date,tsla_df['close'].asof(sell_date)),arrowprops=dict(facecolor='yellow'),
                 horizontalalignment='left',verticalalignment='top')

plot_trade_with_annotate('2018-7-2','2018-09-05',annotate='sell for money')
plt.show()

标准化两个股票观察周期

import matplotlib.pyplot as plt
from abupy import ABuSymbolPd
tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)
goo_df=ABuSymbolPd.make_kl_df('usGOOG',n_folds=2)

def plot_two_stock(tsla,goog,axs=None):
    drawer=plt if axs is None else axs
    drawer.plot(tsla,c='r')
    drawer.plot(goog,c='g')
    drawer.grid(True)
    drawer.legend(['tsla','google'],loc='best')
# plot_two_stock(tsla_df.close,goo_df.close)
# plt.title('tsla and google')
# plt.xlabel('time')
# plt.ylabel('close')

def two_mean_list(one,two,type_look='look_max'):
    one_mean=one.mean()
    two_mean=two.mean()
    if type_look=='look_max':# 向较大的均值看齐
        one,two=(one,one_mean/two_mean*two) if one_mean > two_mean else (one * two_mean/one_mean,two)
    elif type_look=='look_min':
        one, two = (one * two_mean / one_mean, two)if one_mean > two_mean else (one, one_mean / two_mean * two)
    return one,two

def regular_std(group):
    # z-score规范化, 也是零均值规范化
    return (group-group.mean())/group.std()

def regular_mm(group):
    # 最大-最小规范化
    return (group - group.min()) /(group.max()-group.min())

_,axs=plt.subplots(nrows=2,ncols=2,figsize=(14,10))
drawer=axs[0][0]
plot_two_stock(regular_std(tsla_df.close),regular_std(goo_df.close),drawer)
drawer.set_title('(group - group.mean)/group.std')
drawer=axs[0][1]
plot_two_stock(regular_mm(tsla_df.close),regular_mm(goo_df.close),drawer)
drawer.set_title('(group - group.mean)/group.std')
drawer=axs[1][0]
one,two=two_mean_list(tsla_df.close,goo_df.close,type_look='look_max')
plot_two_stock(one,two,drawer)
drawer.set_title('two_mean_list look_max')

drawer=axs[1][1]
one,two=two_mean_list(tsla_df.close,goo_df.close,type_look='look_min')
plot_two_stock(one,two,drawer)
drawer.set_title('two_mean_list look_min')

plt.show()

副轴生成

import matplotlib.pyplot as plt
from abupy import ABuSymbolPd
tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)
goo_df=ABuSymbolPd.make_kl_df('usGOOG',n_folds=2)
# 反向轴 也就是副轴生成
_,ax1=plt.subplots()
ax1.plot(tsla_df.close,c='r',label='tsla')
ax1.legend(loc=2)
ax1.grid(False)
ax2=ax1.twinx()
ax2.plot(goo_df.close,c='g',label='google')
ax2.legend(loc=1)

plt.show()

黄金分割线

import matplotlib.pyplot as plt
import numpy as np
from abupy import ABuSymbolPd
from collections import namedtuple
tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)
from scipy import stats
# 视觉上的黄金分割
cs_max=tsla_df.close.max()
cs_min=tsla_df.close.min()
sp382 = (cs_max-cs_min)*0.382 + cs_min
sp618=(cs_max-cs_min)*0.618+ cs_min
# 统计上的黄金分割
# 是按照序列值大小排序后,取序列排序后对应位置上的值
sp_382=stats.scoreatpercentile(tsla_df.close,38.2)
sp_618=stats.scoreatpercentile(tsla_df.close,61.8)

def plot_golden():
    above618=np.maximum(sp618,sp_618)
    below618=np.minimum(sp618,sp_618)
    above382=np.maximum(sp382,sp_382)
    below382=np.minimum(sp382,sp_382)
    plt.plot(tsla_df.close)
    plt.axhline(sp382,c='r')# 画水平视觉线
    plt.axhline(sp_382,c='m')# 画水平线统计

    plt.axhline(sp618, c='g')  # 画水平视觉线
    plt.axhline(sp_618, c='k')  # 画水平线统计
    # plt.axvline()画竖直垂线
    #  填充中间带
    plt.fill_between(tsla_df.index,above618,below618,alpha=0.5,color='r')
    plt.fill_between(tsla_df.index,above382,below382,alpha=0.5,color='g')
    n_t=namedtuple('golden', ['above618', 'below618', 'above382', 'below382'])(above618, below618, above382, below382)
    print(n_t)
    return n_t
golden=plot_golden()
plt.legend(['close','sp382','sp_382','sp618','sp_618'],loc='best')
plt.show()

多维数据绘制

MACD可视化 和 ATR可视化

import talib
from mpl_finance import mpl_finance as mpf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.dates as dates
from abupy import ABuSymbolPd
tsla_df=ABuSymbolPd.make_kl_df('usTSLA',n_folds=2)
kl_index=tsla_df.index
dif,dea,bar=talib.MACD(tsla_df.close.values,fastperiod=12,slowperiod=26,signalperiod=9)
plt.plot(kl_index,dif,label='macd dif')
plt.plot(kl_index,dea,label='signal dea')
bar_red=np.where(bar>0,bar,0)
bar_green=np.where(bar<0,bar,0)
plt.bar(kl_index,bar_red,facecolor='red',label='hist bar')
plt.bar(kl_index,bar_green,facecolor='green',label='hist bar')
plt.legend(loc='best')


# ATR指标
atr14=talib.ATR(tsla_df.high.values,tsla_df.low.values,tsla_df.close.values,timeperiod=14)
atr21=talib.ATR(tsla_df.high.values,tsla_df.low.values,tsla_df.close.values,timeperiod=21)
pd.DataFrame({'close':tsla_df.close,'atr14':atr14,'atr21':atr21}).plot(subplots=True,grid=True)
plt.show()

你可能感兴趣的:(量化交易,数据分析,python,量化交易,数据可视化)