def test_atr2(self): target = 'ATR' result = AverageTrueRange(high=self._df['High'], low=self._df['Low'], close=self._df['Close'], n=14, fillna=False).average_true_range() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False)
def _get_all_ST(self) -> pd.DataFrame: """ ST Indicator, trading predictions, ST high/low """ m = self.close.size dir_, trend = [1] * m, [0] * m long, short = [np.NaN] * m, [np.NaN] * m ATR = AverageTrueRange(high=self.high, low=self.low, close=self.close, window=self.length) hl2_ = (self.high + self.low) / 2 matr = ATR.average_true_range() * self.multiplier upperband = hl2_ + matr lowerband = hl2_ - matr for i in range(1, m): if self.close.iloc[i] > upperband.iloc[i - 1]: dir_[i] = BUY elif self.close.iloc[i] < lowerband.iloc[i - 1]: dir_[i] = SELL else: dir_[i] = dir_[i - 1] if dir_[i] == BUY and lowerband.iloc[i] < lowerband.iloc[i - 1]: lowerband.iloc[i] = lowerband.iloc[i - 1] if dir_[i] == SELL and upperband.iloc[i] > upperband.iloc[i - 1]: upperband.iloc[i] = upperband.iloc[i - 1] if dir_[i] > 0: trend[i] = long[i] = lowerband.iloc[i] else: trend[i] = short[i] = upperband.iloc[i] # Prepare DataFrame to return df = pd.DataFrame( { f"ST": trend, f"ST_strategy": dir_, f"ST_lower": long, f"ST_upper": short, }, index=self.close.index) return df
def get_indicators(df): """ Add set of technical indicators to the dataframe, return original data frame with new features """ feature_df = df.copy() feature_df['RSI'] = RSIIndicator(close=df[CLOSE]).rsi() feature_df['Stochastic'] = StochasticOscillator(high=df[HIGH], low=df[LOW], close=df[CLOSE]).stoch() feature_df['Stochastic_signal'] = StochasticOscillator( high=df[HIGH], low=df[LOW], close=df[CLOSE]).stoch_signal() feature_df['ADI'] = AccDistIndexIndicator( high=df[HIGH], low=df[LOW], close=df[CLOSE], volume=df[VOLUME]).acc_dist_index() feature_df['OBV'] = OnBalanceVolumeIndicator( close=df[CLOSE], volume=df[VOLUME]).on_balance_volume() feature_df['ATR'] = AverageTrueRange(high=df[HIGH], low=df[LOW], close=df[CLOSE]).average_true_range() feature_df['ADX'] = ADXIndicator(high=df[HIGH], low=df[LOW], close=df[CLOSE]).adx() feature_df['ADX_pos'] = ADXIndicator(high=df[HIGH], low=df[LOW], close=df[CLOSE]).adx_pos() feature_df['ADX_neg'] = ADXIndicator(high=df[HIGH], low=df[LOW], close=df[CLOSE]).adx_neg() feature_df['MACD'] = MACD(close=df[CLOSE]).macd() feature_df['MACD_diff'] = MACD(close=df[CLOSE]).macd_diff() feature_df['MACD_signal'] = MACD(close=df[CLOSE]).macd_signal() return feature_df
def add_volatility_ta(df: pd.DataFrame, high: str, low: str, close: str, fillna: bool = False, colprefix: str = "") -> pd.DataFrame: """Add volatility technical analysis features to dataframe. Args: df (pandas.core.frame.DataFrame): Dataframe base. high (str): Name of 'high' column. low (str): Name of 'low' column. close (str): Name of 'close' column. fillna(bool): if True, fill nan values. colprefix(str): Prefix column names inserted Returns: pandas.core.frame.DataFrame: Dataframe with new features. """ # Average True Range df[f'{colprefix}volatility_atr'] = AverageTrueRange( close=df[close], high=df[high], low=df[low], n=10, fillna=fillna).average_true_range() # Bollinger Bands indicator_bb = BollingerBands(close=df[close], n=20, ndev=2, fillna=fillna) df[f'{colprefix}volatility_bbm'] = indicator_bb.bollinger_mavg() df[f'{colprefix}volatility_bbh'] = indicator_bb.bollinger_hband() df[f'{colprefix}volatility_bbl'] = indicator_bb.bollinger_lband() df[f'{colprefix}volatility_bbw'] = indicator_bb.bollinger_wband() df[f'{colprefix}volatility_bbhi'] = indicator_bb.bollinger_hband_indicator( ) df[f'{colprefix}volatility_bbli'] = indicator_bb.bollinger_lband_indicator( ) # Keltner Channel indicator_kc = KeltnerChannel(close=df[close], high=df[high], low=df[low], n=10, fillna=fillna) df[f'{colprefix}volatility_kcc'] = indicator_kc.keltner_channel_central() df[f'{colprefix}volatility_kch'] = indicator_kc.keltner_channel_hband() df[f'{colprefix}volatility_kcl'] = indicator_kc.keltner_channel_lband() df[f'{colprefix}volatility_kchi'] = indicator_kc.keltner_channel_hband_indicator( ) df[f'{colprefix}volatility_kcli'] = indicator_kc.keltner_channel_lband_indicator( ) # Donchian Channel indicator_dc = DonchianChannel(close=df[close], n=20, fillna=fillna) df[f'{colprefix}volatility_dcl'] = indicator_dc.donchian_channel_lband() df[f'{colprefix}volatility_dch'] = indicator_dc.donchian_channel_hband() df[f'{colprefix}volatility_dchi'] = indicator_dc.donchian_channel_hband_indicator( ) df[f'{colprefix}volatility_dcli'] = indicator_dc.donchian_channel_lband_indicator( ) return df
def setUpClass(cls): cls._df = pd.read_csv(cls._filename, sep=',') cls._params = dict(high=cls._df['High'], low=cls._df['Low'], close=cls._df['Close'], n=10, fillna=False) cls._indicator = AverageTrueRange(**cls._params)
def setUpClass(cls): cls._df = pd.read_csv(cls._filename, sep=",") cls._params = dict( high=cls._df["High"], low=cls._df["Low"], close=cls._df["Close"], window=10, fillna=False, ) cls._indicator = AverageTrueRange(**cls._params)
def supertrend(df:pd.DataFrame, period=10, multiplier=3)->pd.DataFrame: #basic upper band = (high + low)/2 + (multipler * atr) #basic lower band = (high + low)/2 - (multipler * atr) atr = AverageTrueRange(high=df['high'], low=df['low'], close=df['close'], window=14) df['atr'] = atr.average_true_range() df['st_upperband'] = ((df['high']+df['low'])/2 + (multiplier*df['atr'])) df['st_lowerband'] = ((df['high']+df['low'])/2 - (multiplier*df['atr'])) df['in_uptrend'] = True for current in range(1, len(df.index)): previous = current-1 if df['close'][current] > df['st_upperband'][previous]: df['in_uptrend'][current] = True elif df['close'][current] < df['st_lowerband'][previous]: df['in_uptrend'][current] = False else: df['in_uptrend'][current] = df['in_uptrend'][previous] if df['in_uptrend'][current] and df['st_lowerband'][current] < df['st_lowerband'][previous]: df['st_lowerband'][current] = df['st_lowerband'][previous] if not df['in_uptrend'][current] and df['st_upperband'][current] > df['st_upperband'][previous]: df['st_upperband'][current] = df['st_upperband'][previous] return df
def get_data_from_yahoo(market_type="nyse", reload=False, rewrite=True): if reload: tickers = save_all_tickers() else: with open(market_type + "tickers.pickle", "rb") as f: tickers = pickle.load(f) if not os.path.exists("stock_" + market_type): os.makedirs("stock_" + market_type) start = dt.datetime(2019, 1, 1) end = dt.datetime.now() for ticker in tickers: print(ticker) ticker = ticker.strip("\n") if "." in ticker and "HK" not in ticker: ticker = ticker.replace(".", "-") #print(ticker) # just in case your connection breaks, we'd like to save our progress! if not os.path.exists("stock_" + market_type + "/{}.csv".format(ticker)) or rewrite: try: #df = web.DataReader(ticker, 'yahoo', start, end) #iex-tops econdb #df.reset_index(inplace=True) #df.set_index("Date", inplace=True) #df = df.drop("Symbol", axis=1) df = yf.download(ticker, start=start, end=end) # Initialize ATR Indicator indicator_atr = AverageTrueRange(high=df["High"], low=df["Low"], close=df["Close"]) # Add ATR df['ATR'] = indicator_atr.average_true_range() # Initialize ATR Indicator indicator_atr_2 = AverageTrueRange(high=df["ATR"], low=df["ATR"], close=df["ATR"]) # Add ATR df['ATR_2'] = indicator_atr_2.average_true_range() df.to_csv("stock_" + market_type + "/{}.csv".format(ticker)) except: continue else: print('Already have {}'.format(ticker))
def exec(self, sym, data5min, ex1: Exchange, ord_log=None, strat_log=None): # print(data5min) # print("-----") # print(data1hour) # print("-------------------------") self.symbol = sym self.ex1 = ex1 # print(data5min) self.ts = data5min.iloc[251]['t1'] self.lasto = data5min.iloc[251]['open'] self.lasth = data5min.iloc[251]['high'] self.lastl = data5min.iloc[251]['low'] self.lastc = data5min.iloc[251]['close'] # self.candles = "["+str(self.ts)+","+str(self.lasto)+","+str(self.lasth)+","+str(self.lastl)+","+str(self.lastc)+"]" self.candle = [] self.candle.append(self.ts) self.candle.append(self.lasto) self.candle.append(self.lasth) self.candle.append(self.lastl) self.candle.append(self.lastc) self.symbol = sym.upper() # datac = data.Data() self.data = data5min ######################################################################################## # strategy variables : self.usr_risk = 3.0 self.atr_mult = 0.5 self.sma_slow = 99 self.sma_med = 25 self.sma_fast = 7 # strategy conditions : # find pinbars in a candle self.bullishPinBar = ( self.lastc > self.lasto and (self.lasto - self.lastl) > 0.66 * (self.lasth - self.lastl)) or (self.lastc < self.lasto and (self.lastc - self.lastl) > 0.66 * (self.lasth - self.lastl)) self.bearishPinBar = ( self.lastc > self.lasto and (self.lasth - self.lastc) > 0.66 * (self.lasth - self.lastl)) or (self.lastc < self.lasto and (self.lasth - self.lasto) > 0.66 * (self.lasth - self.lastl)) # check if we are in an uptrend or downtrend sum1 = 0.0 sum2 = 0.0 sum3 = 0.0 index = 0 while index < 99: if index < 7: sum1 += data5min.iloc[251 - index]['close'] sum2 += data5min.iloc[251 - index]['close'] sum3 += data5min.iloc[251 - index]['close'] if index >= 7 and index < 25: sum2 += data5min.iloc[251 - index]['close'] sum3 += data5min.iloc[251 - index]['close'] if index >= 25 and index < 99: sum3 += data5min.iloc[251 - index]['close'] index += 1 self.ma7 = sum1 / 7 self.ma25 = sum2 / 25 self.ma99 = sum3 / 99 self.upTrend = self.ma7 > self.ma25 and self.ma25 > self.ma99 self.dnTrend = self.ma7 < self.ma25 and self.ma25 < self.ma99 # now lets check some piercing a candle in a MA : self.bullPierce = ( self.lastl < self.ma7 and self.lasto > self.ma7 and self.lastc > self.ma7) or ( self.lastl < self.ma25 and self.lasto > self.ma25 and self.lastc > self.ma25) or (self.lastl < self.ma99 and self.lasto > self.ma99 and self.lastc > self.ma99) self.bearPierce = ( self.lasth > self.ma7 and self.lasto < self.ma7 and self.lastc < self.ma7) or ( self.lasth > self.ma25 and self.lasto < self.ma25 and self.lastc < self.ma25) or (self.lasth > self.ma99 and self.lasto < self.ma99 and self.lastc < self.ma99) # Final long short condition : self.logCondition = self.bullishPinBar and self.upTrend and self.bullPierce self.shortCondition = self.bearishPinBar and self.dnTrend and self.bearPierce # now lets calculate ATR : self.df = self.data self.df["atr"] = AverageTrueRange( high=self.df['high'], low=self.df['low'], close=self.df['close'], window=14, fillna=False, ).average_true_range() # Amount and Entry and Stoploss : risk = self.usr_risk * 0.01 * 10 # 10 is strategy equity self.sl = self.df.iloc[250]['low'] - (self.df.iloc[250]['atr'] * self.atr_mult) self.entry = self.df.iloc[250]['high'] self.amount = risk / (self.entry - self.sl) self.ord_log = ord_log self.strat_log = strat_log # self.ta() self.decide()
def add_volatility_ta( df: pd.DataFrame, high: str, low: str, close: str, fillna: bool = False, colprefix: str = "", vectorized: bool = False, ) -> pd.DataFrame: """Add volatility technical analysis features to dataframe. Args: df (pandas.core.frame.DataFrame): Dataframe base. high (str): Name of 'high' column. low (str): Name of 'low' column. close (str): Name of 'close' column. fillna(bool): if True, fill nan values. colprefix(str): Prefix column names inserted vectorized(bool): if True, use only vectorized functions indicators Returns: pandas.core.frame.DataFrame: Dataframe with new features. """ # Bollinger Bands indicator_bb = BollingerBands(close=df[close], window=20, window_dev=2, fillna=fillna) df[f"{colprefix}volatility_bbm"] = indicator_bb.bollinger_mavg() df[f"{colprefix}volatility_bbh"] = indicator_bb.bollinger_hband() df[f"{colprefix}volatility_bbl"] = indicator_bb.bollinger_lband() df[f"{colprefix}volatility_bbw"] = indicator_bb.bollinger_wband() df[f"{colprefix}volatility_bbp"] = indicator_bb.bollinger_pband() df[f"{colprefix}volatility_bbhi"] = indicator_bb.bollinger_hband_indicator( ) df[f"{colprefix}volatility_bbli"] = indicator_bb.bollinger_lband_indicator( ) # Keltner Channel indicator_kc = KeltnerChannel(close=df[close], high=df[high], low=df[low], window=10, fillna=fillna) df[f"{colprefix}volatility_kcc"] = indicator_kc.keltner_channel_mband() df[f"{colprefix}volatility_kch"] = indicator_kc.keltner_channel_hband() df[f"{colprefix}volatility_kcl"] = indicator_kc.keltner_channel_lband() df[f"{colprefix}volatility_kcw"] = indicator_kc.keltner_channel_wband() df[f"{colprefix}volatility_kcp"] = indicator_kc.keltner_channel_pband() df[f"{colprefix}volatility_kchi"] = indicator_kc.keltner_channel_hband_indicator( ) df[f"{colprefix}volatility_kcli"] = indicator_kc.keltner_channel_lband_indicator( ) # Donchian Channel indicator_dc = DonchianChannel(high=df[high], low=df[low], close=df[close], window=20, offset=0, fillna=fillna) df[f"{colprefix}volatility_dcl"] = indicator_dc.donchian_channel_lband() df[f"{colprefix}volatility_dch"] = indicator_dc.donchian_channel_hband() df[f"{colprefix}volatility_dcm"] = indicator_dc.donchian_channel_mband() df[f"{colprefix}volatility_dcw"] = indicator_dc.donchian_channel_wband() df[f"{colprefix}volatility_dcp"] = indicator_dc.donchian_channel_pband() if not vectorized: # Average True Range df[f"{colprefix}volatility_atr"] = AverageTrueRange( close=df[close], high=df[high], low=df[low], window=10, fillna=fillna).average_true_range() # Ulcer Index df[f"{colprefix}volatility_ui"] = UlcerIndex( close=df[close], window=14, fillna=fillna).ulcer_index() return df