[PYTHON] Quantopian Tutorial LESSON 6

This is a continuation of Last time.

LESSON 6 The history() Function

The data.history () method [^ 1] gets historical data. The arguments to pass are as follows.

position keyword value
1 Instance of the brand
2 fields 'price', 'open', 'high', 'low', 'close'
3 bar_count The number of data
4 frequency frequency

The return value will be of pandas DataFrame type. In the example below, we get the price for 10 days of AAPL and calculate the average.

# Get the 10-day trailing price history of AAPL in the form of a Series.
hist = data.history(sid(24), 'price', 10, '1d')

# Mean price over the last 10 days.
mean_price = hist.mean()

By specifying '1d' in the 4th argument, data is acquired at a frequency of every day. If you specify '1m', you will get the data every minute.

If you specify '1d', the price for the day is also included. I think that the average up to the previous day is often used for trades that use the moving average as a guide. To calculate the average for 10 days up to the previous day, write as follows.

data.history(sid(8554), 'volume', 11, '1d')[:-1].mean()

Similar to data.current () introduced in LESSON 5, if multiple issues are specified, the DataFrame type of pandas will be returned.

# Get the last 5 minutes of volume data for each security in our list.
hist = data.history([sid(24), sid(8554), sid(5061)], 'volume', 5, '1m')

# Calculate the mean volume for each security in our DataFrame.
mean_volumes = hist.mean(axis=0)

If there are multiple brands and multiple fields are specified, the pandas Panel type [^ 2] will be returned.

# Low and high minute bar history for each of our securities.
hist = data.history([sid(24), sid(8554), sid(5061)], ['low', 'high'], 5, '1m')

# Calculate the mean low and high over the last 5 minutes
means = hist.mean()
mean_lows = means['low']
mean_highs = means['high']

The code below outputs the average volume of AAPL, MSFT, and SPY for 10 minutes.

def initialize(context):
    # AAPL, MSFT, SPY
    context.security_list = [sid(24), sid(8554), sid(5061)]

def handle_data(context, data):
    hist = data.history(context.security_list, 'volume', 10, '1m').mean()
    print hist.mean()

LESSON 5<-->LESSON7


[^ 1]: Notated as a method as before. [^ 2]: I've heard that Panel is integrated into xray. If anyone knows the details, please let me know.

Recommended Posts

Quantopian Tutorial LESSON 10
Quantopian Tutorial LESSON 1, 2
Quantopian Tutorial LESSON 6
Quantopian Tutorial LESSON 9
Quantopian Tutorial LESSON 5
Quantopian Tutorial LESSON 3
Quantopian Tutorial LESSON 7
Quantopian Tutorial LESSON 4
Quantopian Tutorial LESSON 11
sqlalchemy tutorial
PyODE Tutorial 2
Python tutorial
PyODE Tutorial 1
PyODE Tutorial 3
TensorFlow tutorial tutorial