# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
import numpy as np
import math
from sqlalchemy import or_
def initialize(context):
context.limit = 500
schedule_function(rebalance,
date_rule = date_rules.month_start(),
time_rule = time_rules.market_open())
def before_trading_start(context):
context.security = get_fundamentals(
query(fundamentals.valuation.market_cap,
fundamentals.company_reference.primary_exchange_id)
.filter(fundamentals.valuation.market_cap > 4e9)
.filter(fundamentals.company_reference.country_id == "USA")
.filter(or_(fundamentals.company_reference.primary_exchange_id == "NAS", fundamentals.company_reference.primary_exchange_id == "NYS"))
.order_by(fundamentals.valuation.market_cap.desc())
.limit(500)
) # S&P 500 rebalances on an as needed basis, so we'll just use today
update_universe(context.security.columns.values)
def rebalance(context,data):
for stock in data:
prices = history(bar_count = 253, frequency = '1d', field = 'price')
pct_change = (prices.ix[-252] - prices.ix[232]) / prices.ix[232]
pct_change2 = (prices.ix[-126]-prices.ix[-42]) / prices.ix[-42]
theory1 = pct_change+pct_change2
uptheory1 = np.percentile(theory1, 50)
most_theory = theory1[theory1>uptheory1]
amount = context.portfolio.positions[stock].amount
if stock not in most_theory:
order(stock, -amount)
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
prices = history(bar_count = 253, frequency = '1d', field = 'price')
pct_change = (prices.ix[-252] - prices.ix[232]) / prices.ix[232]
pct_change2 = (prices.ix[-126]-prices.ix[-42]) / prices.ix[-42]
theory1 = pct_change+pct_change2
uptheory1 = np.percentile(theory1, 50)
most_theory = theory1[theory1>uptheory1]
#print uptheory1
print most_theory
#print pct_change
#print pct_change2
for stock in context.stocks:
cash = context.portfolio.cash
price = data[stock].price
if stock in most_theory:
if cash > 0:
hope = (math.floor(cash/price))/4
order(stock, hope)