def get_data_f(dontchange): s_data = bt.get('spy,efa,iwm,vwo,ibb,agg,hyg,gld,slv,tsla,aapl,msft,qqq', start='2017-01-01') cry_data = bt.get('btc-usd,eth-usd', start='2017-01-01') data_cache = cry_data.join(s_data, how='outer') data_cache = data_cache.dropna() return data_cache
def abovema_trainandtest(tickers, sma=50, start_train='06-01-2015', end_train='05-31-2017', start_test='06-01-2017', end_test='05-31-2019', name1='above_sma50_train', name2='above_sma50_test'): #training test data_train = bt.get(tickers, start=start_train, end=end_train) sma_train = data_train.rolling(sma).mean() signal = data_train > sma_train s = bt.Strategy(name1, [ bt.algos.SelectWhere(signal), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) #testing set data_test = bt.get(tickers, start=start_test, end=end_test) sma_test = data_test.rolling(sma).mean() signal2 = data_test > sma_test s2 = bt.Strategy(name2, [ bt.algos.SelectWhere(signal2), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) return (bt.Backtest(s, data_train), bt.Backtest(s2, data_test))
def Calc_Beta(Ticker): #one year ago OneYearAgo = datetime.datetime.now() - datetime.timedelta(days=365) #Get data from the market df = bt.get(Ticker, start=OneYearAgo).pct_change() df = df.dropna() mkt = bt.get('^GSPC', start=OneYearAgo).pct_change() mkt = mkt.dropna() df['gspc'] = mkt.gspc df = df.dropna() np_array = df.values m = np_array[:, 0] # market returns are column zero from numpy array s = np_array[:, 1] # stock returns are column one from numpy array covariance = np.cov(s, m) # Calculate covariance between stock and market Beta = covariance[0, 1] / covariance[1, 1] return Beta
def buy_and_hold(ticker: str, start: Union[str, datetime], name: str): """ Generates a backtest object for the given ticker Parameters ---------- ticker: str Stock to test start: Union[str, datetime] Backtest start date. Can be either string or datetime name: Name of the backtest (for labeling purposes) Returns ------- bt.Backtest object for buy and hold strategy """ prices = bt.get(ticker, start=start) bt_strategy = bt.Strategy( name, [ bt.algos.RunOnce(), bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance(), ], ) return bt.Backtest(bt_strategy, prices)
def main(): days = 5 change = .02 with open('ticker_sectors.data', 'rb') as f: tickerSectors = pickle.load(f) companies = tickerSectors[0] companyList = 'aos' for i in range(1, 10): companyList = companyList + ',' + companies[i].lower() print(companyList) data = bt.get(companyList, start='2014-01-01') print(data) weights = getPredictions(days, change) print(weights) s = bt.Strategy('s1', [ bt.algos.RunWeekly(), bt.algos.SelectAll(), bt.algos.WeighTarget(weights), bt.algos.Rebalance() ]) test = bt.Backtest(s, data) res = bt.run(test) res.plot() res.display() print("GOOD")
def MktReturn(): #one year ago OneYearAgo = datetime.datetime.now() - datetime.timedelta(days=365) #Get data from the market mktdata = bt.get('^GSPC', start=OneYearAgo) #Calculate Return of the market start = mktdata.gspc[0] end = mktdata.gspc[-1] Return = end / start - 1 return Return
def buy_and_hold(ticker, name, start='2020-2-1', end='2020-11-1'): # Get the data price_data = bt.get(ticker, start=start, end=end) # Define the benchmark strategy bt_strategy = bt.Strategy(name, [ bt.algos.RunOnce(), bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) # Return the backtest return bt.Backtest(bt_strategy, price_data)
def signal_strategy(ticker, period, name, start='2020-2-1', end='2020-11-1'): # Get the data and calculate SMA price_data = bt.get(ticker, start=start, end=end) sma = price_data.rolling(period).mean() # Define the signal-based trategy bt_strategy = bt.Strategy(name, [ bt.algos.SelectWhere(price_data > sma), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) # Return the backtest return bt.Backtest(bt_strategy, price_data)
def RiskFree(): from datetime import timedelta adate = datetime.datetime.now() adate -= timedelta(days=1) while adate.weekday() > 4: # Mon-Fri are 0-4 adate -= timedelta(days=1) rfrdf = bt.get('^IRX', start=adate) / 100 rfr = rfrdf.iloc[-1, -1] return rfr
def run(self): data = bt.get(self.underlyings,start=self.startDate) self.data = data # Run Signals self.generateSignals(data) self.generateStrategies() test = [] res = [] #Generate Strategies for s in self.strat: test=bt.Backtest(s,data[data.index < self.endDate]) res.append(bt.run(test)) return res
def long_only_ew(tickers=None, start='2010-01-01', name='long_only_ew', data=None): s = bt.Strategy(name, [ bt.algos.RunOnce(), bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) if tickers: data = bt.get(tickers, start=start) return bt.Backtest(s, data)
def abovema(tickers, sma_days=50, start='06-01-2015', end='05-31-2017', name='abovesma50train'): data = bt.get(tickers, start=start, end=end) sma = data.rolling(sma_days).mean() signal = data > sma s = bt.Strategy(name, [ bt.algos.SelectWhere(signal), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) return bt.Backtest(s, data)
def __init__(self, symbol, start_date, balance_sheet_items=DEFAULT_BALANCE_SHEET_ITEMS, data_path='ScraXBRL/data/extracted_data/{0}/'): self.symbol = symbol self.balance_sheet_items = balance_sheet_items self.last_balance_sheet_date = start_date # Start date in format YYYY-MM-DD self.date_format = '%Y-%m-%d' self.data_path = data_path self.stock_data = bt.get( '{0}:Open,{0}:High,{0}:Low,{0}:Close'.format(symbol), start=start_date) self.balance_sheet_data = self.get_balance_sheet_data( self.last_balance_sheet_date)
def sma_cross(ticker, start = "2010-01-01", short_ma = 50, long_ma = 200, name = "ma_cross"): data = bt.get(ticker, start = start) short_sma = data.rolling(short_ma).mean() long_sma = data.rolling(long_ma).mean() tw = long_sma.copy() tw[short_sma > long_sma] = 1.0 tw[short_sma <= long_sma] = -1.0 tw[long_sma.isnull()] = 0.0 s = bt.Strategy(name, [WeighTarget(tw), bt.algos.Rebalance() ], [ticker]) return bt.Backtest(s, data)
def above_sd(tickers, period=50, start='2010-01-01', name='above_sma'): """ Long securities that are above their n period sd with equal weights. """ # download data data = bt.get(tickers, start=start) # calc sma sma = data.rolling(period).sd() # create strategy s = bt.Strategy(name, [ SelectWhere(data > sma), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) # now we create the backtest return bt.Backtest(s, data)
def btexample(): # fetch some data data = bt.get('spy,agg', start='2010-01-01') print data.head() # create the strategy s = bt.Strategy('s1', [bt.algos.RunMonthly(), bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance()]) # create a backtest and run it test = bt.Backtest(s, data) res = bt.run(test) res.display() res.to_csv(sep=',', path='./bar.csv') # first let's see an equity curve plot = res.plot(figsize=(15,5)) fig = plot.get_figure() fig.savefig("foo.png")
def aggressive(ticker, start, end): data = bt.get(ticker, start=start, end=end) print data.head() data = data.asfreq(freq='M', method='pad') # plots = data.plot(subplots=True, figsize=(10, 4)) # plt.show() EntryAlgorithm = data.ewm(span=6).mean() ExitAlgorithm = data.ewm(span=12).mean() tw = EntryAlgorithm.copy() tw[EntryAlgorithm > ExitAlgorithm] = 1.0 tw[EntryAlgorithm <= ExitAlgorithm] = 0.0 s = bt.Strategy('Perissos All-Weather', [ bt.algos.RunMonthly(), bt.algos.SelectAll(), bt.algos.WeighTarget(tw), bt.algos.Rebalance() ]) return bt.Backtest(s, data)
def bench(ticker, start, end, weights): data = bt.get(ticker, start=start, end=end) print data.head() data = data.asfreq(freq='M', method='pad') # plots = data.plot(subplots=True, figsize=(10, 4)) # plt.show() weights = weights print weights EntryAlgorithm = data.ewm(span=6).mean() ExitAlgorithm = data.ewm(span=12).mean() tw = EntryAlgorithm.copy() tw[EntryAlgorithm > ExitAlgorithm] = 1.0 tw[EntryAlgorithm <= ExitAlgorithm] = 0.0 s2 = bt.Strategy( 'Bench', [bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance()]) return bt.Backtest(s2, data)
def above_sma(tickers=None, sma_per=50, start='2010-01-01', name='above_sma', data=None): """ Long securities that are above their n period Simple Moving Averages with equal weights. """ # download data if tickers: data = bt.get(tickers, start=start) # calc sma sma = data.rolling(sma_per).mean() # create strategy s = bt.Strategy(name, [ SelectWhere(data > sma), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) # now we create the backtest return bt.Backtest(s, data)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Dec 13 14:59:25 2017 @author: cortinamatthieu """ import bt ##récupération du SP500 pour comparer nos stratégies au marché## data_spy = bt.get('spy', start='2012-03-01', end='2014-01-01') s_spy = bt.Strategy('S&P 500 only', [ bt.algos.RunMonthly(), bt.algos.SelectThese(['spy']), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) b_spy = bt.Backtest(s_spy, data_spy) result = bt.run(b_spy) result.plot() ############################################################### ############################################################### ####on récup le taux sans risque### riskfree = bt.get('IEF', start='2012-03-01', end='2014-01-01') riskfree_rate = float(riskfree.calc_cagr()) import quandl ####on importe les données####
# -*- coding: utf-8 -*- """ Created on Thu Jun 14 00:59:43 2019 @author: MichaelRolleigh """ # This script enacts the crossover strategy in bt import bt # download data #data = bt.get('vaw, vis, vcr, vdc, vht, vfh, vgt, vox, vpu, vnq, vde', start='2010-01-01') data = bt.get('gsg', start='2010-01-01') # calculate moving average DataFrame using pandas' rolling_mean import pandas as pd import matplotlib.pyplot as plt # define the length of the short and long averages short_s1 = 50 long_s1 = 200 short_s2 = 32 long_s2 = 248 # a rolling mean is a moving average, right? sma_short_s1 = data.rolling(short_s1).mean() sma_long_s1 = data.rolling(long_s1).mean() sma_short_s2 = data.rolling(short_s2).mean() sma_long_s2 = data.rolling(long_s2).mean() # and compute sma_50 for replicating earlier strat sma_50 = data.rolling(50).mean() sma_200 = data.rolling(200).mean()
import bt import matplotlib.pyplot as plt data = bt.get('spy,agg', start='2010-01-01') s = bt.Strategy('s1', [ bt.algos.RunMonthly(), bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) test = bt.Backtest(s, data) res = bt.run(test) res.plot() plt.show()
import os import sys import logging import math import pandas as pd import pytz import bt import matplotlib.pyplot as plt from strategy.rsi_25_75_talib import create_strategy from strategy.sma import above_sma, long_only_ew from strategy.r3 import create_strategy as r3_create_strategy #tickers = 'aapl,msft,c,gs,ge,tsla,fb' tickers = 'AVGO' start_date = '2017-01-01' data = bt.get(tickers, start=start_date) sma = data.rolling(720).mean() print(sma.tail(5))
def __call__(self, target): # get signal on target.now if target.now in self.signal.index: sig = self.signal.ix[target.now] # get indices where true as list selected = list(sig.index[sig]) # save in temp - this will be used by the weighing algo target.temp['selected'] = selected # return True because we want to keep on moving down the stack return True data = bt.get('aapl,msft,c,gs,ge', start='2010-01-01') # calculate moving average DataFrame using pandas' rolling_mean import pandas as pd # a rolling mean is a moving average, right? sma = pd.rolling_mean(data, 50) # let's see what the data looks like - this is by no means a pretty chart, but it does the job tmp = bt.merge(data, sma).asfreq('m', 'ffill').rebase() plot = tmp.plot(figsize=(15, 5)) signal = data > sma # first we create the Strategy s = bt.Strategy('above50sma', [SelectWhere(data > sma), bt.algos.WeighEqually(),
col2_graph = col2.beta_container() col1_second = col1.beta_container() col2_second = col2.beta_container() #Sidebar Inputs stock_choice_1 = col1_s.selectbox( "Ticker 1", ('spy', 'efa', 'iwm', 'vwo', 'ibb', 'agg', 'hyg', 'gld', 'slv', 'tsla', 'aapl', 'msft', 'qqq', 'btc-usd', 'eth-usd')) #get ticker percent_1 = col2_s.text_input( "% Allocation", value=55, max_chars=3, ) # get percent stock_choice_1 = stock_choice_1.lower() #bt likes lower case data_1 = bt.get(stock_choice_1, start=start_date) # get the data stock_choice_2 = col1_s.selectbox( "Ticker 2", ('agg', 'spy', 'efa', 'iwm', 'vwo', 'ibb', 'hyg', 'gld', 'slv', 'tsla', 'aapl', 'msft', 'qqq', 'btc-usd', 'eth-usd')) percent_2 = col2_s.text_input("% Allocation", value=40, max_chars=3) stock_choice_2 = stock_choice_2.lower() data_2 = bt.get(stock_choice_2, start=start_date) stock_choice_3 = col1_s.selectbox( "Ticker 3", ('btc-usd', 'spy', 'efa', 'iwm', 'vwo', 'ibb', 'agg', 'hyg', 'gld', 'slv', 'tsla', 'aapl', 'msft', 'qqq', 'eth-usd')) percent_3 = col2_s.text_input("% Allocation", value=5, max_chars=3) stock_choice_3 = stock_choice_3.lower()
import bt data = bt.get('RUB=X', start='2016-01-01', end='2016-08-01') print(data.head())
# Prints results as supplementary if within x percent of the top result within_percentage = 4 # END USER SETTINGS file = "" data = "" # Open file with data, if it doesn't exist pull new data and save it to a file try: file = open(filename, 'r') data = pickle.load(file) except IOError: # generate the file file = open(filename, 'w+') data = bt.get(full_set, start=start_date) pickle.dump(data, file) file.close() ### Finds optimal SMA cross settings and return percentage # [best_low, best_high, best_percentage] = sma_cross_optimal_values(data, sma_low_bot, sma_low_top, sma_high_bot, sma_high_top, within_percentage) ### Get SMA based on the data # sma_low_plot = pd.rolling_mean(data, best_low) # sma_high_plot = pd.rolling_mean(data, best_high) # # plot = bt.merge(data, sma_low_plot, sma_high_plot).plot() ############################ ### Finds optimal SMA value for price crossing the SMA line # [best_sma, best_percentage] = above_sma_optimal_value(data, 5, sma_high_top, within_percentage)
import bt # Download historical prices bt_data = bt.get('fb, amzn, goog, nflx, aapl', start='2020-12-15', end='2020-12-31') # Print the top five rows print(bt_data.head(10))
import bt import matplotlib.pyplot as plt import pandas as pd data = bt.get('^NSEI', start='2016-01-01') #print data #sma = pd.rolling_mean(data,34) df = pd.DataFrame(data) #print df sma = df.rolling(window=34,center=False).mean() #print sma strategy = bt.Strategy('Price-MA Cross', [bt.algos.SelectWhere(data>sma), bt.algos.WeighEqually(), bt.algos.Rebalance() ]) test = bt.Backtest(strategy, data) result = bt.run(test) print result result.plot(), result.display() plt.show()
import bt import ffn # fetch some data data = bt.get('spy,agg', start='2010-01-01') print data.head() s = bt.Strategy('s1', [bt.algos.RunMonthly(), bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance()]) # create a backtest and run it test = bt.Backtest(s, data) res = bt.run(test) res.plot() res.display() res.plot_weights() #print test.security_weights.tail(20) #print test.weights.tail(20) #print test.positions.tail(20) prices = ffn.get('aapl,msft', start='2010-01-01')
import bt import matplotlib matplotlib.get_backend() # download data from bt.algos import SelectWhere data = bt.get('aapl,msft', start='2016-01-01') # calculate moving average DataFrame using pandas' rolling_mean import pandas as pd # a rolling mean is a moving average, right? sma = pd.rolling_mean(data, 50) bt.merge(data, sma).plot(figsize=(15, 5)) signal = data > sma # first we create the Strategy s = bt.Strategy('above50sma', [SelectWhere(data > sma), bt.algos.WeighEqually(), bt.algos.Rebalance()]) # now we create the Backtest t = bt.Backtest(s, data) # and let's run it! res = bt.run(t) res.plot('d') print(type(res)) res.display()
""" #GENERAL INPUTS FOR FOLLOWING CODE """ tickers = ticker_list["Ticker"].to_list() start_date = dt(2010,1,1) end_date = dt(2020, 2, 17) RFR = 0.021 #annual TBOND (10y or 30y?) yield bc we look for long term """ #OPTIMIZE FOR MAX SHARPE RATIO BY SOURCING TICKERS FROM DCF OUTPUT """ table = bt.get(tickers, start = start_date, end = end_date) # calculate daily and annual returns of the stocks returns_daily = table.pct_change() returns_daily = returns_daily.dropna() returns_annual = returns_daily.mean() * 252 # get daily and covariance of returns of the stock cov_daily = returns_daily.cov() cov_annual = cov_daily * 252 # empty lists to store returns, volatility and weights of imiginary portfolios port_returns = [] port_volatility = [] sharpe_ratio = [] stock_weights = []
__author__ = 'tyler' import bt #%pylab inline # download data data = bt.get('aapl,msft', start='2013-01-01') data.head() import pandas as pd # a rolling mean is a moving average, right? sma = pd.rolling_mean(data, 50) s = bt.Strategy('above50sma', [ bt.algos.SelectWhere(data > sma), bt.algos.WeighEqually(), bt.algos.Rebalance()]) # now we create the Backtest t = bt.Backtest(s, data) # and let's run it! res = bt.run(t)
# these compile and display the plot so that it is formatted as expected plt.tight_layout() plt.show() ######################################################## # Import the bt package so we can use the backtesting functions import bt #define the beginning date, so I can loop over different time periods beginning = [datetime(2015, 1, 1), datetime(2017, 1, 1), datetime(2019, 1, 1)] #instantiate the offset, over which time period the backtesting should go, here two years offset = timedelta(weeks=104) for b in beginning: # Import data data_bt = bt.get(tickers_list, start=b, end=b + offset) # We will need the risk-free rate to get correct Sharpe Ratios riskfree = bt.get('^IRX', start=b, end=b + offset) # Take the average of the risk free rate over entire time period riskfree_rate = float(riskfree.mean()) / 100 # Print out the risk free rate to make sure it looks good print('risk-free rate:', riskfree_rate) #instantiate a conditional statement to select the strategy based on the given risk tolerance of the investor if risk_tolerance == 'Low': # if the investors has a low risk tolerance, we use a Inverse Volatiliy Strategy s_mark = bt.Strategy('Portfolio', [ bt.algos.RunMonthly(), bt.algos.SelectAll(), bt.algos.WeighInvVol(),