1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        十行代碼繪制漂亮金融K線圖,這個(gè)神器你不可錯(cuò)過

        共 10691字,需瀏覽 22分鐘

         ·

        2022-07-23 12:59



        近期發(fā)現(xiàn)許多小伙伴有繪制K線圖的需求,甚至有些同學(xué)沒有用第三方模塊自己寫代碼繪制圖表,其實(shí)這完全是重復(fù)性工作,網(wǎng)上有許多已經(jīng)成熟的K線圖繪制方案,比如我們今天要講的 Mplfinance.

        Mplfinance 是 Matplotlib 組織開源項(xiàng)目的一部分。相對(duì)于Matplotlib,Mplfinance這個(gè)處于金融行業(yè)的垂直領(lǐng)域的模塊的關(guān)注度確實(shí)是少了一些,以至于很多朋友都不知道它的存在,實(shí)際上它非常實(shí)用且好用。

        1.準(zhǔn)備



        開始之前,你要確保Python和pip已經(jīng)成功安裝在電腦上,如果沒有,可以訪問這篇文章:超詳細(xì)Python安裝指南 進(jìn)行安裝。

        (可選1) 如果你用Python的目的是數(shù)據(jù)分析,可以直接安裝Anaconda:Python數(shù)據(jù)分析與挖掘好幫手—Anaconda,它內(nèi)置了Python和pip.

        (可選2) 此外,推薦大家用VSCode編輯器,它有許多的優(yōu)點(diǎn):Python 編程的最好搭檔—VSCode 詳細(xì)指南。

        請(qǐng)選擇以下任一種方式輸入命令安裝依賴
        1. Windows 環(huán)境 打開 Cmd (開始-運(yùn)行-CMD)。
        2. MacOS 環(huán)境 打開 Terminal (command+空格輸入Terminal)。
        3. 如果你用的是 VSCode編輯器 或 Pycharm,可以直接使用界面下方的Terminal.

        pip install --upgrade mplfinance


        2.基本使用



        我們以滬深300分鐘線為例,使用mplfinance繪制各類金融圖形。

        首先看看數(shù)據(jù)結(jié)構(gòu):

        import pandas as pd
        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        print(mins)


        結(jié)構(gòu)如下:

        day      open      high       low     close     volume
        0 2022-03-07 10:47:00  4406.223  4406.352  4405.662  4405.922   54345400
        1 2022-03-07 10:48:00  4406.172  4406.175  4403.834  4403.918   70803100
        2 2022-03-07 10:49:00  4403.333  4403.333  4402.235  4402.340   49632500
        3 2022-03-07 10:50:00  4402.330  4402.519  4401.838  4402.519   48159200


        我們用于mplfinance的數(shù)據(jù)必須是 Pandas DataFrame. 字段則按需提供,至少要有時(shí)間字段和一列數(shù)據(jù)。另外原始數(shù)據(jù)如果是其他的數(shù)據(jù)類型,你必須得先轉(zhuǎn)成DataFrame格式。

        此外,時(shí)間字段必須轉(zhuǎn)為DatetimeIndex:

        # 公眾號(hào):二七阿爾量化
        import pandas as pd
        import mplfinance as mpf
        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        mins["day"] = pd.to_datetime(mins["day"])
        mins = mins.set_index("day")
        mins.index.name = 'Time'
        print(mins)


        效果如下:

        open      high       low     close     volume
        Time
        2022-03-07 10:47:00  4406.223  4406.352  4405.662  4405.922   54345400
        2022-03-07 10:48:00  4406.172  4406.175  4403.834  4403.918   70803100
        2022-03-07 10:49:00  4403.333  4403.333  4402.235  4402.340   49632500
        2022-03-07 10:50:00  4402.330  4402.519  4401.838  4402.519   48159200


        準(zhǔn)備完成后就可以繪制圖表了:

        # 公眾號(hào):二七阿爾量化
        import pandas as pd
        import mplfinance as mpf
        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        mins["day"] = pd.to_datetime(mins["day"])
        mins = mins.set_index("day")
        mins.index.name = 'Time'

        # 繪制默認(rèn)圖像(美國(guó)線)
        mpf.plot(mins)



        繪制蠟燭圖(K線圖),為了避免圖表過大,我這里只取了240條K線:

        # 公眾號(hào):二七阿爾量化
        import pandas as pd
        import mplfinance as mpf
        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        mins["day"] = pd.to_datetime(mins["day"])
        mins = mins.set_index("day")
        mins.index.name = 'Time'

        candle_chart = mins.tail(240)
        mpf.plot(candle_chart, type='candle')



        黑白顏色太單調(diào)了,我們可以換成“雅虎”配色:

        mpf.plot(candle_chart, type='candle', style='yahoo')


        繪制線型圖:

        # 公眾號(hào):二七阿爾量化
        import pandas as pd
        import mplfinance as mpf
        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        mins["day"] = pd.to_datetime(mins["day"])
        mins = mins.set_index("day")
        mins.index.name = 'Time'
        mpf.plot(mins, type='line')


        除了美國(guó)線、蠟燭圖(K線)、線型圖外,mplfinance還支持 renko、pnf 等圖形。有興趣的同學(xué)可以改個(gè)type看看效果:

        3.添加技術(shù)指標(biāo)



        繪制簡(jiǎn)單移動(dòng)平均線MA5,我們只需要多加一個(gè)參數(shù):

        # 公眾號(hào):二七阿爾量化
        import pandas as pd
        import mplfinance as mpf
        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        mins["day"] = pd.to_datetime(mins["day"])
        mins = mins.set_index("day")
        mins.index.name = 'Time'
        candle_chart = mins.tail(240)
        mpf.plot(candle_chart, type='candle', mav=5)


        如果你需要多條移動(dòng)平均線,只需要將mav改為元組參數(shù),傳入你需要的周期參數(shù):


        如果你還需要顯示成交量(volume), mplfinance 也能實(shí)現(xiàn):

        # 公眾號(hào):二七阿爾量化
        import pandas as pd
        import mplfinance as mpf
        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        mins["day"] = pd.to_datetime(mins["day"])
        mins = mins.set_index("day")
        mins.index.name = 'Time'
        candle_chart = mins.tail(240)
        mpf.plot(candle_chart, type='candle', mav=(5, 10, 20), volume=True)


        如果你還想給蠟燭上色、想更改線條顏色、想增加其他指標(biāo),請(qǐng)看第三部分高級(jí)使用。

        4.高級(jí)使用



        上色是非常簡(jiǎn)單的,正如我們之前換成雅虎配色一樣,你只需要添加style參數(shù)即可換成我們傳統(tǒng)的技術(shù)指標(biāo)顏色。

        如果你想自定義顏色也是可以做到的,這里我將前120根柱子設(shè)置為藍(lán)黃相間,后120根柱子保留原形:

        # 公眾號(hào):二七阿爾量化
        import pandas as pd
        import mplfinance as mpf
        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        mins["day"] = pd.to_datetime(mins["day"])
        mins = mins.set_index("day")
        mins.index.name = 'Time'
        candle_chart = mins.tail(240)
        mco = ['yellow','blue'] * 60 + [None] * 120
        mpf.plot(candle_chart, volume=True, style='yahoo', type='candle', marketcolor_overrides=mco)


        效果如下:

        有些同學(xué)還希望能夠繪制自己的技術(shù)指標(biāo),mplfinance也可以做到:

        上滑查看更多代碼

        # 公眾號(hào):二七阿爾量化
        # https://github.com/matplotlib/mplfinance/blob/master/examples/mpf_animation_macd.py#L28

        import pandas as pd
        import mplfinance as mpf
        import matplotlib.animation as animation

        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        mins["day"] = pd.to_datetime(mins["day"])
        mins = mins.set_index("day")
        mins.index.name = 'Time'
        candle_chart = mins.tail(240)

        df = candle_chart

        exp12 = df['close'].ewm(span=12, adjust=False).mean()
        exp26 = df['close'].ewm(span=26, adjust=False).mean()
        macd = exp12 - exp26
        signal = macd.ewm(span=9, adjust=False).mean()
        histogram = macd - signal

        apds = [mpf.make_addplot(exp12,color='lime'),
                mpf.make_addplot(exp26,color='c'),
                mpf.make_addplot(histogram,type='bar',width=0.7,panel=1,
                                 color='dimgray',alpha=1,secondary_y=False),
                mpf.make_addplot(macd,panel=1,color='fuchsia',secondary_y=True),
                mpf.make_addplot(signal,panel=1,color='b',secondary_y=True),
               ]

        s = mpf.make_mpf_style(base_mpf_style='classic',rc={'figure.facecolor':'lightgray'})

        fig, axes = mpf.plot(df,type='candle',addplot=apds,figscale=1.5,figratio=(7,5),title='\n\nMACD',
                             style=s,volume=True,volume_panel=2,panel_ratios=(6,3,2),returnfig=True)

        mpf.show()


        mpf.make_addplot 支持添加任意圖形到任意panel上,panel參數(shù)默認(rèn)為0,如果設(shè)為1則將圖形添加到第二個(gè)圖上,color參數(shù)能設(shè)置圖形顏色,secondary_y 能將圖形的值設(shè)置到y(tǒng)軸上。效果如下:


        此外,如果你希望能動(dòng)態(tài)看到整個(gè)繪制過程,增加個(gè)animation即可:

        上滑查看更多代碼

        # 公眾號(hào):二七阿爾量化
        import pandas as pd
        import mplfinance as mpf
        import matplotlib.animation as animation

        mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
        mins["day"] = pd.to_datetime(mins["day"])
        mins = mins.set_index("day")
        mins.index.name = 'Time'
        candle_chart = mins.tail(240)

        df = candle_chart

        exp12 = df['close'].ewm(span=12, adjust=False).mean()
        exp26 = df['close'].ewm(span=26, adjust=False).mean()
        macd = exp12 - exp26
        signal = macd.ewm(span=9, adjust=False).mean()
        histogram = macd - signal

        apds = [mpf.make_addplot(exp12,color='lime'),
                mpf.make_addplot(exp26,color='c'),
                mpf.make_addplot(histogram,type='bar',width=0.7,panel=1,
                                 color='dimgray',alpha=1,secondary_y=False),
                mpf.make_addplot(macd,panel=1,color='fuchsia',secondary_y=True),
                mpf.make_addplot(signal,panel=1,color='b',secondary_y=True),
               ]

        s = mpf.make_mpf_style(base_mpf_style='classic',rc={'figure.facecolor':'lightgray'})

        fig, axes = mpf.plot(df,type='candle',addplot=apds,figscale=1.5,figratio=(7,5),title='\n\nMACD',
                             style=s,volume=True,volume_panel=2,panel_ratios=(6,3,2),returnfig=True)

        mpf.show()

        ax_main = axes[0]
        ax_emav = ax_main
        ax_hisg = axes[2]
        ax_macd = axes[3]
        ax_sign = ax_macd
        ax_volu = axes[4]


        def animate(ival):
            if (20+ival) > len(df):
                print('no more data to plot')
                ani.event_source.interval *= 3
                if ani.event_source.interval > 12000:
                    exit()
                return
            data = df.iloc[0:(30+ival)]
            exp12 = data['close'].ewm(span=12, adjust=False).mean()
            exp26 = data['close'].ewm(span=26, adjust=False).mean()
            macd = exp12 - exp26
            signal = macd.ewm(span=9, adjust=False).mean()
            histogram = macd - signal
            apds = [mpf.make_addplot(exp12,color='lime',ax=ax_emav),
                    mpf.make_addplot(exp26,color='c',ax=ax_emav),
                    mpf.make_addplot(histogram,type='bar',width=0.7,
                                     color='dimgray',alpha=1,ax=ax_hisg),
                    mpf.make_addplot(macd,color='fuchsia',ax=ax_macd),
                    mpf.make_addplot(signal,color='b',ax=ax_sign),
                   ]

            for ax in axes:
                ax.clear()
            mpf.plot(data,type='candle',addplot=apds,ax=ax_main,volume=ax_volu)

        ani = animation.FuncAnimation(fig,animate,interval=100)

        mpf.show()




        還有許多更有趣的玩法,你可以閱讀mplfinance的examples學(xué)習(xí)更多的使用技巧:

        https://github.com/matplotlib/mplfinance/tree/master/examples

        本文的全部代碼和數(shù)據(jù)包括mplfinance的examples都可以在【二七阿爾量化】公眾號(hào)后臺(tái)回復(fù):mplfinance 下載。

        我們的文章到此就結(jié)束啦,如果你喜歡今天的量化投資內(nèi)容,請(qǐng)持續(xù)關(guān)注二七阿爾量化。

        有任何問題,可以在公眾號(hào)后臺(tái)回復(fù):加群,回答相應(yīng)紅字驗(yàn)證信息,進(jìn)入互助群詢問。

        希望你能在下面點(diǎn)個(gè)贊和在看支持我繼續(xù)創(chuàng)作,謝謝!

        歡迎關(guān)注公眾號(hào):二七阿爾量化

        瀏覽 39
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            老牛嫩草一区二区三区日本 | 青青草性爱 | 骚逼系列 | 欧美日韩精品一区二区天天拍 | www.豆花视频com | ass漂亮女人下部picasa | 中国china中国hdxxxx | 国产成人精品网站 | 成人午夜激情 | 精品人妻无码一区二区三区四川人 |