13.08.2022 Views

advanced-algorithmic-trading

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

286

tslag["Volume"] = ts["Volume"]

# Create the shifted lag series of

# prior trading period close values

for i in range(0,lags):

tslag["Lag%s" % str(i+1)] = ts["Adj Close"].shift(i+1)

# Create the returns DataFrame

tsret = pd.DataFrame(index=tslag.index)

tsret["Volume"] = tslag["Volume"]

tsret["Today"] = tslag["Today"].pct_change()*100.0

# If any of the values of percentage

# returns equal zero, set them to

# a small number (stops issues with

# QDA model in scikit-learn)

for i,x in enumerate(tsret["Today"]):

if (abs(x) < 0.0001):

tsret["Today"][i] = 0.0001

# Create the lagged percentage returns columns

for i in range(0,lags):

tsret["Lag%s" % str(i+1)] = tslag[

"Lag%s" % str(i+1)

].pct_change()*100.0

# Create the "Direction" column

# (+1 or -1) indicating an up/down day

tsret["Direction"] = np.sign(tsret["Today"])

tsret = tsret[tsret.index >= start_date]

return tsret

Note that we are not storing the direct close price values in the "Today" or "Lag" columns.

Instead we are storing the close-to-close percentage return from the previous day.

We need to obtain the data for Amazon daily prices along some suitable time frame. I have

chosen Jan 1st 2004 to Oct 27th 2016. However this is an arbitrary choice. You can adjust the

time frame as you see fit. To obtain the data and place it into a Pandas DataFrame called lags

we can use the following code:

if __name__ == "__main__":

symbol = "AMZN"

start_date = datetime.datetime(2004, 1, 1)

end_date = datetime.datetime(2016, 10, 27)

lags = create_lagged_series(

symbol, start_date, end_date, lags=10

)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!