I want to find out how a stock changes between the hours of 10 and 12PST. How do I do this when it seems the get_prices() method doesn't have keys for the date/time...I can only access the prices...?
I want to find out how a stock changes between the hours of 10 and 12PST. How do I do this when it seems the get_prices() method doesn't have keys for the date/time...I can only access the prices...?
import pandas as pd
def initialize(context):
context.stock = sid(19725)
context.price_10 = context.price_12 = 0
def handle_data(context, data):
time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern').time()
minute_high = data.current(context.stock, 'price')
if time.hour == 10 and time.minute == 0:
context.price_10 = minute_high
log.info("The price is %s at %s" % (context.price_10, time))
if time.hour == 12 and time.minute == 0:
context.price_12 = minute_high
log.info("The price is %s at %s" % (context.price_12, time))
log.info("The difference between 10 am and 12 pm is: %s" % (context.price_12-context.price_10))
record(price10 = context.price_10)
record(price12 = context.price_12)
record(difference = context.price_12-context.price_10)
That worked. Although, I have a feeling you can index more appropriately with pandas:
https://pandas.pydata.org/pandas-docs/stable/timeseries.html
Miles's idea with using the '.tz_convert' method is the way to go. Since the question was " How do I do this when it seems the get_prices() method doesn't have keys for the date/time" I'll assume this is for a notebook. Actually, the index of the result from the 'get_prices' method IS a datetime.
# set the start and stop date-time.
# note that times are specified in UTC
start_date = '2013-01-03'
end_date = '2013-01-04'
my_prices_utc = get_pricing(symbols=symbols('AAPL'),
start_date=start_date,
end_date=end_date,
frequency='minute',
fields='close_price')
my_prices_et = my_prices.tz_convert('US/Eastern')
# Because of the nuances with timezones I like to create a separate hours column
# if one wants to check for certain hours
my_prices_et['hour'] = my_prices_et.index.hour
# Now to get only prices between certain hours one can use the '.query' method
my_prices_et.query('hour >= 10 & hour <= 12')
See the attached notebook (the last several cells) for this in action