Hi Everyone,
I am trying to follow Quantopian Lecture Series and I have some questions regarding this beautifully written algorithm that I cloned from "Beta Hedging" Example of Quantopian Lecture 4.
First question:
def buy_assets(context, data):
all_prices = history(1, '1d', 'price', ffill=True)
eligible_assets = [asset for asset in all_prices
if asset not in context.dont_buys
and asset != context.index]
pct_per_asset = 1.0 / len(eligible_assets)
context.pct_per_asset = pct_per_asset
for asset in eligible_assets:
# Some assets might cause a key error due to being delisted
# or some other corporate event so we use a try/except statement
try:
if get_open_orders(sid=asset):
continue
order_target_percent(asset, pct_per_asset)
except:
log.warn("[Failed Order] asset = %s"%asset.symbol)
In the above buy_assets() function, if there is open orders left from the previous period ( in this case, month ) for a particular asset, the algorithm leaves it alone. Won't that be
potentially problematic ? Because order_target_percent(asset, pct_per_asset) was called in the last period, and "pct_per_asset" for the current period would most likely be different from
that of the previous period.
Second Question:
def before_trading_start(context, data):
# Number of stocks to find
num_stocks = 100
fundamental_df = get_fundamentals(
query(
# To add a metric. Start by typing "fundamentals."
fundamentals.valuation_ratios.earning_yield,
fundamentals.valuation.market_cap,
)
.filter(fundamentals.valuation.market_cap > 1e9)
.order_by(fundamentals.valuation_ratios.earning_yield.desc())
.limit(num_stocks)
)
update_universe(fundamental_df)
My understanding is that when the universe is updated, stocks that qualify that fundamental metrics, ( columns of fundamental_df) are added and the ones that don't qualify would be kicked
out of the universe. If so, there should be only around 100 stocks any given day. My test shows that is not the case as you can see in custom data plot as
stocks_in_universe
What happens to the stocks that are already in the portfolio ? Will they still be part of the universe ? When do stocks leave universe?
And, would those stocks, ( stocks that are already in the portfolio, but didn't pass the fundamental test) show up when
all_prices = history(1, '1d', 'price', ffill=True)
is called ? If this is the case, they can still be part of
eligible_assets
even though they didn't pass the fundamental test. Won't that be against the underlying strategy ?
Third Question:
Beta of the strategy is calculated by taking the average of beta of individual assets. What if we calculate beta using the returns of the whole portfolio? What are the pros and cons ?