So here we will talk about order management. By default on Quantopian there is no limit as to how much money you can borrow and invest in your algorithm, but in reality this isn't realistic. So here we will take a look at how to control the amount of money you invest.
def initialize(context)
context.stock = sid(xtl) <---- now here, when you type in 'xtl' it will appear as '40768'.
def before_trading_start(context, data):
pass
# Called every minute
def handle_data(context, data):
open_orders = get_open_orders()
if context.stock not in open _orders:
order_target_percent(context.stock, 1.00)
record(cash = context.portfolio.cash)
What you see here in the 'order_target_percent(context.stock, 1.00) is the order we are placing for 100% (1.00) of the stock. Then we use the record function to plot the cash in my portfolio at the end of each day (even though we are in minute mode).
After you have written the code above, go ahead and hit the 'build' button.
When the build is finished, you will notice that the cash dips below zero, this is because we are investing borrowed money.
For this example, let's say we don't want to borrow any money, we just want to invest what is in our capital base.
Now, you might be wondering 'I already ordered 100% of my portfolio value so why is it ordering more?" The answer is because sometimes an order takes more than a bar to fill. Like with what is happening in our order. Remember, we are ordering more than a million dollars of XTL shares, and in every bar after that we are making similar-sized orders because our original order has not yet filled. Each of these order are going to stack up on each other to the point where, at the end, when all the orders are resolved, you will end up in a much bigger position in XTL than you had originally planned. To prevent this, we can use the function get_open_orders to see which securities we have placed orders for that have not yet been filled. The get_open_orders is going to give us a dictionary keyed by security ID of our open orders. So, if we hit the 'build' button again after inserting this function, we will notice that we are no longer borrowing a lot of money. The number we get is not zero (what we want) and this is due to slippage which we will discuss later.
So let's look at ticker XTL, using an algorithm that uses order-target percent to order 100% of our portfolio in XTL in a minute!
I hope you enjoyed this lesson about managing orders in Quantopian, as always, if you have any questions or comments please feel free to leave feedback!
No comments:
Post a Comment