V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
a499492580
V2EX  ›  Python

用 Python 画 K 线图并进行分析!(源代码分享)

  •  2
     
  •   a499492580 · 2017-11-14 11:14:38 +08:00 · 7932 次点击
    这是一个创建于 2565 天前的主题,其中的信息可能已经有所发展或是发生改变。
    花了半天时间在 MINDGO 量化交易平台的研究环境中绘制了 K 线图,并进行了分析,有兴趣的可以到 MINDGO 量化交易平台上学习画 K 线图,并分析,如有疑难,加入 MINDGO 量化交流群:217901996. 对学 Python 绘图包有兴趣的可以加一波
    K 线图源代码:
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.finance import candlestick2_ohlc
    import datetime
    data=get_price(['000300.SH'], None, '20171110', '1d', ['open','high','low','close'], True, None, 200, is_panel=0)
    data=data['000300.SH']
    #时间转化格式
    time=data.index
    t=[]
    for x in time:
    x=str(x).split()[0]
    x=x.split('-')
    x=x[0]+x[1]+x[2]
    x=int(x)
    t.append(x)
    #画图数据
    time=t
    open1=list(data['open'])
    high1=list(data['high'])
    low1=list(data['low'])
    close1=list(data['close'])
    #画图
    fig,ax = plt.subplots(figsize = (32,8),facecolor='pink')
    fig.subplots_adjust()
    plt.xticks()
    plt.yticks()
    plt.title("沪深 300K 线走势图")
    plt.ylabel("股指")
    ticks = ax.set_xticks(range(1,200,40))
    labels = ax.set_xticklabels([time[0],time[40],time[80],time[120],time[160]])
    candlestick2_ohlc(ax,open1,high1,low1,close1,width=0.6,colorup='red',colordown='green')
    #支撑线
    plt.plot([75,200],[3316,3954],'g',linewidth=10)
    # 红星:回踩 1
    plt.plot(75, 3316, 'r*', markersize = 40.0,label='趋势线')
    plt.annotate(r'二次低位', xy=(75, 3316),
    xycoords='data', xytext=(-90, -50),
    textcoords='offset points', fontsize=26,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    # 红星:回踩 2
    plt.plot(140, 3650, 'r*', markersize = 40.0)
    plt.annotate(r'止跌,形成趋势线', xy=(140, 3650),
    xycoords='data', xytext=(-90, -50),
    textcoords='offset points', fontsize=26,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    # 红星:回踩 3
    plt.plot(172, 3800, 'r*', markersize = 40.0)
    plt.annotate(r'回踩趋势线', xy=(172, 3800),
    xycoords='data', xytext=(-90, -50),
    textcoords='offset points', fontsize=26,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    #MA5
    data['ma5']=pd.rolling_mean(data['close'],5)
    plt.plot(list(data['ma5']),label='五日均线')
    #MA10
    data['ma10']=pd.rolling_mean(data['close'],10)
    plt.plot(list(data['ma10']),label='十日均线')
    #MA20
    data['ma20']=pd.rolling_mean(data['close'],20)
    plt.plot(list(data['ma20']),label='二十日均线')
    #MA30
    data['ma30']=pd.rolling_mean(data['close'],30)
    plt.plot(list(data['ma30']),label='三十日均线')
    #MA60
    data['ma60']=pd.rolling_mean(data['close'],60)
    plt.plot(list(data['ma60']),label='六十日均线')
    plt.legend()
    print('沪深 300 走势图分析')

    成交量源代码:
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import mlab
    from matplotlib import rcParams
    data=get_price(['000300.SH'], None, '20171110', '1d', ['volume'], True, None,200, is_panel=0)['000300.SH']
    data['volma5']=pd.rolling_mean(data['volume'],5)
    data['volma10']=pd.rolling_mean(data['volume'],10)
    volma5=list(data['volma5'])
    volma10=list(data['volma10'])
    data['goldordie']=(data['volma5']-data['volma10'])
    time=data.index
    t=[]
    for x in time:
    x=str(x).split()
    x=x[0]
    t.append(x)
    #画图数据
    time=t
    x=list(data['volume'])
    y=len(x)
    z=range(0,y,1)
    fig,ax = plt.subplots(figsize = (48,8),facecolor='pink')
    ticks = ax.set_xticks(range(1,200,40))
    rects =plt.bar(left = z,height = x,width = 0.4,color=('r','g'),align="center",yerr=0.1)
    plt.title('VOL')
    # plt.xticks(z,t)
    # 蓝线:五日量能
    plt.plot(volma5,'b',label="五日量能")
    # 蓝线:十日量能
    plt.plot(volma10,'y',label="十日量能")
    plt.title("沪深 300 成交量")
    print("沪深 300 成交量")
    jc=[]
    sc=[]
    for x in range(0,200,1):
    z=x-1
    y2=data['goldordie'].iloc[x]
    y1=data['goldordie'].iloc[z]
    if y1<0 and y2>0:
    jc.append(x)
    elif y1>0 and y2<0:
    sc.append(x)
    for x in jc:
    if x== jc[-1]:
    vol=data['volma5'].iloc[x]
    plt.plot(x, vol, 'r*', markersize = 40.0,label='金叉')
    else:
    vol=data['volma5'].iloc[x]
    plt.plot(x, vol, 'r*', markersize = 40.0)
    for x in sc:
    if x==sc[-1]:
    vol=data['volma5'].iloc[x]
    plt.plot(x, vol, 'g*', markersize = 40.0,label='死叉')
    else:
    vol=data['volma5'].iloc[x]
    plt.plot(x, vol, 'g*', markersize = 40.0)
    plt.legend()
    plt.show()
    MACD 指标源代码:
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import mlab
    from matplotlib import rcParams
    data=get_price(['000300.SH'], None, '20171110', '1d', ['close'], True, None,233, is_panel=0)['000300.SH']
    data['ma12']=pd.ewma(data['close'],12)
    data['ma26']=pd.ewma(data['close'],26)
    data['diff']=data['ma12']-data['ma26']
    data['dea']=pd.ewma(data['diff'],9)
    data['macd']=data['diff']-data['dea']
    data=data[33:]
    diff=list(data['diff'])
    dea=list(data['dea'])
    fig,ax=plt.subplots(figsize=(16,4),facecolor='pink')
    plt.plot(diff,'b',label='diff')
    plt.plot(dea,'y',label='dea')
    macd=list(data['macd'])
    x=len(list(data['macd']))
    x=range(0,x,1)
    rects =plt.bar(left = x,height = macd,width = 0.4,color=('g','r'),align="center",yerr=0.1)
    plt.title('MACD 指标')
    jc=[]
    sc=[]
    data['goldordie']=data['diff']-data['dea']
    for x in range(0,200,1):
    z=x-1
    y2=data['goldordie'].iloc[x]
    y1=data['goldordie'].iloc[z]
    if y1<0 and y2>0:
    jc.append(x)
    elif y1>0 and y2<0:
    sc.append(x)
    for x in jc:
    if x==jc[-1]:
    diff=data['diff'].iloc[x]
    if diff>0:
    plt.plot(x, diff, 'r*', markersize = 20.0,label='金叉')
    plt.annotate(r'多方金叉顺势买入', xy=(x, diff),
    xycoords='data', xytext=(-20, -20),
    textcoords='offset points', fontsize=12,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    else:
    plt.plot(x, diff, 'r*', markersize = 20.0,label='金叉')
    plt.annotate(r'空方金叉猥琐买入', xy=(x, diff),
    xycoords='data', xytext=(-20, -20),
    textcoords='offset points', fontsize=12,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    else:
    diff=data['diff'].iloc[x]
    if diff>0:
    plt.plot(x, diff, 'r*', markersize = 20.0)
    plt.annotate(r'多方金叉顺势买入', xy=(x, diff),
    xycoords='data', xytext=(-20, -20),
    textcoords='offset points', fontsize=12,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    else:
    plt.plot(x, diff, 'r*', markersize = 20.0)
    plt.annotate(r'空方金叉猥琐买入', xy=(x, diff),
    xycoords='data', xytext=(-20, -20),
    textcoords='offset points', fontsize=12,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    for x in sc:
    if x==sc[-1]:
    diff=data['diff'].iloc[x]
    if diff >0:
    plt.plot(x, diff, 'g*', markersize = 20.0,label='死叉')
    plt.annotate(r'多方死叉猥琐卖出', xy=(x, diff),
    xycoords='data', xytext=(20, 20),
    textcoords='offset points', fontsize=12,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    if diff <0:
    plt.plot(x, diff, 'g*', markersize = 20.0,label='死叉')
    plt.annotate(r'空方死叉顺势卖出', xy=(x, diff),
    xycoords='data', xytext=(20, 20),
    textcoords='offset points', fontsize=12,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    else:
    diff=data['diff'].iloc[x]
    if diff>0:
    plt.plot(x, diff, 'g*', markersize = 20.0)
    plt.annotate(r'多方死叉猥琐卖出', xy=(x, diff),
    xycoords='data', xytext=(10, 20),
    textcoords='offset points', fontsize=12,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    else:
    plt.plot(x, diff, 'g*', markersize = 20.0)
    plt.annotate(r'空方死叉顺势卖出', xy=(x, diff),
    xycoords='data', xytext=(10, 20),
    textcoords='offset points', fontsize=12,
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    plt.legend()
    第 1 条附言  ·  2017-11-14 14:17:13 +08:00
    详细内容可参见:quant.10jqka.com.cn/platform/html/article.html#id/91095146
    第 2 条附言  ·  2017-11-14 14:44:44 +08:00


      
      

    23 条回复    2017-11-14 16:08:31 +08:00
    a499492580
        1
    a499492580  
    OP
       2017-11-14 11:17:38 +08:00
    clino
        2
    clino  
       2017-11-14 11:22:11 +08:00
    为什么不贴一个 gist url 就好?
    a499492580
        3
    a499492580  
    OP
       2017-11-14 11:27:04 +08:00
    @clino 哈哈 我还不熟悉 gist url 还请指教
    misaka19000
        4
    misaka19000  
       2017-11-14 11:28:12 +08:00
    为什么不把代码格式化一下
    a499492580
        5
    a499492580  
    OP
       2017-11-14 11:29:18 +08:00
    @misaka19000 哈哈 加群我给你文件吧
    master13
        6
    master13  
       2017-11-14 11:38:27 +08:00
    我猜想 python 画这种图应该由封装更高层次的库吧
    clino
        7
    clino  
       2017-11-14 11:39:45 +08:00
    @a499492580 上载到 gist 然后这里贴个 url 就行了,v2ex 这里支持点个按钮展开代码的
    a499492580
        8
    a499492580  
    OP
       2017-11-14 11:42:28 +08:00
    @clino gist 纯英文看不懂啊
    a499492580
        9
    a499492580  
    OP
       2017-11-14 11:42:46 +08:00
    @master13 没有的 Python 自带的绘图库即可画了
    4ever911
        10
    4ever911  
       2017-11-14 12:18:58 +08:00
    matplot 就算了吧, 丑死了又慢, 建议用 pyqtgraph, 里面就自带一个例子,我用这个封装了一个,狠漂亮,很好用。
    TimePPT
        11
    TimePPT  
       2017-11-14 12:30:13 +08:00   ❤️ 2
    lixuda
        12
    lixuda  
       2017-11-14 12:49:15 +08:00
    是同花顺的官方吗?
    lyh404
        13
    lyh404  
       2017-11-14 13:06:37 +08:00
    没有前途,放弃吧。
    a499492580
        14
    a499492580  
    OP
       2017-11-14 13:21:23 +08:00
    @lixuda MINDGO
    a499492580
        15
    a499492580  
    OP
       2017-11-14 13:25:04 +08:00
    @4ever911 呵呵 重要的是如何绘制,而不是美观
    a499492580
        16
    a499492580  
    OP
       2017-11-14 13:25:29 +08:00
    @lyh404 重要是如何绘制,学习 Python 代码 而不是别的目的
    livc
        17
    livc  
       2017-11-14 13:37:33 +08:00
    @TimePPT #11 这是 K 线?
    a499492580
        18
    a499492580  
    OP
       2017-11-14 13:47:00 +08:00
    @livc 他打广告呢 别理他
    xiaket
        19
    xiaket  
       2017-11-14 13:52:00 +08:00
    @livc url 实际上是: http://pyecharts.herokuapp.com/kline

    @a499492580 你才是打广告吧?而且还很不高明
    a499492580
        20
    a499492580  
    OP
       2017-11-14 13:54:20 +08:00
    @xiaket 哦,是吗?我带着源代码打广告?
    thomaspaine
        21
    thomaspaine  
       2017-11-14 15:17:26 +08:00
    @a499492580 你这广告太明显了啊,再看看自己发帖纪录,是不是更明显?
    TimePPT
        22
    TimePPT  
       2017-11-14 15:18:34 +08:00
    @a499492580 呵呵,你也忒小人之心了,我跟 pyecharts 一点儿关系都没有,至于跟人打广告? Echarts 本身就是世界上比较知名的 charts 库了,用得着我宣传?

    你要能找出足够的证据指明我在给人打广告,我在 V2EX 单开帖给你道歉!
    lixuda
        23
    lixuda  
       2017-11-14 16:08:31 +08:00
    @TimePPT 知道这个库,还没有用
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5291 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 09:00 · PVG 17:00 · LAX 01:00 · JFK 04:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.