def ticker_to_eq(ticker): ohlc = pybacktest.load_from_yahoo(ticker, '2008') normalize(ohlc) orig_eq(ohlc) cci(ohlc) #trade_cci(ohlc) #sig_to_eq(ohlc) return ohlc
def handle(self, *args, **options): #models.Run.objects.all().delete() for stock in models.Stock.objects.all(): ohlc = pb.load_from_yahoo(stock.symbol + '.ns', adjust_close=True, start='2005') for name, strategy in models.strategies.items(): params = {} for param, value in strategy['default_params'].items(): params[param] = (math.floor(0.75*value), math.ceil(1.25*value), 1) optimizer = pb.Optimizer(strategy['strategy'], ohlc, params, metrics=['profit', 'pf', 'average', 'average_gain', 'average_loss', 'winrate', 'payoff', 'pf', 'maxdd', 'rf', 'trades'], processes=1) for run in optimizer.results.to_dict('records'): models.Run.objects.create( stock = stock, strategy = name, profit = run.pop('profit'), profit_factor = run.pop('pf'), average = run.pop('average'), average_gain = run.pop('average_gain'), average_loss = run.pop('average_loss'), winrate = run.pop('winrate'), payoff = run.pop('payoff'), max_drawdown = run.pop('maxdd'), risk_factor = run.pop('rf'), trades = run.pop('trades'), params = run, default = run == strategy['default_params'])
#headers========================== import pandas as pd import pybacktest as pt import macd import ema import rsi import json import matplotlib.pyplot as plt # script = 'WOCKPHARMA.NS' # script = 'SIEMENS.NS' script = '^nsei' # stg = "MACD" # stg = "RSI" stg = "_MACD_EMA_" ohlc = pt.load_from_yahoo(script, adjust_close=True) #================================= #strategy========================= def macd_sma_combination(price, macd_small, macd_long, signal, sma_period): value_macd = macd.macd(price, macd_small, macd_long) value_signal = pd.rolling_mean(value_macd, signal) value_sma = pd.rolling_mean(price, sma_period) buy = cover = (value_macd > value_signal) & ( value_macd.shift() < value_signal.shift()) & (price > value_sma) sell = short = (value_macd < value_signal) & ( value_macd.shift() > value_signal.shift()) & (price < value_sma) del cover del short return value_macd, value_signal, value_sma, buy, sell
import sys import pandas import pybacktest #script = sys.argv[1] script = 'siemens.ns' ohlc = pybacktest.load_from_yahoo(script, adjust_close=True) lips_sma_period = 5 teeth_sma_period = 8 jaw_sma_period = 13 hl_diff = (ohlc.H+ ohlc.L)/ 2 ml1 = pandas.rolling_mean(hl_diff, lips_sma_period) mt1 = pandas.rolling_mean(hl_diff, teeth_sma_period) mj1 = pandas.rolling_mean(hl_diff, jaw_sma_period) ml = ml1.shift(2) mt = mt1.shift(4) mj = mj1.shift(7) buy = cover = (ml > mt) & (mt > mj) & ((ml.shift() < mt.shift()) | (mt.shift() < mj.shift())) sell = short = (ml < mt) & (mt < mj) & ((ml.shift() > mt.shift()) | (mt.shift() > mj.shift())) del cover del short bt = pybacktest.Backtest(locals(), 'alligator') # df = pandas.DataFrame()
import pybacktest import pandas as pd ohlc = pybacktest.load_from_yahoo('SPY') ohlc.tail() short_ma = 50 long_ma = 200 ms = pd.rolling_mean(ohlc.C, short_ma) ml = pd.rolling_mean(ohlc.C, long_ma) buy = cover = (ms > ml) & (ms.shift() < ml.shift()) # ma cross up sell = short = (ms < ml) & (ms.shift() > ml.shift()) # ma cross down bt = pybacktest.Backtest(locals(), 'ma_cross') import pylab bt.plot_trades() pd.rolling_mean(ohlc.C, short_ma).plot(c='green') pd.rolling_mean(ohlc.C, long_ma).plot(c='blue') pylab.legend(loc='upper left') pylab.show()
def datas(symbols): return {symbol: pt.load_from_yahoo(symbol + '.ns') for symbol in symbols}
import pandas as pd import datetime as dt import time import pybacktest as pt nifty_data = pt.load_from_yahoo('^nsei', start='2014', adjust_close=True) nifty_all = pd.read_csv('/home/sigmasoft6/Desktop/indicator/nifty_all.csv') data = dict(zip(nifty_all['Symbol'], nifty_all['Company'])) def datas(symbols): return {symbol: pt.load_from_yahoo(symbol + '.ns') for symbol in symbols} def strategy_sma(script, period_small=5, period_long=10): ms = pd.rolling_mean(script.C, period_small) ml = pd.rolling_mean(script.C, period_long) buy = (ms > ml) & (ms.shift() < ml.shift()) sell = (ms < ml) & (ms.shift() > ml.shift()) return buy, sell def stgy2(script, period_small=50, period_long=100): ms = pd.rolling_mean(script.C, period_small) ml = pd.rolling_mean(script.C, period_long) buy = (ms > ml) & (ms.shift() < ml.shift()) sell = (ms < ml) & (ms.shift() > ml.shift()) return buy, sell def trades(stock_stgy, nifty):
from numpy import inf from scipy.optimize import brute from pybacktest import Backtest, load_from_yahoo from ta import * def cost(params, ohlc=None, fn=None): signals = fn(ohlc, *params) bt = Backtest(signals) try: sharpe = bt.report['risk/return profile']['sharpe'] cost = 1.0 / sharpe print params, sharpe, cost return cost except Exception, e: cost = inf print params, None, cost return cost if __name__ == "__main__": ohlc = load_from_yahoo('AAPL', start='2000') # TODO: multiprocessing? fn, params = mav_cross_double, [slice(5, 35, 5), slice(20, 110, 10)] res = brute(cost, params, args=(ohlc, fn), finish=None) print 'Solution (fast period, slow period): %s\n' % res print Backtest(fn(ohlc, *res)).summary()