[PYTHON] zipline Function to buy and sell stocks

1 What about this article?

Introducing commands to buy and sell stocks.

2 Contents

Get the csv files for the brands n1570 and n7752 used to run the code get here

2-1 zipline.api.order Purchase the specified number of shares.

test.py


from zipline.api import order, record, symbol,set_benchmark
import pandas as pd
from datetime import datetime
import zipline
import pytz  #timezone settings https://narito.ninja/blog/detail/81/
from trading_calendars import get_calendar #Import the calendar of each exchange
from collections import OrderedDict
import seaborn as sns
import matplotlib.dates as mdates
import matplotlib.pyplot as plt


###### (1)Initial setting#######

HDIR="xxxxxxxxxxxxxxxxxx" #Specify the directory where the brand data csv file is stored.
data=OrderedDict() #Give order to the ordered dictionary.
tickers=["n1570","n7752"]  #Specify the brand name.


###### (2)Read the stock price of a stock from a csv file######

for ticker in tickers:
    DIR=HDIR + ticker +".csv" #Brand to read(csv file)To specify.
    data[ticker]= pd.read_csv(DIR, index_col=0,parse_dates=True) #Read the csv file.

###### (3)Prepare the data set.###########

panel=pd.Panel(data)  #Put the brand data in the 3D array panel.
panel.major_axis=panel.major_axis.tz_localize(pytz.utc) #Set the time to the UTC zone.(An error will occur if the UTC zone is not set for convenience.)


###### (4)Description of trading algorithm#########

def initialize(contect):
    set_benchmark(symbol("n1570")) #Designate brand n1570 as a benchmark.


def handle_data(context,data):
    order(symbol("n1570"),1) #Buy one share every day at the close.
    record(N1570=data.current(symbol("n1570"),"price")) #Record the close value of issue n1570.


###### (5)Perform backtesting#########    
    
#Specify start date and time and end date and time
starttime=datetime(2020,2,4,0,0,0,0,pytz.utc)
endtime=datetime(2020,2,8,0,0,0,0,pytz.utc)    
    
#Run backtest.(Buy one share of brand n1570 at the close every day.)
perf=zipline.run_algorithm(start=starttime,
                            end=endtime,
                            initialize=initialize,
                            capital_base=1000000, #Specify the asset at the start.
                            handle_data= handle_data,
                            data=panel,
                            trading_calendar=get_calendar('XTKS') #Read the Tokyo Stock Exchange calendar
                           )

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

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

The execution result is as follows.

python


[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

(note)Description of each line
N1570           :CLOSE value of brand N1570
ending_cash     :Cash on hand
ending_exposure :Valuation value of stocks held

2-2 zipline.api.order_percent Purchases stocks within the specified ratio of cash on hand. Of the code posted in 2-1 only, the part "(4) Description of trading algorithm" is posted. (Other parts are the same)

test.py


###### (4)Description of trading algorithm#########

def initialize(contect):
    set_benchmark(symbol("n1570")) #Designate brand n1570 as a benchmark.


def handle_data(context,data):

    zipline.api.order_percent(symbol("n1570"),0.1) #Close every day and percent of all assets(=10%)Buy the stock that corresponds to
    record(N1570=data.current(symbol("n1570"),"price")) #Record the close value of issue n1570.

python


[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

(Description)
Daily assets(ending_cash)10 of%I am buying the stock price of the amount of.(Fractions are truncated)

Recommended Posts

zipline Function to buy and sell stocks
Buy and sell cryptocurrencies using Zaif API
Introduction to Thano Function definition and automatic differentiation
Introduction to Deep Learning ~ Localization and Loss Function ~
[Python] How to use hash function and tuple.
[Cistre] Buy and sell with moving average MACD ♬
Let Code Day 19 Starting from Zero "121. Best Time to Buy and Sell Stock"
I tried LeetCode every day 121 Best Time to Buy and Sell Stock (Python, Go)
How to define Decorator and Decomaker in one function
I tried LeetCode every day 122. Best Time to Buy and Sell Stock II (Python, Go)