0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

zipline 銘柄を売買する関数

Last updated at Posted at 2020-06-20

1 この記事は?

銘柄を売買するコマンドを紹介します。

2 内容

コード実行時に使用した銘柄n1570とn7752のcsvファイルはこちらから取得ください

2-1 zipline.api.order

指定した株数を購入する。

test.py
from zipline.api import order, record, symbol,set_benchmark
import pandas as pd
from datetime import datetime
import zipline
import pytz  # timezoneの設定 https://narito.ninja/blog/detail/81/
from trading_calendars import get_calendar #各取引所のカレンダーを取り込む
from collections import OrderedDict
import seaborn as sns
import matplotlib.dates as mdates
import matplotlib.pyplot as plt


###### (1)初期設定 #######

HDIR="xxxxxxxxxxxxxxxxxx" #銘柄データcsvファイルが格納されているディレクトリを指定する。
data=OrderedDict() #順序付き辞書に順番を持たせる。
tickers=["n1570","n7752"]  #銘柄名を指定する。


###### (2)csvファイルから銘柄の株価を読み込む ######

for ticker in tickers:
    DIR=HDIR + ticker +".csv" #読み込む銘柄(csvファイル)を指定する。
    data[ticker]= pd.read_csv(DIR, index_col=0,parse_dates=True) #csvファイルを読み込む。

###### (3)データセットを用意する。 ###########

panel=pd.Panel(data)  #3次元配列panelに銘柄データを入れる。
panel.major_axis=panel.major_axis.tz_localize(pytz.utc) #時刻をUTCゾーンにする。(便宜的にUTCゾーンにしないとエラーになる)


###### (4) トレードアルゴリズムの記述 #########

def initialize(contect):
    set_benchmark(symbol("n1570")) #銘柄n1570をベンチマークに指定する。


def handle_data(context,data):
    order(symbol("n1570"),1) #毎日大引けで1株購入する。
    record(N1570=data.current(symbol("n1570"),"price")) #銘柄n1570のclose値を記録する。


###### (5) バックテストを実施する #########    
    
# 開始日時と終了日時を指定する    
starttime=datetime(2020,2,4,0,0,0,0,pytz.utc)
endtime=datetime(2020,2,8,0,0,0,0,pytz.utc)    
    
# バックテストを実行する。(毎日大引けで銘柄n1570を1株購入する。)
perf=zipline.run_algorithm(start=starttime,
                            end=endtime,
                            initialize=initialize,
                            capital_base=1000000, #スタート時のアセットを指定する。
                            handle_data= handle_data,
                            data=panel,
                            trading_calendar=get_calendar('XTKS') #東京証券取引所のカレンダーを読み込む
                           )

dat0=pd.DataFrame(perf,columns=["N1570","ending_cash","ending_exposure"])

dat0.to_csv("C:/Users/fdfpy/anaconda3/backtestresult/dat0.csv")
print(dat0)

実行結果は下記です。

[4 rows x 38 columns]
                           N1570  ending_cash  ending_exposure
2020-02-04 06:00:00+00:00  21240  1000000.000              0.0
2020-02-05 06:00:00+00:00  21680   978309.159          21680.0
2020-02-06 06:00:00+00:00  22750   955547.783          45500.0
2020-02-07 06:00:00+00:00  22630   932906.467          67890.0

(注)各行の説明
N1570           : 銘柄N1570のCLOSE値
ending_cash     : 手持ちの現金
ending_exposure : 保有銘柄の評価額

2-2 zipline.api.order_percent

手持ちの現金に対して、指定した割合の範囲内で銘柄を購入します。
2-1で掲載したコードのうち「(4)トレードアルゴリズムの記述」の部分のみ掲載します。(他の箇所は同じです)

test.py
###### (4) トレードアルゴリズムの記述 #########

def initialize(contect):
    set_benchmark(symbol("n1570")) #銘柄n1570をベンチマークに指定する。


def handle_data(context,data):

    zipline.api.order_percent(symbol("n1570"),0.1) #毎日大引けで全資産のpercent(=10%)に当たる株式を購入する
    record(N1570=data.current(symbol("n1570"),"price")) #銘柄n1570のclose値を記録する。
[4 rows x 38 columns]
                           N1570  ending_cash  ending_exposure
2020-02-04 06:00:00+00:00  21240  1000000.000              0.0
2020-02-05 06:00:00+00:00  21680   913236.636          86720.0
2020-02-06 06:00:00+00:00  22750   822191.132         182000.0
2020-02-07 06:00:00+00:00  22630   731625.868         271560.0

(説明)
毎日保有資産(ending_cash)の10%の金額の株価を購入しています。(端数は切り捨て処理です)

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?