How would I write a code that returns max price of a stock in my portfolio since it was purchased?
How would I write a code that returns max price of a stock in my portfolio since it was purchased?
There's two issues here. First, keeping track of how long one has held a security, and second, finding the highest high during that time.
Many ways to keep track of how long a security has been held. Creating a simple python dic could serve the purpose. The values could be the number of trading days that security has been held. Increment and update this dic every trading day in 'before_trading_start'. Maybe something like this.
def initialize(context):
# Create a dic to hold "days held" value for each security in our current portfolio
context.held_days = {}
def before_trading_start(context, data):
# Update and increment our 'days_held' dic
# This keeps track of how long we have held our current holdings
# We create a new dic with values equal to the current dic + 1
# Note that the 'get' method returns a 0 value if the security isn't in the current list
# Set the context.held_days to this new dic.
# This avoids having to delete old positions from dic
held_days = {security: (context.held_days.get(security, 0) + 1)
for security in context.portfolio.positions}
context.held_days = held_days
The next task is to find the highest high within the past days which a security was held. This can be done with 'data.history' looping through all ones holdings. Something like this. If the number of holdings is high, it may however be more efficient to get ALL the data first.
def log_highs(context,data):
"""
Log the highest high of each currently held security since it was opened
Note this isn't really exact. It does not include the high on the day it was purchased.
"""
log.info('holding {} securities'.format(len(context.portfolio.positions)))
for security, lookback in context.held_days.items():
highs = data.history(security, 'high', lookback, '1d')
max_high = highs.max()
log.info('{} had a high of {}'.format(security, max_high))
As the comment in the code notes, this may not be entirely accurate. It does NOT look at pricing on the day the security was purchased which may have had a high.
See the attached algo and especially the logs to see these two in action.
Good luck.
Adapted this to record highs. A little more interesting if you click the AMZN chart legend item to toggle that trace off.