简单画出k线及均线

用户成长系列
标签: #<Tag:0x00007f8c5cea8f68>

(hugo) #1
克隆策略

使用pyhth

In [1]:
import talib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.finance as mpf

def plotcandlestict(instrument,start_date,end_date,sma_n1,sma_n2):
    # 获取数据
    data = D.history_data(instrument, start_date=start_date, end_date=end_date,
                          fields=['close','high','open','high','low','volume'])
    data=data.set_index('date')

    # 计算 10 日和 30 日均线
    #使用talib的时候需要更改数据类型....
    sma_1 = talib.SMA(np.array(data['close'].astype('double')), sma_n1)
    sma_2 = talib.SMA(np.array(data['close'].astype('double')), sma_n2)

    # 创建图像和子图
    fig = plt.figure(figsize=(17, 10))
    ax = fig.add_axes([0,0.2,1,0.5])
    ax2 = fig.add_axes([0,0,1,0.2])

    # k 线
    mpf.candlestick2_ochl(ax, data['open'], data['close'], data['high'], data['low'], 
                          width=0.5, colorup='r', colordown='g', alpha=0.8)

    # 设置横轴坐标
    ax.set_xticks(range(0, len(data.index), 10))
    ax.plot(sma_1, label=str('sma%s'%sma_n1))
    ax.plot(sma_2, label=str('sma%s'%sma_n2))

    # 创建图例
    ax.legend(loc='upper left')

    # 网格
    ax.grid(True)

    # 成交量
    mpf.volume_overlay(ax2, data['open'], data['close'], data['volume'], colorup='r', colordown='g', width=0.5, alpha=0.8)
    ax2.set_xticks(range(0, len(data.index), 10))
    ax2.set_xticklabels(data.index.strftime('%Y-%m-%d')[::10], rotation=30)
    ax2.grid(True)

    plt.show()
In [2]:
plotcandlestict('000001.SHA','2017-01-01','2017-11-21',10,20)

使用highstock画出上面的图

highstock比matplotlib方便的是提供交互

In [17]:
def candlestick_processor(df_options):
    # df_options:为df转化后的数据

    # 蜡烛图

    # 生成ohlc:从series中读取OHLC数据(前四列)合并
    ohlc_series = {}
    sma_series={}
    other_series = []
    series = df_options['series']
    for s in series:
        if s['name'] in {'open', 'high', 'low', 'close'}:
            ohlc_series[s['name']] = s
        elif s['name'] in {'sma_10'}:
            sma_series[s['name']]=s
        else:
            other_series.append(s)
    if len(ohlc_series) != 4:
        print('【错误】蜡烛图,没有找到open, high, low, close数据,请确保输入的数据有这四列')
        return None

    ohlc_data = []
    for i in range(0, len(ohlc_series['open']['data'])):
        row = [ohlc_series['open']['data'][i][0]]
        for j in ['open', 'high', 'low', 'close']:
            row.append(ohlc_series[j]['data'][i][1])
        ohlc_data.append(row)
    
    sma_data=[]
    for i in range(0,len(sma_series['sma_10']['data'])):
        xrow = [sma_series['sma_10']['data'][i][0]]
        for j in ['sma_10']:
            xrow.append(sma_series[j]['data'][i][1])
        sma_data.append(xrow)
    df_options['series'] = [{'data': ohlc_data, 'name': 'OHLC', 'yAxis': 0, 'type': 'candlestick',},
                           {'data':sma_data,'name':'sma_10','yAxis':0,'type':'spline',}] + other_series

    if other_series:
        #  设置其他数据使用第二个y轴
        for s in other_series:
            s.update({'yAxis':1, 'type': 'column'})
        
        y_axis = [
            {
                'labels': {'align': 'right', 'x': -3},
                'title': {'text': 'OHLC'},
                'height': '60%', 'lineWidth': 2
            },
            {
                'labels': {'align': 'right', 'x': -3},
                'top': '65%', 'height': '35%', 'offset': 0, 'lineWidth': 2,
            }
        ]
        
       

       
        df_options = T.deep_update(df_options, {'yAxis': y_axis})

    return df_options
In [11]:
data = D.history_data(['000001.SHA'], start_date='2017-01-01', end_date='2017-06-30',
                      fields=['close','high','open','low','volume'])
data=data.set_index('date')
del data['instrument']

data['sma_10'] = talib.SMA(np.array(data['close'].astype('double')), 10)
In [18]:
T.plot(data, options=candlestick_processor, title='股票数据分析', stock=True)

Pandas DataFrame数据图表可视化
策略研究常用功能