def test_capture(self): res_a = empyrical.capture(ret['a'], benchmark_rets['a']) res_b = empyrical.capture(ret['b'], benchmark_rets['b']) res_c = empyrical.capture(ret['c'], benchmark_rets['c']) assert isclose(ret['a'].vbt.returns.capture(benchmark_rets['a']), res_a) pd.testing.assert_series_equal( ret.vbt.returns.capture(benchmark_rets), pd.Series([res_a, res_b, res_c], index=ret.columns))
def test_capture(self): res_a = empyrical.capture(ret['a'], benchmark_rets['a']) res_b = empyrical.capture(ret['b'], benchmark_rets['b']) res_c = empyrical.capture(ret['c'], benchmark_rets['c']) assert isclose(ret['a'].vbt.returns.capture(benchmark_rets['a']), res_a) pd.testing.assert_series_equal( ret.vbt.returns.capture(benchmark_rets), pd.Series([res_a, res_b, res_c], index=ret.columns).rename('capture')) pd.testing.assert_series_equal( ret.vbt.returns.rolling_capture(ret.shape[0], benchmark_rets, minp=1).iloc[-1], pd.Series([res_a, res_b, res_c], index=ret.columns).rename(ret.index[-1]))
def runstrategy(ticker_list,bench_ticker): args = parse_args() print(args) # Create a cerebro cerebro = bt.Cerebro() # Get the dates from the args fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d') todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d') # bench = bt.feeds.YahooFinanceData( # dataname=bench_ticker, # fromdate=fromdate, # todate=todate, # buffered=True,plot = False # ) bench = bt.feeds.GenericCSVData( dataname='/Users/joan/PycharmProjects/CSV_DB/IB/' + bench_ticker + '.csv', fromdate=fromdate, todate=todate, nullvalue=0.0, dtformat=('%Y%m%d'), datetime=1, open=2, high=3, low=4, close=5, volume=6, reverse=False, plot=False) cerebro.adddata(bench, name=bench_ticker) for i in ticker_list: print('Loading data: '+ i) # data = bt.feeds.YahooFinanceData( # dataname=i, # fromdate=fromdate, # todate=todate, # adjclose=True, # buffered=True, plot = False # ) data = bt.feeds.GenericCSVData( dataname='/Users/joan/PycharmProjects/CSV_DB/IB/'+i+'.csv', fromdate=fromdate, todate=todate, nullvalue=0.0, dtformat=('%Y%m%d'), datetime=1, open=2, high=3, low=4, close=5, volume=6, reverse=False, plot= False) cerebro.adddata(data,name = i) # Add the strategy cerebro.addstrategy(PairTradingStrategy, period=args.period, stake=args.stake) # Add the commission - only stocks like a for each operation cerebro.broker.setcash(args.cash) # Add the commission - only stocks like a for each operation # cerebro.broker.setcommission(commission=args.commperc) comminfo = FixedCommisionScheme() cerebro.broker.addcommissioninfo(comminfo) cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe_ratio') cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta") cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn") cerebro.addanalyzer(bt.analyzers.SharpeRatio_A, _name='myysharpe', riskfreerate=args.rf_rate) cerebro.addanalyzer(bt.analyzers.PyFolio, _name='mypyf') cerebro.addanalyzer(bt.analyzers.TimeReturn, timeframe=bt.TimeFrame.Days, data=bench, _name='benchreturns') cerebro.addobserver(bt.observers.Value) cerebro.addobserver(bt.observers.Benchmark,plot = False) cerebro.addobserver(bt.observers.DrawDown) # And run it strat = cerebro.run(runonce=not args.runnext, preload=not args.nopreload, oldsync=args.oldsync ) # Plot if requested if args.plot: cerebro.plot(style='candlestick', barup='green', bardown='red',figsize=(100,100)) bench_returns = strat[0].analyzers.benchreturns.get_analysis() bench_df = pd.DataFrame.from_dict(bench_returns, orient='index', columns=['return']) return_df = pd.DataFrame.from_dict(strat[0].analyzers.mypyf.get_analysis()['returns'], orient='index', columns=['return']) # print('Sharpe Ratio(bt):', firstStrat.analyzers.myysharpe.get_analysis()['sharperatio']) # print('Sharpe Ratio:', empyrical.sharpe_ratio(return_df, risk_free=args.rf_rate / 252, period='daily')[0]) # print('Sharpe Ratio Benchmark:', empyrical.sharpe_ratio(bench_df, risk_free=args.rf_rate / 252, period='daily')[0]) # print('') # # print('Sortino Ratio:', empyrical.sortino_ratio(return_df, period='daily')[0]) # print('Sortino Ratio Benchmark:', empyrical.sortino_ratio(bench_df, period='daily')[0]) # print('') # print('VaR:', empyrical.value_at_risk(return_df) * 100, '%') # print('VaR Benchmark:', empyrical.value_at_risk(bench_df) * 100, '%') # # print('') # # print('Capture:', round(empyrical.capture(return_df, bench_df, period='daily')[0] * 100), '%') # print('') # # print('Max drawdown: ', round(empyrical.max_drawdown(return_df)[0] * 100), '%') # print('Max drawdown Benchmark: ', round(empyrical.max_drawdown(bench_df)[0] * 100), '%') # # print('') alpha, beta = empyrical.alpha_beta(return_df, bench_df, risk_free=args.rf_rate) # print('Beta: ', beta) # print('') # print('Annual return:', round(empyrical.annual_return(return_df)[0] * 100), '%') # print('Annual Vol:', round(empyrical.annual_volatility(return_df)[0] * 100), '%') # print('') # print('Annual return Benchmark:', round(empyrical.annual_return(bench_df)[0] * 100), '%') # print('Annual Vol Benchmark:', round(empyrical.annual_volatility(bench_df)[0] * 100), '%') # print('') dic = {'SQN': printSQN(strat[0].analyzers.sqn.get_analysis()), 'sharpe': empyrical.sharpe_ratio(return_df, risk_free=args.rf_rate / 252, period='daily')[0], 'sharpe_bm': empyrical.sharpe_ratio(bench_df, risk_free=args.rf_rate / 252, period='daily')[0], 'sortino': empyrical.sortino_ratio(bench_df, period='daily')[0], 'sortino_bm': empyrical.sortino_ratio(bench_df, period='daily')[0], 'VaR': empyrical.value_at_risk(return_df) * 100, 'VaR_bm': empyrical.value_at_risk(bench_df) * 100, 'capture': round(empyrical.capture(return_df, bench_df, period='daily')[0] * 100), 'max_dd': round(empyrical.max_drawdown(return_df)[0] * 100), 'max_dd_bm':round(empyrical.max_drawdown(bench_df)[0] * 100), 'beta': beta, 'return_annual':round(empyrical.annual_return(return_df)[0] * 100,2), 'return_annual_bm':round(empyrical.annual_volatility(return_df)[0] * 100,2), 'vol_annual':round(empyrical.annual_return(bench_df)[0] * 100,2), 'vol_annual_bm':round(empyrical.annual_volatility(bench_df)[0] * 100,2)} df = pd.DataFrame(dic,index = [0]) print(df) def calc_stats(df): df['perc_ret'] = (1 + df['return']).cumprod() - 1 # print(df.tail()) return df s = return_df.rolling(30).std() b = bench_df.rolling(30).std() # Get final portfolio Value portvalue = cerebro.broker.getvalue() # Print out the final result print('Final Portfolio Value: ${}'.format(round(portvalue)), 'PnL: ${}'.format(round(portvalue - args.cash)), 'PnL: {}%'.format(((portvalue / args.cash) - 1) * 100)) # Finally plot the end results if args.plot: fig, axs = plt.subplots(2, sharex=True) fig.autofmt_xdate() axs[1].plot(s) axs[1].plot(b) axs[1].set_title('Drawdown') axs[1].legend(['Fund', 'Benchmark']) axs[0].set_title('Returns') axs[0].plot(calc_stats(return_df)['perc_ret']) axs[0].plot(calc_stats(bench_df)['perc_ret']) axs[0].legend(['Fund', 'Benchmark']) plt.show()
empyrical.sharpe_ratio(return_df, risk_free=rf / 252, period='daily')[0]) print('Sharpe Ratio Benchmark:', empyrical.sharpe_ratio(bench_df, risk_free=rf / 252, period='daily')[0]) print('') print('Sortino Ratio:', empyrical.sortino_ratio(return_df, period='daily')[0]) print('Sortino Ratio Benchmark:', empyrical.sortino_ratio(bench_df, period='daily')[0]) print('') print('VaR:', empyrical.value_at_risk(return_df) * 100, '%') print('VaR Benchmark:', empyrical.value_at_risk(bench_df) * 100, '%') print('') print('Capture:', round(empyrical.capture(return_df, bench_df, period='daily')[0] * 100), '%') print('') print('Max drawdown: ', round(empyrical.max_drawdown(return_df)[0] * 100), '%') print('Max drawdown Benchmark: ', round(empyrical.max_drawdown(bench_df)[0] * 100), '%') print('') alpha, beta = empyrical.alpha_beta(return_df, bench_df, risk_free=rf) print('Beta: ', beta) print('') print('Annual return:', round(empyrical.annual_return(return_df)[0] * 100), '%') print('Annual Vol:', round(empyrical.annual_volatility(return_df)[0] * 100), '%')