<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          十行代碼繪制漂亮金融K線圖,這個神器你不可錯過

          共 10691字,需瀏覽 22分鐘

           ·

          2022-07-23 12:59



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

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

          1.準備



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

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

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

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

          pip install --upgrade mplfinance


          2.基本使用



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

          首先看看數(shù)據(jù)結構:

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


          結構如下:

          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ù)據(jù)。另外原始數(shù)據(jù)如果是其他的數(shù)據(jù)類型,你必須得先轉成DataFrame格式。

          此外,時間字段必須轉為DatetimeIndex:

          # 公眾號:二七阿爾量化
          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


          準備完成后就可以繪制圖表了:

          # 公眾號:二七阿爾量化
          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)



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

          # 公眾號:二七阿爾量化
          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')



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

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


          繪制線型圖:

          # 公眾號:二七阿爾量化
          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')


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

          3.添加技術指標



          繪制簡單移動平均線MA5,我們只需要多加一個參數(shù):

          # 公眾號:二七阿爾量化
          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)


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


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

          # 公眾號:二七阿爾量化
          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)


          如果你還想給蠟燭上色、想更改線條顏色、想增加其他指標,請看第三部分高級使用。

          4.高級使用



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

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

          # 公眾號:二七阿爾量化
          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)


          效果如下:

          有些同學還希望能夠繪制自己的技術指標,mplfinance也可以做到:

          上滑查看更多代碼

          # 公眾號:二七阿爾量化
          # 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ù)默認為0,如果設為1則將圖形添加到第二個圖上,color參數(shù)能設置圖形顏色,secondary_y 能將圖形的值設置到y(tǒng)軸上。效果如下:


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

          上滑查看更多代碼

          # 公眾號:二七阿爾量化
          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學習更多的使用技巧:

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

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

          我們的文章到此就結束啦,如果你喜歡今天的量化投資內容,請持續(xù)關注二七阿爾量化。

          有任何問題,可以在公眾號后臺回復:加群,回答相應紅字驗證信息,進入互助群詢問。

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

          歡迎關注公眾號:二七阿爾量化

          瀏覽 39
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  丁香五月婷婷中文字幕 | 久三级电影片 | 美女高潮视频网站 | 99久久群交毛片 | 国语对白中文字幕第二页 |