I'm not great with python (I've finished an online course but am still struggling at times) and I've recently been playing around with trying to filter my universe of stocks based on fundamentals but have hit some roadblocks.
I was trying to grab 20 stocks based on my fundamental filters and have each of those stocks hold 5% of the portfolio.
So I wanted to sell stocks that weren't in the 20, and allocate 5% to those stocks that were in the 20 and to make sure it doesn't overdraw on cash as well.
This is what I put:
def before_trading_start(context):
fundamental_df = get_fundamentals(
query(
"""Fundamental Criteria"""
.order_by(fundamentals.valuation_ratios.pe_ratio.asc())
.limit(20)
)
context.stocks = [stock for stock in fundamental_df]
context.fundamental_df = fundamental_df
update_universe(context.fundamental_df.columns.values)
def handle_data(context, data):
for stock in context.portfolio.positions:
if stock not in data:
order_target(stock, 0)
for stock in data:
if context.portfolio.cash >= 0.05 * context.portfolio.portfolio_value:
order_target_percent(stock, 0.05)
The above seems to buy the stocks, but never sells out of a position.
And i also tried this:
def handle_data(context, data):
for stock in context.portfolio.positions:
if stock not in context.fundamental_df:
order_target(stock, 0)
for stock in data:
if context.portfolio.cash >= 0.05 * context.portfolio.portfolio_value:
order_target_percent(stock, 0.05)
Any insights would be appreciated.