跳轉到

finlab.online

finlab.online.base_account.Account

Bases: ABC

股票帳戶的 abstract class 可以繼承此 Account,來實做券商的帳戶買賣動作,目前已經實做 SinopacAccount (永豐證券) 以及 FugleAccount (玉山富果),來進行交易。可以用以下方式建構物件並用來交易:

永豐證券

import os
from finlab.online.sinopac_account import SinopacAccount


# 舊版請使用
# shioaji < 1.0.0 and finlab < 0.3.18
os.environ['SHIOAJI_ACCOUNT']= '永豐證券帳號'
os.environ['SHIOAJI_PASSWORD']= '永豐證券密碼'

# 新版請使用
# shioaji >= 1.0.0 and finlab >= 0.3.18
os.environ['SHIOAJI_API_KEY'] = '永豐證券API_KEY'
os.environ['SHIOAJI_SECRET_KEY'] = '永豐證券SECRET_KEY'
os.environ['SHIOAJI_CERT_PERSON_ID']= '身份證字號'

# shioaji
os.environ['SHIOAJI_CERT_PATH']= '永豐證券憑證路徑'
os.environ['SHIOAJI_CERT_PASSWORD'] = '永豐證券憑證密碼' # 預設與身份證字號

acc = SinopacAccount()
玉山富果:
from finlab.online.fugle_account import FugleAccount
import os
os.environ['FUGLE_CONFIG_PATH'] = '玉山富果交易設定檔(config.ini.example)路徑'
os.environ['FUGLE_MARKET_API_KEY'] = '玉山富果的行情API Token'

acc = FugleAccount()

cancel_order(order_id) abstractmethod

刪除委託單

建議使用 刪除委託單此功能前,先使用 update_order() 來更新委託單的狀況!如下

acc.update_order()
acc.cancel_order('ORDER_ID')

Attributes:

Name Type Description
order_id str

券商所提供的委託單 ID

Returns:

Type Description
None

代表成功更新委託單

create_order(action, stock_id, quantity, price=None, force=False, wait_for_best_price=False) abstractmethod

產生新的委託單

Attributes:

Name Type Description
action Action

買賣方向,通常為 'BUY' 或是 'SELL'

stock_id str

股票代號 ex: '2330'

quantity numbers.Number

委託股票的總數量(張數),允許小數點

price numbers.Number

股票買賣的價格(限價單)

force bool

是否用最差之價格(長跌停)強制成交? 當成交量足夠時,可以比較快成交,然而當成交量低時,容易有大的滑價

wait_for_best_price bool

是否用最佳之價格(長跌停),無限時間等待?當今天要出場時,可以開啟等漲停價來購買,當今天要買入時,可以掛跌停價等待買入時機。

Returns:

Type Description
str

order id 券商提供的委託單編號

get_orders() abstractmethod

拿到現在所有委託單

Returns:

Type Description
Dict[str, Order]

所有委託單 id 與委託單資料

Example

{'12345A': Order(order_id='12345A', stock_id='5410',...),...}

get_position() abstractmethod

拿到當前帳戶的股票部位

Returns:

Type Description
Position

當前股票部位

get_stocks(stock_ids) abstractmethod

拿到現在股票報價

Attributes:

Name Type Description
stock_ids `list` of `str`

一次拿取所有股票的報價,ex: ['1101', '2330']

Returns:

Type Description
dict

報價資料,

Example

{'1101': Stock(stock_id='1101', open=31.15, high=31.85, low=31.1, close=31.65, bid_price=31.6, bid_volume=728.0, ask_price=31.65, ask_volume=202)}

get_total_balance() abstractmethod

拿到當前帳戶的股票部位淨值

update_order(order_id, price=None, quantity=None) abstractmethod

產生新的委託單

Attributes:

Name Type Description
order_id str

券商所提供的委託單 ID

price numbers.Number

更新的限價

quantity numbers.Number

更新的待成交量

Returns:

Type Description
None

無跳出 erorr 代表成功更新委託單

finlab.online.order_executor.Position(stocks, margin_trading=False, short_selling=False, day_trading_long=False, day_trading_short=False)

使用者可以利用 Position 輕鬆建構股票的部位,並且利用 OrderExecuter 將此部位同步於實際的股票帳戶。

建構股票部位

Attributes:

Name Type Description
stocks `dict` of `str`

number.Number): 股票代號與張數 ex: {'1101': 1} 是指持有一張 1101 台泥,可以接受負數,代表做空。

margin_trading bool

做多部位是否使用融資

short_selling bool

做空部位是否使用融券

day_trading_long bool

做多部位為當沖先做多

day_trading_short bool

做空部位為當沖先做空

Examples:

設計部位,持有一張和 100 股 1101

from finlab.online.order_executor import Position

Position({'1101': 1.1})
output
[
    {'stock_id': '1101',
     'quantity': 1.1,
     'order_condition': <OrderCondition.CASH: 1>
    }
]

將兩個部位相加

from finlab.online.order_executor import Position

p1 = Position({'1101': 1})
p2 = Position({'2330': 1})
p1 + p2
output
[
    {'stock_id': '1101', 'quantity': 1.0, 'order_condition': <OrderCondition.CASH: 1>},
    {'stock_id': '2330', 'quantity': 1.0, 'order_condition': <OrderCondition.CASH: 1>}
]

from_list(position) classmethod

利用 dict 建構股票部位

Attributes:

Name Type Description
position `list` of `dict`

股票詳細部位

from finlab.online.enums import OrderCondition
from finlab.online.order_executor import Position

Position.from_list(
[{
  'stock_id': '1101', # 股票代號
  'quantity': 1.1, # 張數
  'order_condition': OrderCondition.CASH # 現股融資融券、先買後賣
}])

其中 OrderCondition 除了 CASH 外,還有 MARGIN_TRADINGDAY_TRADING_LONGSHORT_SELLINGDAY_TRADING_SHORT

from_report(report, fund, kwargs) classmethod

利用回測完的報告 finlab.report.Report 建構股票部位。

Attributes:

Name Type Description
report finlab.report.Report

回測完的結果報告。

fund int

希望部屬的資金。

price pd.Series or `dict` of `float`

股票代號對應到的價格,若無則使用最近個交易日的收盤價。

odd_lot bool

是否考慮零股。預設為 False,只使用整張操作。

board_lot_size int

一張股票等於幾股。預設為1000,一張等於1000股。

allocation func

資產配置演算法選定,預設為finlab.online.utils.greedy_allocation(最大資金部屬貪婪法)。

Example

from finlab import backtest
from finlab.online.order_executor import Position

report1 = backtest.sim(...)
report2 = backtest.sim(...)

position1 = Position.from_report(report1, 1000000) # 策略操作金額一百萬
position2 = Position.from_report(report2, 1000000) # 策略操作金額一百萬

total_position = position1 + position2

from_weight(weights, fund, price=None, odd_lot=False, board_lot_size=1000, allocation=greedy_allocation) classmethod

利用 weight 建構股票部位

Attributes:

Name Type Description
weights `dict` of `float`

股票詳細部位

fund number.Number

資金大小

price pd.Series or `dict` of `float`

股票代號對應到的價格,若無則使用最近個交易日的收盤價。

odd_lot bool

是否考慮零股

board_lot_size int

一張股票等於幾股

allocation func

資產配置演算法選定,預設為預設為finlab.online.utils.greedy_allocation(最大資金部屬貪婪法)

Examples:

例如,用 100 萬的資金,全部投入,持有 1101 和 2330 各一半:

from finlab.online.order_executor import Position

Position.from_weight({
    '1101': 0.5,
    '2330': 0.5,
}, fund=1000000)
output
[
  {'stock_id': '1101', 'quantity': 13, 'order_condition': <OrderCondition.CASH: 1>},
  {'stock_id': '2330', 'quantity': 1, 'order_condition': <OrderCondition.CASH: 1>}
]

finlab.online.order_executor.OrderExecutor(target_position, account)

對比實際帳戶與欲部屬的股票部位,進行同步

Parameters:

Name Type Description Default
target_position Position

想要部屬的股票部位。

required
account Account

目前支援永豐與富果帳戶,請參考 Account 來實做。

required

cancel_orders()

刪除所有未實現委託單

create_orders(market_order=False, best_price_limit=False, view_only=False)

產生委託單,將部位同步成 self.target_position 預設以該商品最後一筆成交價設定為限價來下單

Attributes:

Name Type Description
market_order bool

以類市價盡量即刻成交:所有買單掛漲停價,所有賣單掛跌停價

best_price_limit bool

掛芭樂價:所有買單掛跌停價,所有賣單掛漲停價

view_only bool

預設為 False,會實際下單。若設為 True,不會下單,只會回傳欲執行的委託單資料(dict)。

show_alerting_stocks()

產生下單部位是否有警示股,以及相關資訊

update_order_price()

更新委託單,將委託單的限價調整成當天最後一筆價格。 (讓沒成交的限價單去追價)

finlab.online.base_account.Order dataclass

Order status

委託單的狀態

Attributes:

Name Type Description
order_id str

委託單的 id,與券商 API 所提供的 id 一致

stock_id str

股票代號 ex: '2330'

action Action

買賣方向,通常為 'BUY' 或是 'SELL'

price numbers.Number

股票買賣的價格(限價單)

quantity numbers.Number

委託股票的總數量(張數),允許小數點

filled_quantity numbers.Number

以成交股票的數量(張數),允許小數點

status OrderStatus

委託狀態,可以設定為:'NEW', 'PARTIALLY_FILLED', 'FILLED', 'CANCEL'

time datetime.datetime

委託時間

org_order Any = None

券商所提供的委託物件格式

finlab.online.panel.order_panel(account)

下單 GUI 介面

Parameters:

Name Type Description Default
account Account

請參考 Account 針對不同券商來建構相對應的操作帳戶

required