order
order 関数は,株数を指定する注文関数です.銘柄と株数を指定すれば,成り行き注文が入ります.(成り行き以外はstyle
で指定)
order(asset, amount, style=OrderType)
asset: Equity/Future オブジェクト
amount: 株数
style: 注文方法(指定方法はorderを参照)
アルゴリズム例
例は,
株価が急騰した時Longするという単純なアルゴリズムを書いてみたいと思います.
急騰=過去5日の株価平均よりも現在価格が1%以上高いという定義にします.
ポジションを持ったあと,現在価格が平均価格より低くなった場合はポジションを閉じます.
今回は,1銘柄(アップル)だけを見ます.
元ネタはBasic Algorithmです.
def initialize(context):
# AAPL
context.security = sid(24)
# rebalance 関数を毎日クローズ一分前(15:59)に実行するように指定
schedule_function(rebalance,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_close(minutes = 1))
def rebalance(context, data):
# 過去5日間の平均を取得して,今日の価格よりも1%大きければLong
# 今日価格が移動平均より小さければ,ポジションクローズする
# 過去5日間のヒストリカルデータを取得.
# 【注意】https://www.quantopian.com/help#ide-history に説明があるとおり,
# 日中にヒストリカルデータを複数日分取得すると,
# 「過去4日分と今現在の価格」が取得できます.現在価格はhistorical data 同様,アジャストされた価格です.
price_history = data.history(
context.security,
fields='price',
bar_count=5,
frequency='1d'
)
# price_historyを出力
# log.info(price_history)
# 平均値
average_price = price_history.mean()
# 現在の価格
current_price = data.current(context.security, 'price')
# log.info(current_price)
# 注文しようとしている銘柄が,現在上場されているか確認
if data.can_trade(context.security):
# 平均値より,1%大きければ,Long
if current_price > (1.01 * average_price):
# 成り行きで10株買う
order(context.security, 10)
log.info("Buying %s" % (context.security.symbol))
# 平均値より小さければ,ポジションをクローズ
elif current_price < average_price:
# 0と注文することでポジションを精算することになる
order_target(context.security, 0)
log.info("Selling %s" % (context.security.symbol))
# 平均値と現在価格を描画
record(current_price=current_price, average_price=average_price)
メモ
rebalance
関数は毎日取引終了1分前に実行されるようにスケジュールしています.よって,条件に会えば毎日でも10株買い足して行くというアルゴリズムになります.
次はこれ
気が向いた時に,アルゴリズムの注文方法を少しずつ書いていこうと思います.
次回は,order_value
です.
他のオーダー方法
#Quantopian Algorithm で order_value - Qiita
#Quantopian Algorithm で order_percent - Qiita
#Quantopian Algorithm で order_target
#Quantopian Algorithm で order_target_value