I'm very confused. I tried to use get_fundamentals to filter out some stocks.
There are two lines of "order_by" in the code snippet below.
#.order_by(fundamentals.valuation_ratios.pe_ratio)
.order_by(fundamentals.valuation_ratios.peg_ratio)
If I use it as is, it does not work. The debug message always shows 0 stocks in updated universe.
Instead, if comment out the "peg_ratio" line and uncomment the "pe_ratio" line, everything works just fine.
What did I do wrong with peg_ratio? I'd expect some outputs no matter what kind of value peg_ratio is.
Any advice?
import pandas as pd
import numpy as np
def initialize(context):
context.num_stocks = 10
# Rebalance monthly on the first day of the month at market open
schedule_function(rebalance,
date_rule=date_rules.month_start(),
time_rule=time_rules.market_open())
def rebalance(context, data):
# Exit all positions before starting new ones
for stock in context.portfolio.positions:
if stock not in context.fundamental_df and stock in data:
order_target_percent(stock, 0)
# Rebalance all stocks to target weights
for stock in context.stocks:
pct = 1.0/len(context.stocks)
log.debug("stock = %s, pct = %f" % (stock.symbol, pct))
order_target_percent(stock, pct)
def before_trading_start(context, data):
context.fundamental_df = get_fundamentals(
query(
# put your query in here by typing "fundamentals."
fundamentals.valuation.market_cap
)
#.filter(fundamentals.valuation_ratios.peg_ratio != 0)
.filter(fundamentals.valuation.market_cap > 200000000)
.filter(fundamentals.valuation.market_cap < 10000000000)
#.order_by(fundamentals.valuation_ratios.pe_ratio)
.order_by(fundamentals.valuation_ratios.peg_ratio)
.limit(context.num_stocks)
)
context.stocks = [stock for stock in context.fundamental_df]
log.debug("number of stocks in updated universe : %d" % len(context.stocks))
update_universe(context.stocks)
def handle_data(context, data):
# track how many positions we're holding
record(num_positions = len(context.portfolio.positions))