Back to Community
Buy to Rebalance & Cash Contributions

I generally subscribe to the bogleheads theory when it comes to investing: buy the market and hold. So Quantopian at first wouldn't seem like a great fit for someone like me; but I was and am very excited to use Quantopian for a buy & hold "strategy." Over the last couple years I've invested in the iShares ETFs which are available commission free via Fidelity. I've had a monthly contribution to the Fidelity account which required me to log in periodically and put my cash to work in these core ETFs. The trouble was that I'd forget or be too busy often times to invest the money I was contributing monthly. When I would log in and be ready to invest the money it would take me a little bit of time to calculate how many of each asset class I should buy to keep my asset allocation in line with my long term target. But with quantopian I can automate all of this!

So I developed an algorithm to look for cash in my account. When there is cash it calculates how many shares of each asset class/ETF it should buy to get to my target asset allocation. I'm an engineer so I wanted to have some "fun" with the algorithm; so instead of blindly placing market orders it places limit orders at the 10 day moving average. This helps protect against sudden price surges, and also helps when above the average by waiting to not buy at the peak. Such a script would minimize my cash drag by investing automatically; and it would minimize the number of transactions I need (cutting costs and taxes) by only buying to keep my target allocation = no selling required!

Unfortunately though Quantopian doesn't allow for you to simulate cash contributions into an account. But for backtesting, I added a function which is called monthly that cuts the current allocation in half to simulate a deposit into the account or an addition of cash. After some playing around I was ready to put the strategy to work with a Robinhood account I opened! But then I had a problem with Quantopian thinking a cash contribution was an investment return which I'll cover in the next post...

Clone Algorithm
11
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 581c93a6199a40132e3bd5bb
There was a runtime error.
6 responses

After developing my buy to rebalance algorithm I linked it to my Robinhood account I opened. I funded the account with only $300 to start to make sure the algorithm was working correctly. At 11:30 yesterday morning it "came alive" and ordered a couple ETFs at the 10 day SMA. I was pumped, it was working! So I immediately deposited another $500 into the account; but this is when I had a small problem. Quantopian saw this addition of cash as an investment return so my performance skyrocketed.

I tweaked my algorithm to track contributions by looking for additions of cash into the account from the day before. Now some cash additions will be from dividends so I had to add a little bit of smarts by looking for cash additions that are a multiple of $100. It's very unlikely a dividend payout will be an even hundred dollars, so as long as my contributions are a multiple of $100 the algorithm will correctly track the total contributions and plot them against my portfolio value. Unfortunately I'll have to ignore the Quantopian reported returns; but with the records feature and my tracked variables I have everything I need!

Check out the algorithm. I'm also curious to hear what people think of my asset allocation. I had done quite a lot of backtesting with annual data going back to the 70s to get this asset allocation which, historically, offers superior risk adjusted returns to the more traditional asset allocations that are found in target date funds or a total stock market fund.

Clone Algorithm
22
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 581c903ae90249106c7a4530
There was a runtime error.

Preface: I'm new to Quantopian (just started 1 day ago) and coding (2 months ago). My financial eduction and stock trading experience is beginner to intermediate.

Given that, I really like your approach to buy and holding within your programming. I feel that a lot of the algorithms that I've seen could result in too many short term capital gains and wash sales due to constant/near constant rebalancing, and leverage use. I've played around with many different combinations of weights and equities; this latest one was using leveraged ETFs. It clearly won't win me any contests due to it's volatility. Thank you for your work.

Clone Algorithm
8
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 59469403e1c61869d52ad32d
There was a runtime error.

Personally, as far as your allocation, I think the country and sector specific funds are too risky. I know that you're trying to differentiate, however in my opinion, less is more. You have a good selection, I would trim exposures to, FM, EZA, EWD. Otherwise, I like your setup

I'll agree with Jonathan and suggest that less may be more. The number of ETFs this algo trades and their inferred diversity (many international equity and some specific sector funds) make this seem 'diversified'. The inference is that a 'diversified' portfolio reduces risk so this algo is less 'risky'.

The volatility and max drawdown (two measures of 'risk') as shown in the backtest overview are 12% and -17.7% respectively over the the backtest time period. If the same algorithm is run but invested in a single SP500 ETF SPY, the volatility and drawdown are 14% and -12.8%. Not too different (and the returns would have been almost double). Also notice that the alpha and beta for the algorithm over that time are -.02 and .83. This implies that most of the algo returns come from correlation with the SP500 and virtually none (actually a negative 2%) is derived by the algo secret sauce.

Even though this invest in a number of different funds it's still very highly correlated with the market (83% correlation). The number of funds may seem good on the surface but it's not really getting you anything.

Try a simple half SP500 and half bond strategy. Attached is the same algorithm but investing half and half in SPY and TLT. By all measures the performance is better. Volatility and drawdown are cut in half. beta is now .32 and the icing on the cake is returns are doubled. Less is often more. Because so many markets are so highly correlated, simply spreading the investments around doesn't decrease market risk. Look for assets which are both uncorrelated between each other but also uncorrelated with the market (typically SPY is a good market proxy).

A very promising strategy would be the same 50-50 equity/bond split but invest in 2X leveraged ETFs (try SSO and UBT). This will about double the volatility and drawdown but it will about double the returns. If one was willing to accept the initial 12% and 17% volatility and drawdown, then this would be about the same risk but with 6X the return of the original. This can also be seen in a 3X increase in the Sharpe ratio. Try it.

Clone Algorithm
8
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 5946b7975495d969f60c8783
There was a runtime error.

Jonathan, glad you found the code useful! I'll issue a small word of warning about Quantopian... I came to this with no intentions to pick stocks or write any market neutral strategies... but that's exactly what I started doing. I fell deep down a rabbit hole with pipeline but I think it's mostly been for my benefit. I have a few contest entries doing quite well, a Robinhood account doing a combination of strategies (both ETF and individual stocks), and also migrated my Roth IRAs to Interactive Brokers that are also now running on Quantopian algorithms.

I attached a cleaned up version that uses pandas (wasn't familiar with them at first). I also added in tax loss harvesting but it's commented out in the attached backtest. It may not be super appropriate without having access to tax lots. It also has an added line to let you take advantage of any Robinhood Gold that you may have access to.

In regard to the asset allocation... yeah it's definitely an attempt to be a bit different - but I think it's more than that. I tried to quantitatively find "optimal" asset allocation models that seem to love a small bit of Sweden and South Africa. I just posted a notebook and backtest that details how I came to these asset allocations (slightly different to what I first posted a few months ago).

Clone Algorithm
31
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 594c6a6189430269719696df
There was a runtime error.

With a couple of tweaks, I've utilized your code in a Robin Hood account, not this code but the previous one. I feel pretty confident in it. Tax loss harvesting is nice but I'm not in the tax bracket that can take full advantage of it... yet. Kudos to you for killing it in the contests.

Personally, I love volatility and leverage, both of which have been a boon to my live account for the past several years. In order for me to have any chance at the contests, I'll have to reframe how I see the market and moderate the use of leverage. I have my own trade style, however I need to learn how to write it. When I get a chance I'll peruse what you just shared and see what I can learn from it and perhaps make it better. Thank you for your work!