def env_spy(seed=0): def indicator1(df): close = df[DF_ADJ_CLOSE] windows = [100, 400] outs = {} for window in windows: ts = TrailingStats(close, window) out = ts.exp_growth out[np.isnan(out)] = 0 outs[f'growth({window})'] = out out = ts.exp_reg_diff out[np.isnan(out)] = 0 outs[f'diff({window})'] = out return outs stock_data = YahooData(symbols=['SPY']) indicators = Indicators(stock_data) indicators.create(indicator1) env = EnvBase( stock_data=stock_data, indicators=indicators, price_name=DF_ADJ_CLOSE, seed=seed, commission=0, ) env.reset() return env
def env_noise(seed=0): def indicator1(df): close = df['Close'] windows = [20, 50, 100] outs = {} for window in windows: ts = TrailingStats(close, window) out = ts.exp_growth out[np.isnan(out)] = 0 outs[f'growth({window})'] = out out = ts.exp_reg_diff out[np.isnan(out)] = 0 outs[f'diff({window})'] = out return outs fdata = FakeData(0, include=['Noise(1.0)']) indicators = Indicators(fdata) indicators.create(indicator1, ) env = EnvBase(stock_data=fdata, indicators=indicators, price_name='Close', seed=seed) env.reset() return env
def test_indicator(): y = YahooData(['DIS', 'GOOG']) indicators = Indicators(y) indicators.create(trailing_avg, 5, name='trailing') df1 = indicators.dataframes['DIS'] df2 = indicators.dataframes['GOOG'] assert 'trailing' in df1.columns assert 'trailing' in df2.columns
def env_sin20_growth(): """Test environment for simple, smooth sin wave with trailing growth rate as indicators.""" def indicator1(df): close = df['Close'] windows = [5, 10, 20, 50] outs = {} for window in windows: ts = TrailingStats(close, window) out = ts.exp_growth # Replace NAN with 0 out[np.isnan(out)] = 0 outs[f'{window}'] = out return outs fdata = FakeData(0, include=['Sin(20)']) indicators = Indicators(fdata) indicators.create(indicator1, name='growth') env = EnvBase(stock_data=fdata, indicators=indicators, price_name='Close') env.reset() return env
if np.isnan(out): out = -1 return out def stop_loss(df: pd.DataFrame): series = df[DF_ADJ_CLOSE] ts = TrailingStats(series, window_size=200) loss = ts.max_loss gain = ts.max_gain delta = gain - loss delta = append_nan(delta, ts.window_size) return delta indicator_stoploss = Indicators(yahoo) indicator_stoploss.create(stop_loss) table_stoploss = indicator_stoploss.tables['SPY'] STOCKS = symbols # STOCKS.append('SPY') # STOCKS.append('VOO') # STOCKS.append('GOOG') # STOCKS.append('TSLA') STOCKS = np.array(STOCKS) # rng = np.random.default_rng(1) # rng.shuffle(STOCKS) # STOCKS = STOCKS[0:200] # %% Strategies
STOCKS.append('SPY') STOCKS.append('VOO') # STOCKS.append('GOOG') # STOCKS.append('TSLA') STOCKS = np.array(STOCKS) def post1(df: pd.DataFrame): series = df[DF_ADJ_CLOSE] ts = TrailingStats(series, 252 * 5) stat1 = ts.exp_growth return stat1 yahoo.symbol_names = STOCKS indicator = Indicators(yahoo) indicator.create(post1) df = indicator.extract_column('post1()') table = TableData(df) index_spy = np.where(df.columns == 'SPY')[0][0] # %% class Strat1(Strategy): def init(self): # Build long and short rate metric self.growths = [] # Arbitrarily set initial stock. Doesn't matter. self.current_stocks = []
# STOCKS.append('GOOG') # STOCKS.append('TSLA') STOCKS = ['SPY'] STOCKS = np.array(STOCKS) def post1(df: pd.DataFrame): series = df[DF_ADJ_CLOSE] ts = TrailingStats(series, 100) metric = ts.max_gain - ts.max_loss return metric yahoo.symbols = STOCKS indicator = Indicators(yahoo) indicator.create(post1) df = indicator.get_column_from_all('post1()') # %% table = TableData(df) # %% class Strat1(Strategy): def init(self): # Build long and short rate metric self.growths = []
return d def post2(df:pd.DataFrame): series = df[DF_ADJ_CLOSE] ts = TrailingStats(series, 8) slope, interc, rvalue = ts.linear_regression r2 = rvalue**2 metric = slope * r2 std = cumulative_std(metric) return metric / std yahoo.symbols = STOCKS indicator = Indicators(yahoo) indicator.create(post2, name='p') # df = indicator.get_column_from_all('post1()') df = indicator.get_symbol_all('SPY') table = TableData(df) # %% class Strat1(Strategy): def init(self): # Build long and short rate metric self.growths = []
from backtester.stockdata import YahooData, Indicators from backtester.indicators import TrailingStats from backtester.definitions import DF_ADJ_CLOSE import matplotlib.pyplot as plt def my_return(df): s = df[DF_ADJ_CLOSE] size = 252 ts = TrailingStats(s, window_size=size) return ts.return_ratio * 252 / size y = YahooData() date1 = np.datetime64('2021-05-01') date0 = date1 - np.timedelta64(6 * 365, 'D') indicator = Indicators(y) indicator.create(my_return, name='return(Yr)') df = indicator.extract_column('return(Yr)') ii = (df.index.values >= date0) & (df.index.values <= date1) df2 = df.iloc[ii] descr = df2.describe().sort_values(by='50%', axis=1, ascending=False) # %% plt.plot(y.dataframes['ALGN'][DF_ADJ_CLOSE]) ax = plt.gca() ax.set_yscale('log')