博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Matplotlib和Tushare绘制K线图
阅读量:6617 次
发布时间:2019-06-25

本文共 6264 字,大约阅读时间需要 20 分钟。

hot3.png

股市数据获取

import tushare as ts

ts.get_hist_data('600848')#一次性获取全部日k线数据

结果显示:

open    high  close    low    volume    p_change  ma5 \date2012-01-11  6.880  7.380  7.060  6.880  14129.96    2.62  7.0602012-01-12  7.050  7.100  6.980  6.900    7895.19    -1.13  7.0202012-01-13  6.950  7.000  6.700  6.690    6611.87    -4.01  6.9132012-01-16  6.680  6.750  6.510  6.480    2941.63    -2.84  6.8132012-01-17  6.660  6.880  6.860  6.460    8642.57    5.38  6.8222012-01-18  7.000  7.300  6.890  6.880  13075.40    0.44  6.7882012-01-19  6.690  6.950  6.890  6.680    6117.32    0.00  6.7702012-01-20  6.870  7.080  7.010  6.870    6813.09    1.74  6.832           ma10    ma20      v_ma5    v_ma10    v_ma20    turnoverdate2012-01-11  7.060  7.060  14129.96  14129.96  14129.96    0.482012-01-12  7.020  7.020  11012.58  11012.58  11012.58    0.272012-01-13  6.913  6.913    9545.67    9545.67    9545.67    0.232012-01-16  6.813  6.813    7894.66    7894.66    7894.66    0.102012-01-17  6.822  6.822    8044.24    8044.24    8044.24    0.302012-01-18  6.833  6.833    7833.33    8882.77    8882.77    0.452012-01-19  6.841  6.841    7477.76    8487.71    8487.71    0.212012-01-20  6.863  6.863    7518.00    8278.38    8278.38    0.23

绘制K线图

matplotlib.finance 工具包的绘制K线图

def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r',                 alpha=1.0, ochl=True):    """    Plot the time, open, high, low, close as a vertical line ranging    from low to high.  Use a rectangular bar to represent the    open-close span.  If close >= open, use colorup to color the bar,    otherwise use colordown    Parameters    ----------    ax : `Axes`        an Axes instance to plot to    quotes : sequence of quote sequences        data to plot.  time must be in float date format - see date2num        (time, open, high, low, close, ...) vs        (time, open, close, high, low, ...)        set by `ochl`    width : float        fraction of a day for the rectangle width    colorup : color        the color of the rectangle where close >= open    colordown : color         the color of the rectangle where close <  open    alpha : float        the rectangle alpha level    ochl: bool        argument to select between ochl and ohlc ordering of quotes    Returns    -------    ret : tuple        returns (lines, patches) where lines is a list of lines        added and patches is a list of the rectangle patches added    """    OFFSET = width / 2.0    lines = []    patches = []    for q in quotes:        if ochl:            t, open, close, high, low = q[:5]        else:            t, open, high, low, close = q[:5]        if close >= open:            color = colorup            lower = open            height = close - open        else:            color = colordown            lower = close            height = open - close        vline = Line2D(            xdata=(t, t), ydata=(low, high),            color=color,            linewidth=0.5,            antialiased=True,        )        rect = Rectangle(            xy=(t - OFFSET, lower),            width=width,            height=height,            facecolor=color,            edgecolor=color,        )        rect.set_alpha(alpha)        lines.append(vline)        patches.append(rect)        ax.add_line(vline)        ax.add_patch(rect)    ax.autoscale_view()    return lines, patches

tushare 的 pandas dataframe 生成K线图

def _candlestick(ax, df, width=0.2, colorup='k', colordown='r',                 alpha=1.0):    """    Plot the time, open, high, low, close as a vertical line ranging    from low to high.  Use a rectangular bar to represent the    open-close span.  If close >= open, use colorup to color the bar,    otherwise use colordown    Parameters    ----------    ax : `Axes`        an Axes instance to plot to    df : pandas data from tushare    width : float        fraction of a day for the rectangle width    colorup : color        the color of the rectangle where close >= open    colordown : color         the color of the rectangle where close <  open    alpha : float        the rectangle alpha level    ochl: bool        argument to select between ochl and ohlc ordering of quotes    Returns    -------    ret : tuple        returns (lines, patches) where lines is a list of lines        added and patches is a list of the rectangle patches added    """    OFFSET = width / 2.0    lines = []    patches = []    for date_string,row in df.iterrows():        date_time = datetime.datetime.strptime(date_string,'%Y-%m-%d')        t = date2num(date_time)        open, high, close, low = row[:4]        if close >= open:            color = colorup            lower = open            height = close - open        else:            color = colordown            lower = close            height = open - close        vline = Line2D(            xdata=(t, t), ydata=(low, high),            color=color,            linewidth=0.5,            antialiased=True,        )        rect = Rectangle(            xy=(t - OFFSET, lower),            width=width,            height=height,            facecolor=color,            edgecolor=color,        )        rect.set_alpha(alpha)        lines.append(vline)        patches.append(rect)        ax.add_line(vline)        ax.add_patch(rect)    ax.autoscale_view()    return lines, patchesdef drawPic(df, code, name):    mondays = WeekdayLocator(MONDAY)            # 主要刻度    alldays = DayLocator()                      # 次要刻度    #weekFormatter = DateFormatter('%b %d')     # 如:Jan 12    mondayFormatter = DateFormatter('%m-%d-%Y') # 如:2-29-2015    dayFormatter = DateFormatter('%d')          # 如:12    fig, ax = plt.subplots()    fig.subplots_adjust(bottom=0.2)    ax.xaxis.set_major_locator(mondays)    ax.xaxis.set_minor_locator(alldays)    ax.xaxis.set_major_formatter(mondayFormatter)    _candlestick(ax, df, width=0.6, colorup='r', colordown='g')    ax.xaxis_date()    ax.autoscale_view()    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')    ax.grid(True)    plt.title(name + '  ' + code, fontproperties=zhfont)    plt.show()def makePicture(code, name):    df = ts.get_hist_data(code, start=begin_time, end=end_time)    df = df.sort_index(0)#    df.plot()    drawPic(df, code, name)

转载于:https://my.oschina.net/u/2306127/blog/832540

你可能感兴趣的文章
PHP加载MSSQL失败的解决办法
查看>>
MySQL系列之B-2------MySQL安装
查看>>
普通用户启动redis
查看>>
Memcached实现Session共享
查看>>
1.4-shell自定义变量
查看>>
ansible模块使用
查看>>
grep之正则表达式用法
查看>>
Oracle查询所有序列
查看>>
OGG运维优化脚本(十三)-信息同步类--进程信息上传
查看>>
详解Linux下挂载和格式化虚拟磁盘
查看>>
用永中Office过把DJ瘾
查看>>
SSL/TLS协议簇加解密流程
查看>>
我的友情链接
查看>>
matlab中使用结构体(1)
查看>>
在Redhat 5 上手动创建DNS服务器
查看>>
Linux内核管理--内存(一)
查看>>
乱码过滤器
查看>>
浅谈生产场景如何对linux系统进行分区?
查看>>
RHCS 集群安装部署
查看>>
给10^7个数据量的磁盘文件进行排序
查看>>