Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Efficient method to Get returns over a past period?

Hi,

For each day my algorithm is runned, I want to compute equity returns for the past 6 months. How can I do this without having to get_pricing daily between today and today-6months and then compute returns? My actual method gather way too many information for what I need. Here's a sample code of what i'm doing right now:

hist_PX= get_pricing(
fund_df.columns,
fields='close_price',
start_date = lookbackfrom,
end_date = today,
frequency='daily',
)
PXret = hist_PX.iloc[[0, -1]].pct_change()

Thank you Q community!

3 responses

Hello Thierry,
You could use context.portfolio.cash or context.portfolio.portfolio_value as long as your portfolio is not hedged. Then knowing the initial sum of $ at the begining of the test you could do something like this (replace the 10000 with your starting amount):

Equity_return = context.portfolio.portfolio_value - 100000
record(Equity Return=Equity_return)

Hi Darth,
Actually, I'm interested in individual stocks returns, not in my portfolio return.

I can calculate returns over 6 months for one stock, but in order to do so, I request the pricing of this stock for everyday during 6 months. It's a slow process and I get more prices than I really need. Ideally, I would request only 2 prices: the price of today and the price 6 months ago. Any Idea how I can do this?

Thanks

Would this work?:
for stock in context.portfolio.positions:
price = data[stock].price
purchase_price = context.portfolio.positions[stock].cost_basis
pcentreturn = price/purchase_price