绘图 - 即时行情

以下内容,都是 shioaji 的官网文件的内容,只是加了一些我自己的理解,感谢永丰提供这麽完整的 sample code

绘图会用到 numpy, pandas, bqplot...等套件,如果之前没有安装,可以先行安装

pip install numpy pandas bqplot
  • 引用套件
import json
import datetime as dt
import numpy as np
import pandas as pd
import bqplot as bq
import shioaji as sj
  • 登入 shioaji
api = sj.Shioaji()
api.login(person_id="帐号", passwd="密码")
  • 建立表格的资料集
today = dt.date.today()
df_min = pd.DataFrame(
    index=pd.date_range(
        start=dt.datetime(*(today.year, today.month, today.day, 8, 45)),
        end=dt.datetime(*(today.year, today.month, today.day, 13, 45)),
        freq='1T'), 
    columns=['open', 'high', 'low', 'close'], 
    dtype=float,
)
  • 建立绘图的方法
# ohlc: open high low close
def init_ohlc_chart():
    global ohlc_chart
    sc = bq.LinearScale()
    dt_scale = bq.DateScale()
    ax_x = bq.Axis(label="datetime", scale=dt_scale)
    ax_y = bq.Axis(lable="price", scale=sc, orientation="vertical", tick_format="0.0f")

    # 建立标记
    ohlc_chart = bq.OHLC(
        x=df_min.index,
        y=df_min.dropna().values,
        marker='candle',
        scales={ 'x': dt_scale, 'y': sc },
        format='ohlc',
        opcities=[0.85 for _ in df_min.index],
        display_legend=True,
        labels=['台积电']
    )
    
    fig = bq.Figure(axes=[ax_x, ax_y], marks=[ohlc_chart])

    return fig
  • 建立资料处理方法
def proc_ohlc_data(quote_msg, new_deal_price):
    global df_min
    ts = pd.Timestamp("{Date} {Time}".format(**quote_msg)).replace(second=0, microsecond=0)
    df_min.loc[ts, 'open'] = new_deal_price if np.isnan(df_min.loc[ts, 'open']) else df_min.loc[ts, 'open']
    df_min.loc[ts, 'high'] = new_deal_price if np.isnan(df_min.loc[ts, 'high']) else df_min.loc[ts, 'high']
    df_min.loc[ts, 'low'] = new_deal_price if np.isnan(df_min.loc[ts, 'low']) else df_min.loc[ts, 'low']
    df_min.loc[ts, 'close'] = new_deal_price
  • 建立图表更新方法
def update_ohlc_chart():
    global ohlc_chart
    with ohlc_chart.hold_sync():
        ohlc_chart.x = df_min.dropna().index
        ohlc_chart.y = df_min.dropna().values
  • 建立取得价格後的回呼方法
@sj.on_quote
def quote_callback(topic, quote_msg):
    global new_deal_price
    print(topic, quote_msg)
    proc_ohlc_data(quote_msg, new_deal_price)
    update_ohlc_chart()
  • 建立 solace 事件回呼方法
@sj.on_event
def event_callback(resp_code, event_code, event):
    print("Response Code: {} | Event Code: {} | Event: {}".format(resp_code, event_code, event))
  • 设定回呼方法
api.quote.set_callback(quote_callback)
api.quote.set_event_callback(event_callback)
  • 绘图
init_ohlc_chart()

因为我是在盘後才跑这个程序,所以没有办法取得即资料,所以暂时不确定以上的程序能不能正确运行,之後如果有机会在交易时间跑的话,会再验证,如果有问题的话,会再修改。
另外,我自己用 api.ticks() 的方法,把当天的 ticks 资料抓下来再去进行绘制,我想应该和最後的结果是一样的吧

ticks2330 = api.ticks(stock2330)
dt_index = list(map(lambda x:dt.datetime.utcfromtimestamp(x/1000000000), ticks2330.ts))

print(df_min)

prevTime = ""
open_price = 0
high_price = 0
low_price = 0
close_price = 0

for i in range(len(dt_index)):
    currTime = dt_index[i].strftime("%Y-%m-%d %H:%M:00")

    if currTime != prevTime:
        open_price = ticks2330.close[i]
        high_price = ticks2330.close[i]
        low_price = ticks2330.close[i]
        close_price = ticks2330.close[i]
        prevTime = currTime
    else:
        high_price = max(high, ticks2330.close[i])
        low_price = min(low, ticks2330.close[i])
        close_price = ticks2330.close[i]

    df_min.loc[currTime, "open"] = open_price
    df_min.loc[currTime, "high"] = high_price
    df_min.loc[currTime, "low"] = low_price
    df_min.loc[currTime, "close"] = close_price
    
init_ohlc_chart()

<<:  Day 10:架设 Prometheus (2)

>>:  30-9 之Presentation Layer - MVP ( Model-View-Presenter )

Day 26. slate × Normalizing × normalizeNode

Slate 正规化的相关功能由两个主要函式: interfaces/editor.ts 的 nor...

[Day 19] 阿嬷都看得懂的盒模型

阿嬷都看得懂的盒模型 各位阿嬷,我们今天要来寄自己腌渍的酱瓜给乖孙。 我们找来 4 个纸盒,想在里面...

Youtube Data API 教学 - 基本分类介绍 list.part

「鲑鱼均,因为一场鲑鱼之乱被主管称为鲑鱼世代,广义来说以年龄和脸蛋分类的话这应该算是一种 KNN 的...

Day 28 Compose UI ModalBottomSheetLayout

今年的疫情蛮严重的,希望大家都过得安好,今天疫情已经降级, 希望疫情快点过去,能回到一些线下技术聚会...

Day 28 - 实战演练 — Pagination

Pagination 今天要实作的只是一个最基本的 Pagination,而我个人觉得在处理换页时...