Hi this is the first algorithm I've written and it is very simple. I want to implement an approximation of the 'magic formula' of Joel Greenblatt. I want the algorithm to:
- run once a month at market open on the first trading day of the month
- find the list of stocks at this time that have greater than 25% return on equity
- sort this list to find the company with the lowest price to earnings ratio greater than five
- place a market order for that stock to a value of $83333
- after exactly one year of holding the stock, place a market sell order
- repeat until end of back test.
Here is my code so far:
def before_trading_start(context):
fundamental_df = get_fundamentals(
query(
fundamentals.operation_ratios.roa,
fundamentals.valuation_ratios.pe_ratio
)
.filter(fundamentals.operation_ratios.roa > 0.25)
.filter(fundamentals.valuation_ratios.pe_ratio > 5)
.order_by(fundamentals.valuation_ratios.pe_ratio)
.limit(1)
)
update_universe(context.fundamental_df.columns.values)
def initialize(context):
pass
def handle_data(context, data):
order_value(security, 83333)
I'm pretty sure the before_trading_start(context) method will put one stock into my universe that has the required attributes but I'm not really sure where to go from here.
My questions are:
How do I access the stock that I placed into the universe? i.e. how do I buy the stock that the algorithm has found
How do I get the algorithm to run once at the start of every month? also if the start of the month is a day that the market is not open, like a weekend, how would that affect the algorithm?
Thanks any help appreciated.