Hello, I am an aspiring quant (I'm eighteen years old) with limited Python knowledge. I am struggling to make my system do certain things and behave as expected.
Note: My system uses moving average crossovers as buy and sell triggers. Should be pretty simple, but I am having the following problems:
1) Logging the price at which my system buys a stock. (Useful for future debugging I hope.) Also logging (price x number of shares purchased) (does Quantopian call this amount?) would be helpful.
2) Preventing my system from using leverage! Included with this, I would like to log my remaining cash at the end of each transaction.
3) Using the built-in portfolio object instead of the custom dictionary I created. (portfol[])
4) Making my code more user friendly/professional/efficient for future expansion. Also, removing useless code.
If anyone notices any major flaws in my logic/approach/code, please notify me.
Note: I realize that this code is extremely primitive, as I am trying to grasp the basics of Quantopain by constructing a simple algorithm and then expanding from there. Any other general tips are would be much appreciated. Thanks!
def initialize(context):
set_symbol_lookup_date('2012-01-01')
set_universe(universe.DollarVolumeUniverse(floor_percentile=99.0, ceiling_percentile=100.0))
context.max_notional = 10000.1
context.min_notional = -10000.0
context.init_margin=1.00 #Set initial margin requirement
context.pct_invested_threshold = 0.95
def handle_data(context, data):
buying_power = context.account.buying_power
for stock in data:
current_price = data[stock].price
moving_avg_20 = data[stock].mavg(20)
moving_avg_50 = data[stock].mavg(50)
moving_avg_200 = data[stock].mavg(200)
# BUYING:
mymoney = context.portfolio.cash
if moving_avg_50 > moving_avg_200 and mymoney > current_price and mymoney > 0 and buying_power > 0:
cash = context.portfolio.cash
context.buyorder_id = order_target_percent(stock, .10)
buy_order = get_order(context.buyorder_id)
tradeday = data[stock].datetime
log.info("Buying %s shares of %s on %s. Cash = %s" % ((buy_order.amount), (stock.symbol), (tradeday.strftime('%m/%d/%y')), (cash)))
global portfol
portfol = []
portfol.append(stock)
# SELLING:
if moving_avg_50 < moving_avg_200 and stock in portfol:
order_target(stock, 0)
tradeday = data[stock].datetime
log.info("Selling %s on %s" % ((stock.symbol), (tradeday.strftime('%m/%d/%y'))))
portfol.remove(stock)