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.

285

20.2.5 Python Implementation

We are quite lucky when working with Python and its library ecosystem as much of the "heavy

lifting" is done for us. Using Pandas, Scikit-Learn and Matplotlib, we can rapidly create some

examples to show the usage and issues surrounding cross-validation.

Obtaining the Data

The first task is to obtain the data and put it in a format we can use. I have actually carried out

this procedure in my previous book Successful Algorithmic Trading but I would like to have this

section as self-contained as possible. Hence you can use the following code to obtain historical

data from any financial time series available on Yahoo Finance, as well as their associated daily

predictor lag values:

from __future__ import print_function

import datetime

import pprint

import numpy as np

import pandas as pd

import pandas_datareader.data as web

import sklearn

def create_lagged_series(symbol, start_date, end_date, lags=5):

"""

This creates a pandas DataFrame that stores

the percentage returns of the adjusted closing

value of a stock obtained from Yahoo Finance,

along with a number of lagged returns from the

prior trading days (lags defaults to 5 days).

Trading volume, as well as the Direction from

the previous day, are also included.

"""

# Obtain stock information from Yahoo Finance

ts = web.DataReader(

symbol,

"yahoo",

start_date - datetime.timedelta(days=365),

end_date

)

# Create the new lagged DataFrame

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

tslag["Today"] = ts["Adj Close"]

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

Saved successfully!

Ooh no, something went wrong!