Hi guys,
how could I avoid that the orders not filled into the day are deleted? I want that the orders would spread in days
Hi guys,
how could I avoid that the orders not filled into the day are deleted? I want that the orders would spread in days
There's no way to keep orders from being deleted at the end of the day. On the Quantopian platform all orders are considered to be ' day' orders.
However, a straightforward method to 'carry over' orders from day to day is simply to use the target percent order types and place the order again. If one wants to order AAPL worth 50% of their portfolio then do something like this
# Using the 'order_target_percent' method
order_target_percent(symbol('AAPL'), 0.5)
# Or using the 'order_optimal_portfolio' method
securities_to_trade_list = symbols('AAPL')
weight_list = [0.5]
securities_to_trade_with_weights = pd.Series(index = securities_to_trade_list, data = weight_list)
weight_objective = opt.TargetWeights(securities_to_trade_with_weights)
order_optimal_portfolio(objective = weight_objective, constraints = [])
Simply repeat this over several days. If, for some reason a part of the order fails to fill the first day, any remaining will fill on subsequent days. Now, this isn't perfect but it's straightforward.
A more involved method would be to loop through all open orders just before the end of each day. Store the values. Cancel the orders. Then place the orders the next day. One thing to look out for is to place orders by value and NOT by share quantity. If there is a stock split overnight, ordering by share quantity will probably have undesirable results. Take a look at this post https://www.quantopian.com/posts/is-there-a-way-to-prevent-orders-from-being-cancelled-at-the-end-of-the-day .
Hi Dan.
Many thanks for your post above. I am trying to use it to code my first algorithm where the objective is a target weight for each asset I specify. However I seem to be getting an error 'AttributeError: 'str' object has no attribute 'end_date' when I call orders = algo.order_optimal_portfolio(objective = objective, constraints = []).
Please can you help on this and do let me know if I can provide anymore info.
I cant seem to attach the backtest so here is my code:
import quantopian.algorithm as algo
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import EquityPricing
from quantopian.pipeline.filters import QTradableStocksUS
from quantopian.pipeline.filters import StaticAssets
from quantopian.pipeline.domain import US_EQUITIES
import pandas as pd
import quantopian.optimize as opt
def initialize(context):
"""
Called once at the start of the algorithm.
"""
# Rebalance every day, 1 hour after market open.
algo.schedule_function(
rebalance,
algo.date_rules.every_day(),
algo.time_rules.market_open(hours=1),
)
# Record tracking variables at the end of each day.
algo.schedule_function(
record_vars,
algo.date_rules.every_day(),
algo.time_rules.market_close(),
)
# Create our dynamic stock selector.
algo.attach_pipeline(make_pipeline(), 'pipeline')
context.symbol_list = ['VTI', 'TLT', 'IEF', 'GLD', 'DBC']
context.weight_list = [1.0, 0, 0, 0, 0]
def make_pipeline():
"""
A function to create our dynamic stock selector (pipeline). Documentation
on pipeline can be found here:
https://www.quantopian.com/help#pipeline-title
"""
# Base universe set to the QTradableStocksUS
#Create a reference to our trading universe
base_universe = StaticAssets(symbols('VTI', 'TLT', 'IEF', 'GLD', 'DBC'))
# Get latest closing price
close_price = EquityPricing.close.latest
return Pipeline(
columns={
'close_price': close_price,
},
screen = base_universe,
domain=US_EQUITIES,
)
def before_trading_start(context, data):
"""
Called every day before market open.
"""
context.output = algo.pipeline_output('pipeline')
# These are the securities that we are interested in trading each day.
context.security_list = context.output.index
context.stocks = context.output.index
num = len((context.stocks))
print('%s stocks in pipeline' % num)
def rebalance(context, data):
"""
Execute orders according to our schedule_function() timing.
"""
# Create position size constraint
asset_list = context.symbol_list
weight_list = context.weight_list
assets_to_trade_with_weights = pd.Series(index = asset_list, data = weight_list)
objective = opt.TargetWeights(assets_to_trade_with_weights)
orders = algo.order_optimal_portfolio(objective = objective, constraints = [])
# One could log the orders which were placed
for order_id in orders:
order = algo.get_order(order_id)
log.info('ordered {} shares of {}'.format(order.amount, order.sid))
@Ojas Kulkarni Take a look at your other post (https://www.quantopian.com/posts/trouble-calling-algo-dot-order-optimal-portfolio-using-target-weights). I replied in that thread.
Good luck.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.