Back to Community
Long-only non-day trading algorithm for live

This is a modified version of the algorithm presented in

I have run the backtest for the last year and confirmed it still continues to perform well. In addition to that, I started to run this algo connecting to a broker using the new open source library pylivetrader.

pylivetrader is a(nother) zipline-API-compatible trading framework in python which focuses on live
trading, with less overhead and fewer dependency problems. It is written from the ground up for live trading use cases, so it removes the requirements for a data bundle that was a heavy task for average users here. Data is instead retrieved from your broker or remote data provider (backend). At the moment, the only supported backend is Alpaca*, but we are happy to connect to IB etc. if someone contributes the code.

You can download the working example that converted this presented algo to the live version here.

I also assembled some guidelines for converting Quantopian algorithms to run in live trading more generally.

It’s a great community effort underway with knowledge and insights from everyone greatly appreciated in this forum, to enable algorithms in live trading independently. Again, this effort is going to be a continuous work and I'll keep improving both software and documentations, so please feel free to give me any questions or feedback.

* Brokerage services are provided to self-directed customers by Alpaca Securities LLC ("Alpaca"), member FINRA/SIPC. Alpaca is a wholly-owned subsidiary of AlpacaDB, Inc.

Clone Algorithm
Backtest from to with initial capital
Total Returns
Max Drawdown
Benchmark Returns
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: 5b9608732441fd443fb32d90
There was a runtime error.
44 responses

Thank you for sharing! Is there a way to hook this up to Robinhood/Interactive Brokers? I didn't see any of those brokers in your examples.


Thanks for asking. It has a plugin point to hook up with other API than Alpaca, but we haven't implemented Robinhood or IB yet. We'll be busy with improving its core functionality for the time being, but happy to accept other contribution to add code.

It's a miracle, the birth of an alternative to Robinhood on the side, Alpaca.

@Blue Seahawk Thanks!

@Blue Seahawk Thanks!
the pylivetrader Pipeline support morningstar ?

Pipeline API
This is the API under the quantopian.pipeline or zipline.pipeline package. pylivetrader does not provide direct replacement for pipeline, but you can use pipeline-live. You need to install this package separately as pylivetrader does not automatically include it. For more information, please read pipeline-live's migration document.

Under attach_pipeline and pipeline_output, pylivetrader uses the pipeline-live pakcage if it is installed, otherwise throws RuntimeError.

@Hitoshi - Quantopian doesn't really properly keep track of or enforce "buying power" limitations. The Q backtest makes no indication if you've placed orders for more than you have cash in your account -- it just lets you do it. The "leverage" variable doesn't factor in said "cash held for orders." There doesn't seem to be anything in this algorithm preventing it from placing orders with more than the actually available cash. So backtest results are probably inflated at least a bit due to this. In addition, it selects stocks from as low as the 6% lowest dollar volume stocks, which I believe is quite low volume. That combined with the fact that it orders in odd lots, I'd be surprised if it would perform well in real life. I'd expect significantly worse fills than the Q slippage model would suggest.

I'd be curious to see a side-by-side of Quantopian's simulation and a real live run.

@Nelson for morningstar support, we are discussing actively. There is no public API that someone can use by just signing up so that's the hardest point.

However, we also found that you can duplicate many things using default IEX without morningstar. The some of the fields are completely replaceable with IEX such as marketcap. Please also check out the migration example as well.

@Virdian Great point. I should admit I just copied the original post algo and reformatted without thinking much about leverage and odd lots. There should be some difference in the results between backtesting and real live testing, but I overheard also that some folks (more than one) were running this type of algo with Robinhood and performed quite well. I guess, one thing to note regarding the odd lot is that while it is true that odd lots might slip more than Quantopian backtesting simulation, the slippage may not be a biggest factor to the performance either. Especially, this algo doesn't aim day trading nor high frequent trading (though still notional size can be big), finding those potential spikes is the main driver of the performance here than perfecting slippage. I have been running it the broker paper trading for a week or so, and confirmed things like ALT were in the position (among many other stocks) that contributed a lot to the overall performance. I would say this type of universe, with many low dollar volume stocks, often work well for individual traders but not for large institutional asset managers.

Do you know if this trading algorithm requires a margin account? I was wondering what the purpose of holding for 1 day was, in other words how does it reduce risk?

This model runs with higher margin, but it does not require a margin account at all. It's just the performance may be lower as the re-investment is smaller.

Quick question for you Hitoshi. The title here says "non-day trading algorithm". It seems to be placing trades often enough, and turning over very frequently. What is the logic in the code that prevents the algorithm from fitting the definition of a "Pattern Day Trader" by Alpaca ( or FINRA (

[EDIT: oops, Does not rebalance once a day]

Just taking a cursory look, it would appear the context.age[stock] < 2check prevents it from selling stocks until they have been held for more than 2 days. I believe context.MyFireSaleAgeforces a sale after the stock has been held for more than 6 days, so you don't end up holding losing positions forever.

Thanks Viridian, yes that's exactly what I was going to write to Tanay!

I read too far into the "Rebalance":

    EveryThisManyMinutes = 10  
    TradingDayHours = 6.5  
    TradingDayMinutes = int(TradingDayHours * 60)  
    for minutez in xrange(  

It rescreens quite often but has different securities it adds through out the day if I understand correctly?

@ Hitoshi Harada, my apologies if you've already answered this question, but has this algorithm been tested on a live account?

Yes it keeps buying slowly a few securities throughout the day, and those are screened by the conditions defined in pipeline. So the "candidates" are consistent during the day but the buy logic go through the list of today's candidates and pick up a few every time "rebalance" runs.

That is Awesome! I've been working on a few side projects over the course of my career, but this takes the cake on the AWESOME scale. I would love to contribute to this project, is there anything in particular that you could use some help with?

It's been running in live and doing well for a few weeks now and it's doing what it is expected to do, while we have not compared the actual results between backtesting and live trading as we know there are divergence here like margin leverage, order filling and so on.

Thanks for the great interest! There are couple of issues waiting for fix/improvement in github, if you are interested in it.

More than anything, your help to get words out is very much appreciated!

Thanks Hitoshi, I'll take a look at the issues on github & help any way I can.

This is amazing.

Can you get fundamental data through Alpaca?

I'd be interested in seeing how this algorithm does in a bear market (as we may be entering one).

Does anybody on this thread have an account with alpaca? I’m on the waiting list.

@Peter thanks for the comment! You can get a basic fundamental data through Polygon API Also if you look at pipline-live tutorial, you can see IEX fundamental is also useful to some extent.

@Hitoshi, what broker & portfolio balance did you start with for the live trading run? Also, do you know of any brokers that could integrate with the algo that doesn’t have a minimum balance?

I meant to say brokers that don’t require a minimum balance. For example interactive brokers, they require a minimum balance of 10k, which is out of my reach.

I am running it with Alpaca, which does not have minimum balance.

Hi hitoshi, I'm just a beginner here, My apologies if this question is really stupid...
so I saw your code
" context.MaxCandidates = 100
context.MaxBuyOrdersAtOnce = 30
context.MyLeastPrice = 3.00
context.MyMostPrice = 25.00
context.MyFireSalePrice = context.MyLeastPrice
context.MyFireSaleAge = 6''

but i did not find any instruction on API, are these from the basic python functions?

Great work and thank you for sharing! What code would be needed to trade on Robinhood?

Guys this algo is not going to work, I ran something similar a while back. You're about to see why real trading != simulated trading.

@Trade Goat can you be more specific.
Also isn't Hitoshi running this on Alpaca right now? How is it performing there?

@trade goat, he’s already seeing great results in live.

@hunt cain, do you code bro?

@hitoshi, how’d you get an open account with alpacca? I’ve been on their waiting list for a while now.

@Bob, @Josh, The ability to get filled in these low volume stocks is very hard to simulate and will not match up with quantopian's results at all. I traded a very similar strat for about a month or two with a similar universe (6+ sharpe in backtests) and ended up with a wash.

Joshua, Not really..... I mostly copy and paste aspects that I want or like and make them fit as best as possible. I am hoping to go back to previous post about RH implementation and see if I can get it to work.

@hunt cain, if your interested in using Algos then I would say that your best investment would be in learning some programming fundamentals first, learning some python would be very beneficial to your objective, if it is to delploy algos in a live trading environment. Anyone can learn to code, if you need resources just let me know & I'll gladly point you in the right direction.

I got an email saying alpaca markets is live. However I don't find the company in the sec edgar. Is this firmed registered? I normally do this check before I put in my social security in,

Alpaca Securities is a registered broker dealer under SEC/FINRA

Hi Hitoshi, I'm having trouble running the pylivetrader command from my terminal. I should mention that I had to install with pip3 instead of pip - could that be the issue? Maybe if you just told me the path to add that would solve it?

pylivetrader currently requires python 3, and depending on your environment, you may need to use pip3 not pip. Python environment setup is different from one to another, and I cannot tell exact answer without knowing it. If on windows, there is a tutorial and also there is docker setup sample

i did install with pip3 and i'm running python3. however (as a note) the instruction at says to run $ pip install pylivetrader, maybe they need to update that instruction. Of course that didn't work and I ran as $ pip3 install pylivetrader, successfully.... But now I can't run: $ pylivetrader run
-bash: pylivetrader: command not found

In some environments including mine, pip is fine. I know there is other environments where you need to say pip3. It's python's problem with this confusing command line names and almost nothing has to do with pylivetrader, but we may be able to add the note in the doc. Thanks for suggestion.. That said, I am not sure why you cannot find pylivetrader command. I can find it after installing using pip3 in my other environment.

$ docker run -it --rm python bash
[email protected]:/# pylivetrader  
bash: pylivetrader: command not found  
[email protected]:/# pip3 install pylivetrader  
[email protected]:/# pylivetrader  
Usage: pylivetrader [OPTIONS] COMMAND [ARGS]...

  --help  Show this message and exit.


ok HItoshi thanks for your help. I'll try again soon. Maybe if I understood how to deploy docker I would just do that but I'm not familiar with containers.

I was wondering if anyone could help me....? I am trying to limit my stock selection the members of the Russel 2000. I've reviewed numerous ways but cannot seem to get it integrated. Thank you.