Being the question tagged as python
and given I look for small challenges for my platform, backtrader
, I took the chance to see how easy would be to do this with the platform.
Documented at: http://www.backtrader.com/posts/2016-08-15-stock-screening/stock-screening/
The core code in this case is an analyzer which looks for assets which are above the 10-days moving average (example from the OP). The analyzer code:
class Screener_SMA(bt.Analyzer):
params = dict(period=10)
def start(self):
self.smas = {data: bt.indicators.SMA(data, period=self.p.period)
for data in self.datas}
def stop(self):
self.rets['over'] = list()
self.rets['under'] = list()
for data, sma in self.smas.items():
node = data._name, data.close[0], sma[0]
if data > sma: # if data.close[0] > sma[0]
self.rets['over'].append(node)
else:
self.rets['under'].append(node)
It can be used directly with the built-in executable btrun
(created by setup.py
/ pip
) or managed with a hand-crafted script. A sample execution with btrun
:
btrun --format yahoo --data YHOO --data IBM --data NVDA --data TSLA --data ORCL --data AAPL --fromdate 2016-07-15 --todate 2016-08-13 --analyzer st-screener:Screener_SMA --cerebro runonce=0 --writer --nostdstats
Yes: the prices are being directly downloaded from Yahoo with --format yahoo
.
Which earlier today (before the market closed again today) delivered:
- Analysis:
- over: ('ORCL', 41.09, 41.032), ('IBM', 161.95, 161.221), ('YHOO', 42.94, 39.629000000000005), ('AAPL', 108.18, 106.926), ('NVDA', 63.04, 58.327)
- under: ('TSLA', 224.91, 228.423)
I am sure that the same can be done with other python platforms like pyAlgoTrade
, zipline
, etc. A list of known (to me) python open source platforms can be found in the README of backtrader
on the front page of the repository: https://github.com/mementum/backtrader
Disclaimer: if not obvious, I am the author of backtrader