def _candle_indicators(): # with dpg.collapsing_header(label='indicators'): indicators.rlines() indicators.sma() indicators.ema() indicators.rsi() indicators.bbands()
def ma(data: list, data_properties: dict, ma_type: int = 0) -> dict: """ Strategy for moving averages. :param data: list[numeric] :param data_properties: dict :param ma_type: Moving Average Type SMA = 0 (Default case) EMA = 1 :return: dict Result from strategy_builder """ close = data_parser.get_close(data) if ma_type == 1: ma50 = indicators.ema(close, period=50) ma200 = indicators.ema(close, period=200) else: ma50 = indicators.sma(close, period=50) ma200 = indicators.sma(close, period=200) buy = Condition(data1=ma50, data2=ma200, operation=Operation.CROSSOVER) sell = Condition(data1=ma50, data2=ma200, operation=Operation.CROSSUNDER) chart_1 = ChartElement(data=ma50, label="ma50", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS) chart_2 = ChartElement(data=ma200, label="ma200", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS) charts = [chart_1, chart_2] result = strategy_builder(data_properties=data_properties, data_list=data, strategy=BUY, buy=buy, sell=sell, charts=charts) return result
def update(self, candles, strategy, productID): if self.usesLongMA(): self.ma3Value = indicators.sma(candles, strategy.intervalSecs, strategy.ma3Count) self.ma4Value = indicators.sma(candles, strategy.intervalSecs, strategy.ma4Count) self.ma1Value = indicators.wma(strategy.maWeight, candles, strategy.intervalSecs, strategy.ma1Count) self.ma2Value = indicators.wma(strategy.maWeight, candles, strategy.intervalSecs, strategy.ma2Count) self.price = gdax_api.getPrice(productID)
def addEvidence(self, symbol="AAPL", sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31), sv=100000): leaf_size, bags, days, yBuy, ySell = 5, 20, 10, 0.04, -0.04 prices = get_data([symbol], pd.date_range(sd, ed))[[symbol]] nDayReturns = (prices.shift(-days) / prices) - 1.0 # Create x data for training by combining price/SMA and Bollinger calculations # Decided not to use momentum since it is not very reliable in predicting price trends dataX = pd.concat( [prices / sma(prices), bb(prices)], axis=1)[:-days].values # Every entry in y data is -1, 0, or 1 based on how associated nDayReturns values compares to buy/sell thresholds dataY = [] for index, row in nDayReturns.iterrows(): entry = row[nDayReturns.columns.values[0]] dataY.append(1.0 if entry > (self.impact + yBuy) else ( -1.0 if entry < (ySell - self.impact) else 0.0)) self.learner = bl.BagLearner(rt.RTLearner, {'leaf_size': leaf_size}, bags, False, False) self.learner.addEvidence(dataX, np.asarray(dataY))
def testPolicy(symbol='JPM', sd=dt.datetime(2008,1,1), ed=dt.datetime(2009,12,31), sv=100000): prices = get_data([symbol], pd.date_range(sd, ed)) prices = prices[symbol] SMA = sma(prices) BBP = bbp(prices, SMA) SMA = prices / SMA orders = prices.copy() orders[:] = 0 orders[(SMA < 0.95) & (BBP < 0)] = 1 orders[(SMA > 1.05) & (BBP > 1)] = -1 holdings = 0.0 trades = [] for date in orders.index: trade = 0 if orders.loc[date] == 1: trade = 1000 - holdings trades.append((date, trade)) elif orders.loc[date] == -1: trade = -1000 - holdings trades.append((date, trade)) elif orders.loc[date] == 0: trade = 0 trades.append((date, trade)) holdings = holdings + trade df_trades = pd.DataFrame(trades, columns=["Date", symbol]) df_trades.set_index("Date", inplace=True) return df_trades
def testPolicy(symbol='JPM', sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31), sv=100000): prices = get_data([symbol], pd.date_range(sd, ed))[symbol] priceSMA = prices / sma(prices) BB = bb(prices) # Decide order types based on price-to-SMA ratio and calculated Bollinger value # Decided not to use momentum since it is not very reliable in predicting price trends orders = prices.copy() orders[:] = 0 orders[(priceSMA > 1.02) & (BB > 1)] = -1 orders[(priceSMA < 0.98) & (BB < 0)] = 1 # Make trades based on current holdings and order types trades = [] holdings = 0.0 for date in orders.index: if orders.loc[date] == 1: trades.append((date, 1000 - holdings)) holdings = 1000 elif orders.loc[date] == -1: trades.append((date, -1000 - holdings)) holdings = -1000 elif orders.loc[date] == 0: trades.append((date, 0)) # for date in orders.index: trades.append((date, orders.loc[date] * 1000)) tradesDataframe = pd.DataFrame(trades, columns=["Date", "Shares"]) tradesDataframe.set_index("Date", inplace=True) return tradesDataframe
def testPolicy(symbol="AAPL", sd=dt.datetime(2010, 1, 1), ed=dt.datetime(2011, 12, 31), sv=100000): bb_index = bb(sd, ed, [symbol]) sma_index = sma(sd, ed, [symbol], ratio=True) so_index = so(sd, ed, [symbol]) decisions = pd.DataFrame(index=bb_index.index) decisions['bb'] = [ -1 if x > 1 else 1 if x < 0 else 0 for x in bb_index[symbol] ] decisions['sma'] = [ -1 if x > 1.05 else 1 if x < 0.95 else 0 for x in sma_index[symbol] ] decisions['so'] = [ -1 if x > 80 else 1 if x < 20 else 0 for x in so_index[symbol] ] decisions['holding'] = [ 0 if x == 0 else 1000 if x > 0 else -1000 for x in decisions.sum(axis=1) ] decisions[symbol] = 0 decisions[symbol].values[1:] = decisions['holding'].values[1:] - decisions[ 'holding'].values[:-1] # print decisions['trade'] decisions = decisions[[symbol]] return decisions
def testPolicy(self, symbol = "IBM", \ sd=dt.datetime(2009,1,1), \ ed=dt.datetime(2010,1,1), \ sv = 10000): syms = [symbol] dates = pd.date_range(sd, ed) prices = ut.get_data(syms, dates) prices = prices[syms] SMA = sma(prices) BBP = bbp(prices, SMA) SMA = prices / SMA Xtest = pd.concat([SMA, BBP], axis=1) Xtest = Xtest.values Y = self.learner.query(Xtest) trades = pd.DataFrame(0.0, index=prices.index, columns=[symbol]) holdings = 0.0 for i in range(0, trades.shape[0] - 1): if Y[0][i] >= 0.5: trades[symbol].iloc[i] = 1000.0 - holdings elif Y[0][i] <= -0.5: trades[symbol].iloc[i] = -1000.0 - holdings else: trades[symbol].iloc[i] = 0.0 holdings += trades[symbol].iloc[i] return trades
def dataset_addind(self,sd,ed,symbol,lookback): sma = ind.sma(sd , ed ,syms = [symbol],lookback = self.lb, ratio = False) bb = ind.bb(sd , ed ,syms = [symbol],lookback = self.lb) rsi = ind.rsi(sd , ed ,syms = [symbol],lookback = self.lb) so = ind.so(sd , ed ,syms = [symbol],lookback = self.lb) df = pd.concat([sma,bb[[symbol]],rsi[[symbol]],so[[symbol]]],axis = 1) return df
def dataset_addind(self,sd,ed,symbol,last_inst): # Callling indicators from indicatators.py sma = indicators.sma(sd , ed ,syms = [symbol],last_inst = self.lb, ratio = False) bollinger_bands = indicators.bollinger_bands(sd , ed ,syms = [symbol],last_inst = self.lb) relative_strength = indicators.relative_strength(sd , ed ,syms = [symbol],last_inst = self.lb) sochastic_oscillator = indicators.sochastic_oscillator(sd , ed ,syms = [symbol],last_inst = self.lb) df = pd.concat([sma,bollinger_bands[[symbol]],sochastic_oscillator[[symbol]]],axis = 1) return df
def testPolicy(symbol='JPM', sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31)): bb_indicator = bb(symbol=[symbol], sd=sd, ed=ed) sma_indicator = sma(symbol=[symbol], sd=sd, ed=ed) ema_indicator = ema(symbol=[symbol], sd=sd, ed=ed) #create new strategy df strategy = pd.DataFrame(index=bb_indicator.index) #thresholds and buy/sell/hold flags strategy['sma'] = [ -1 if x > 1.02 else 1 if x < 0.98 else 0 for x in sma_indicator ] strategy['bb'] = [ -1 if x > 1.5 else 1 if x < -.5 else 0 for x in bb_indicator ] strategy['ema'] = [ -1 if x > 1.02 else 1 if x < .98 else 0 for x in ema_indicator ] strategy['holding'] = [ 0 if x == 0 else 1000 if x > 0 else -1000 for x in strategy.sum(axis=1) ] # print strategy strategy[symbol] = 0 strategy[symbol].values[ 1:] = strategy['holding'].values[1:] - strategy['holding'].values[:-1] df_trades = strategy[[symbol]] return df_trades # if __name__ == "__main__": # df_trades = testPolicy() # print df_trades
def indicator(self, ticker): df = {} df['sma'] = indicators.sma(ticker['close'], window=10) df['close'] = ticker['close'] df = pd.DataFrame(df) df = df.reset_index(drop=True) return df
def SMA_level_stats(self, df1, F, S): symbols = df1.columns timestamps = df1.index df_SMA_stats = pd.DataFrame(index=timestamps, columns=symbols) df_SMA_stats = df_SMA_stats.fillna(0) stats_col = [ 'FLS', 'FGS', 'FIFTY', 'TWOH', 'TWOF', 'NFIFTY', 'NTWOH', 'NTWOF', 'SPY' ] df_stats = pd.DataFrame(index=timestamps, columns=stats_col) df_stats = df_stats.fillna(0) df_sma_fast = indicators.sma(df1, F) df_sma_slow = indicators.sma(df1, S) for ts in range(0, len(timestamps)): df_stats['SPY'].ix[ts] = df1['SPY'].ix[ts] for sym in symbols: if df_sma_fast[sym].ix[ts] > df_sma_slow[sym].ix[ts]: df_stats['FGS'].ix[ts] = df_stats['FGS'].ix[ts] + 1 if df1[sym].ix[ts] > df_sma_fast[sym].ix[ts]: df_stats['FIFTY'].ix[ts] = df_stats['FIFTY'].ix[ts] + 1 if df1[sym].ix[ts] < df_sma_slow[sym].ix[ts]: df_stats['TWOH'].ix[ts] = df_stats['TWOH'].ix[ts] + 1 if df1[sym].ix[ts] < df_sma_fast[sym].ix[ts] and df1[ sym].ix[ts] > df_sma_slow[sym].ix[ts]: df_stats['TWOF'].ix[ts] = df_stats['TWOF'].ix[ts] + 1 elif df_sma_fast[sym].ix[ts] < df_sma_slow[sym].ix[ts]: df_stats['FLS'].ix[ts] = df_stats['FLS'].ix[ts] + 1 if df1[sym].ix[ts] < df_sma_fast[sym].ix[ts]: df_stats['NFIFTY'].ix[ ts] = df_stats['NFIFTY'].ix[ts] + 1 if df1[sym].ix[ts] > df_sma_slow[sym].ix[ts]: df_stats['NTWOH'].ix[ts] = df_stats['NTWOH'].ix[ts] + 1 if df1[sym].ix[ts] > df_sma_fast[sym].ix[ts] and df1[ sym].ix[ts] < df_sma_slow[sym].ix[ts]: df_stats['NTWOF'].ix[ts] = df_stats['NTWOF'].ix[ts] + 1 df_stats.to_csv('./debug/df_stats.csv') return df_SMA_stats
def getIndicators(self, dates, ed, syms, window=14, lookback=3): # I can look back at historical data before # the actual start date of the portfolio as # long as I only use that for technical analysis lookback_dates = pd.date_range(dates[0] - (window * 2), ed) prices_w_lookback = ut.get_data(syms, lookback_dates, addSPY=True, colname='Adj Close')[syms] bbp = ind.bollinger_percentage(prices_w_lookback, window) sma = ind.sma(prices_w_lookback, window) momentum = ind.momentum(prices_w_lookback, lookback) return bbp, sma, momentum
def SMA_level_stats(self, df1, F, S): symbols = df1.columns timestamps = df1.index df_SMA_stats = pd.DataFrame(index = timestamps, columns = symbols) df_SMA_stats = df_SMA_stats.fillna(0) stats_col = ['FLS','FGS','FIFTY','TWOH','TWOF','NFIFTY','NTWOH','NTWOF','SPY'] df_stats = pd.DataFrame(index = timestamps, columns = stats_col) df_stats = df_stats.fillna(0) df_sma_fast = indicators.sma(df1,F) df_sma_slow = indicators.sma(df1,S) for ts in range(0,len(timestamps)): df_stats['SPY'].ix[ts] = df1['SPY'].ix[ts] for sym in symbols: if df_sma_fast[sym].ix[ts] > df_sma_slow[sym].ix[ts]: df_stats['FGS'].ix[ts] = df_stats['FGS'].ix[ts] + 1 if df1[sym].ix[ts] > df_sma_fast[sym].ix[ts]: df_stats['FIFTY'].ix[ts] = df_stats['FIFTY'].ix[ts] + 1 if df1[sym].ix[ts] < df_sma_slow[sym].ix[ts]: df_stats['TWOH'].ix[ts] = df_stats['TWOH'].ix[ts] + 1 if df1[sym].ix[ts] < df_sma_fast[sym].ix[ts] and df1[sym].ix[ts] > df_sma_slow[sym].ix[ts]: df_stats['TWOF'].ix[ts] = df_stats['TWOF'].ix[ts] + 1 elif df_sma_fast[sym].ix[ts] < df_sma_slow[sym].ix[ts]: df_stats['FLS'].ix[ts] = df_stats['FLS'].ix[ts] + 1 if df1[sym].ix[ts] < df_sma_fast[sym].ix[ts]: df_stats['NFIFTY'].ix[ts] = df_stats['NFIFTY'].ix[ts] + 1 if df1[sym].ix[ts] > df_sma_slow[sym].ix[ts]: df_stats['NTWOH'].ix[ts] = df_stats['NTWOH'].ix[ts] + 1 if df1[sym].ix[ts] > df_sma_fast[sym].ix[ts] and df1[sym].ix[ts] < df_sma_slow[sym].ix[ts]: df_stats['NTWOF'].ix[ts] = df_stats['NTWOF'].ix[ts] + 1 df_stats.to_csv('./debug/df_stats.csv') return df_SMA_stats
def handle_message(msg): global kierros kierros += 1 if msg['e'] == 'error': #Jos ilmenee ongelmia niin näytetään virheilmoitus ja jatketaan ohjelman ajoa mikäli mahdollista print(msg['m']) #Jos ei ole ongelmaa niin aletaan striimata tietoa reaaliajassa else: hinta = float(msg['k']['c']) lista[0] = hinta sma200, sma50 = indicators.sma(lista) if (kierros % 60 == 0): lista.pop() lista.insert(0, hinta) print("Lista päivitetty") print("----------------", kierros, "----------------") print("SMA50: ", sma50) print("SMA200: ", sma200) print("Hinta: ", hinta) balance = float(client.get_asset_balance(asset='BNB')['free']) #Jos tilillä alle 0.5BNB niin ostetaan if balance < 0.5: if sma50 < hinta: #Jos oston ehdot täyttyvät niin ajetaan osta-functio ( action.py - osta() ) #Välitetään osta-functiolle client, quantity ja api-symbol action.osta(client, quantity, api_symbol) sleep(5) else: print("Odotetaan ostoa") #Jos tilillä yli 0.5BNB niin myydään else: if sma50 > hinta: #Jos myynnin ehdot täyttyvät niin ajetaan myy-functio ( action.py - myy() ) action.myy(client, api_symbol) else: print("Odotetaan myyntiä")
def addEvidence(self, symbol = "IBM", \ sd=dt.datetime(2008,1,1), \ ed=dt.datetime(2009,1,1), \ sv = 10000): leaf_size = 5 bags = 50 N = 10 YBUY = 0.01 YSELL = -0.01 syms = [symbol] dates = pd.date_range(sd, ed) prices = ut.get_data(syms, dates) prices = prices[syms] SMA = sma(prices) BBP = bbp(prices, SMA) SMA = prices / SMA X = pd.concat([SMA, BBP], axis=1) X = X[:-N] X = X.values ndayreturns = (prices.shift(-N) / prices) - 1.0 Y = ndayreturns.applymap(lambda x: 1.0 if x > (YBUY + self.impact) else (-1.0 if x < (YSELL - self.impact) else 0.0)) Y = Y.dropna() Y = Y.values self.learner = bl.BagLearner(learner=rt.RTLearner, kwargs={'leaf_size': leaf_size}, bags=bags, boost=False, verbose=False) self.learner.addEvidence(X, Y)
def testPolicy(self, symbol="AAPL", sd=dt.datetime(2010, 1, 1), ed=dt.datetime(2011, 12, 31), sv=100000): prices = get_data([symbol], pd.date_range(sd, ed))[[symbol]] trades = pd.DataFrame(0.0, prices.index, [symbol]) dataX = pd.concat([prices / sma(prices), bb(prices)], axis=1).values queryResults = self.learner.query(dataX) # Update values in trades based on holdings at each step and output from query to learner holdings = 0.0 for i in range(trades.shape[0]): if abs(queryResults[0][i]) < 0.5: trades[symbol].iloc[i] = 0.0 else: trades[symbol].iloc[i] = 1000.0 - holdings - ( 0 if queryResults[0][i] >= 0.5 else 2000) holdings += trades[symbol].iloc[i] return trades
def testPolicy(symbol='JPM', sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31), sv=100000): prices = get_data([symbol], pd.date_range(sd, ed))[symbol] priceSMA = prices / sma(prices) BB = bb(prices) # Decide order types based on price-to-SMA ratio and calculated Bollinger value orders = prices.copy() orders[:] = 0 orders[(priceSMA > 1.02) & (BB > 1)] = -1 orders[(priceSMA < 0.98) & (BB < 0)] = 1 trades = [] for date in orders.index: trades.append((date, orders.loc[date] * 1000)) tradesDataframe = pd.DataFrame(trades, columns=["Date", "Shares"]) tradesDataframe.set_index("Date", inplace=True) return tradesDataframe
def testPolicy(symbol=["JPM"], sd=dt.datetime(2010, 1, 1), ed=dt.datetime(2011, 12, 31), sv=100000): prices = get_data(['JPM'], pd.date_range(sd, ed), addSPY=True, colname='Adj Close') # mean_5 = indicators.mean_2(prices) # mean_5 = mean_5[19:] orders = pd.DataFrame().reindex_like(prices) orders = orders.rename(index=str, columns={ "SPY": "Position", "JPM": "Symbol" }) orders['Symbol'] = 'JPM' orders['Shares'] = 0 orders['Position'] = 0 orders['Order'] = 'HOLD' orders.index.name = 'Date' orders.index = pd.to_datetime(orders.index, format="%Y/%m/%d") # # SMA # sma_20 = indicators.sma(prices, 20) # sma_5 = indicators.sma(prices, 5) # for date, row in orders.iloc[2:, :].iterrows(): # stock = row['Symbol'] # i = orders.index.get_loc(date) # p0 = prices.iloc[i, 1] # sma_5_1 = sma_5.iloc[i-1, 1] # sma_20_1 = sma_20.iloc[i-1, 1] # sma_5_2 = sma_5.iloc[i-2, 1] # sma_20_2 = sma_20.iloc[i-2, 1] # current = row['Position'] # if sma_5_1 < sma_20_1 and sma_5_2 > sma_20_2: # buy # target = min(1000, sv // p0 + current) # orders.loc[date, 'Shares'] = target - current # orders.loc[date, 'Position'] = target # orders.loc[date, 'Order'] = 'BUY' # sv -= (target - current) * p0 # elif sma_5_1 > sma_20_1 and sma_5_2 < sma_20_2: # target = min(1000, sv // p0 + current) # orders.loc[date, 'Shares'] = target - current # orders.loc[date, 'Position'] = -target # orders.loc[date, 'Order'] = 'SELL' # sv += (target - current) * p0 # else: # orders.loc[date, 'Shares'] = 0 # orders.loc[date, 'Position'] = current # orders.loc[date, 'Order'] = 'HOLD' #SMA sma = indicators.sma(prices, 10) for date, row in orders.iloc[2:, :].iterrows(): stock = row['Symbol'] i = orders.index.get_loc(date) p0 = prices.iloc[i, 1] p1 = prices.iloc[i - 1, 1] ma1 = sma.iloc[i - 1, 1] p2 = prices.iloc[i - 2, 1] ma2 = sma.iloc[i - 2, 1] current = row['Position'] if p1 < ma1 * 0.95: # buy target = min(1000, sv // p0 + current) orders.loc[date, 'Shares'] = target - current orders.loc[date, 'Position'] = target orders.loc[date, 'Order'] = 'BUY' sv -= (target - current) * p0 elif p1 > ma1 * 1.05: target = min(1000, sv // p0 + current) orders.loc[date, 'Shares'] = target - current orders.loc[date, 'Position'] = -target orders.loc[date, 'Order'] = 'SELL' sv += (target - current) * p0 else: orders.loc[date, 'Shares'] = 0 orders.loc[date, 'Position'] = current orders.loc[date, 'Order'] = 'HOLD' return orders
import numpy as np import sys import indicators CANDLE_SIZE = 10 inds = [ indicators.ema(5), indicators.ema(10), indicators.ema(50), indicators.ema(100), indicators.ema(200), indicators.sma(20), indicators.sma(50), indicators.rsi(14), indicators.macd(12, 26), indicators.accdistdelt(), indicators.ichimoku_tenkan(), indicators.ichimoku_kijun() ] def main(): print "Loadng from txt" idata = np.genfromtxt(sys.argv[1], delimiter=',', skip_header=2, usecols=[1, 2, 3, 4, 6]) i = 0
def chart(): """ For plotting normal candle chart or along with indicators :return: None """ # prop, data = data_parser.get_data(start_date="2017-08-18") # result = Strategies.rsi(data, data_properties=prop) # data_properties = result['data_properties'] # main_chart = [] # for key, values in data_properties.items(): # main_chart.append([key, values]) # params = result['params'] # data = result['data'] # print(params,data_with_indicators) # final_data = data_with_indicators[1:] # print(final_data) data_prop, data = data_parser.get_data(start_date="2007-01-18") high = data_parser.get_high(data) low = data_parser.get_low(data) close = data_parser.get_close(data) sma = indicators.sma(close) ema = indicators.ema(close) macd = indicators.macd(close) rsi = indicators.rsi(close) stoch = indicators.stoch(high, low, close) bbands = indicators.bollinger_bands(close) pivot = indicators.pivot(data) chart_1 = ChartElement(data=sma, label="sma", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.YELLOW) chart_2 = ChartElement(data=ema, label="ema", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.PINK) chart_3 = ChartElement(data=stoch, label="stoch", chart_type=ChartType.LINE, plot=ChartAxis.DIFFERENT_AXIS, color=ChartColor.PURPLE) chart_4 = ChartElement(data=bbands, label="bbands", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.BLUE) chart_5 = ChartElement(data=pivot, label="pivot", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.GREEN) chart_6 = ChartElement(data=rsi, label="rsi", chart_type=ChartType.LINE, plot=1, color=ChartColor.RED) chart_7 = ChartElement(data=macd, label="macd", chart_type=ChartType.LINE, plot=2, color="magenta") charts = [chart_4, chart_6] buy = Condition(data1=sma, data2=ema, operation=Operation.CROSSOVER) sell = Condition(data1=rsi, data2=70, operation=Operation.GREATER_THAN) result = strategy.strategy_builder(data_properties=data_prop, data_list=data, charts=charts, buy=buy, sell=sell, target=1.0, sl=0.5, strategy=strategy.BUY) # strategy.show_back_testing_reports(result, auto_open=True) data_properties = result['data_properties'] main_chart = [] for key, values in data_properties.items(): main_chart.append([key, values]) params = result['params'] # print(params) data_list = result['data'] return render_template("chart.html", chartData=data_list, chart_params=params, main_chart_properties=main_chart)
def cum_pl_short(): """ Chart for back test reports of Cumulative profit and loss :return: None """ data_prop, data = data_parser.get_data(start_date="2000-01-18") high = data_parser.get_high(data) low = data_parser.get_low(data) close = data_parser.get_close(data) sma = indicators.sma(close) ema = indicators.ema(close) macd = indicators.macd(close) rsi = indicators.rsi(close) stoch = indicators.stoch(high, low, close) bbands = indicators.bollinger_bands(close) pivot = indicators.pivot(data) chart_1 = ChartElement(data=sma, label="sma", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.YELLOW) chart_2 = ChartElement(data=ema, label="ema", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.PINK) chart_3 = ChartElement(data=stoch, label="stoch", chart_type=ChartType.LINE, plot=ChartAxis.DIFFERENT_AXIS, color=ChartColor.PURPLE) chart_4 = ChartElement(data=bbands, label="bbands", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.BLUE) chart_5 = ChartElement(data=pivot, label="pivot", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.GREEN) chart_6 = ChartElement(data=rsi, label="rsi", chart_type=ChartType.LINE, plot=1, color=ChartColor.RED) chart_7 = ChartElement(data=macd, label="macd", chart_type=ChartType.LINE, plot=2, color="magenta") charts = [chart_1, chart_2, chart_3, chart_6] buy = Condition(data1=sma, data2=ema, operation=Operation.CROSSOVER) sell = Condition(data1=rsi, data2=70, operation=Operation.GREATER_THAN) result = strategy.strategy_builder(data_properties=data_prop, data_list=data, charts=charts, buy=buy, sell=sell, target=1.0, sl=0.5, strategy=strategy.BUY) cum_short = result['short']['DATE_CUM_PL'] # print(cum_short) return render_template("cum_pl_short.html", shortData=cum_short)
def indicator(self, ticker): df = {} dataframe = ticker df['rsi'] = pd.DataFrame( numpy.nan_to_num(ta.RSI(dataframe, timeperiod=5))) rsiframe = pd.DataFrame(df['rsi']) rsiframe.columns = ['close'] df['emarsi'] = pd.DataFrame( numpy.nan_to_num(ta.EMA(rsiframe, timeperiod=5))) df['adx'] = pd.DataFrame(numpy.nan_to_num(ta.ADX(dataframe))) df['minusdi'] = pd.DataFrame(numpy.nan_to_num(ta.MINUS_DI(dataframe))) minusdiframe = pd.DataFrame(df['minusdi']) minusdiframe.columns = ['close'] df['minusdiema'] = pd.DataFrame( numpy.nan_to_num(ta.EMA(minusdiframe, timeperiod=25))) df['plusdi'] = pd.DataFrame(numpy.nan_to_num(ta.PLUS_DI(dataframe))) plusdiframe = pd.DataFrame(df['plusdi']) plusdiframe.columns = ['close'] df['plusdiema'] = pd.DataFrame( numpy.nan_to_num(ta.EMA(plusdiframe, timeperiod=5))) df['lowsma'] = pd.DataFrame( numpy.nan_to_num(ta.EMA(dataframe, timeperiod=60))) df['highsma'] = pd.DataFrame( numpy.nan_to_num(ta.EMA(dataframe, timeperiod=120))) df['fastsma'] = pd.DataFrame( numpy.nan_to_num(indicators.sma(dataframe['close'], window=120))) df['slowsma'] = pd.DataFrame( numpy.nan_to_num(indicators.sma(dataframe['close'], window=240))) df['trend'] = pd.DataFrame(df['fastsma'] - df['slowsma']) df['trend'].columns = ['close'] temp = df['fastsma'].gt(df['slowsma']) temp.columns = ['close'] df['bigup'] = pd.DataFrame(temp & pd.DataFrame(df['trend'].gt( pd.DataFrame(dataframe['close'].reset_index() / 300)))) df['bigdown'] = pd.DataFrame(~df['bigup']) df['preparechangetrend'] = pd.DataFrame(df['trend'].gt( df['trend'].shift())) df['preparechangetrendconfirm'] = pd.DataFrame( df['preparechangetrend'] & (df['trend'].shift().gt(df['trend'].shift(2)))) df['continueup'] = pd.DataFrame( (df['slowsma'].gt(df['slowsma'].shift())) & (df['slowsma'].shift().gt(df['slowsma'].shift(2)))) df['delta'] = pd.DataFrame(df['fastsma'] - df['fastsma'].shift()) df['slowingdown'] = pd.DataFrame(df['delta'].lt(df['delta'].shift())) # sd = {} df['close'] = ticker['close'] df['volume'] = pd.DataFrame(ticker['volume']) df['date'] = ticker['date'] for key in df: df[key] = df[key].values.tolist() df = pd.DataFrame(df) df = df.reset_index(drop=True) return df
dateEnd ).get_data() # split to Bid/Ask dfdict = func.splitbidask(dfprices) #----------------------------------------------------------------------------- # indicators testing #----------------------------------------------------------------------------- dfbid = dfdict['bid'] dfbid.head() dfbid.dtypes df1 = ind.trix( dfbid, [10,15]) df1 = ind.sma( dfbid, window = [3,5,9]) df1 = ind.sma( dfbid, 'volume', [5]) df1 = ind.bband( dfbid, 21) df1.head(30) df1 = ( dfbid.pipe( ind.bband, 21) .pipe( ind.sma, [3,5,9]) .pipe( ind.trix, [7,11]) #-----------------------------------------------------------------------------
print("Tilillä yhteensä ", balance, " ETH") print("Tilillä yhteensä ", balance2, " USDT") osto_lkm = 0 myynti_lkm = 0 #Osto osto = True while osto == True: #Valuutan arvot viimeiseltä 200 minuutilta (1 minuutin kynttilät) valuutan_tiedot = prices.valuutan_tiedot() #Hinta nyt price = valuutan_tiedot[0] #Simple moving averages (200 ja 50) sma200, sma50 = indicators.sma(valuutan_tiedot) print("Hinta nyt: ", price) balance = client.get_asset_balance(asset='ETH')['free'] #Osto if float(balance) == 0: print("Kierros: ",osto_lkm) if (sma50 > sma200 and sma50 < price): print("ostetaan------------------------------------------") client.order_market_buy(symbol=api_symbol, quantity=quantity) balance = client.get_asset_balance(asset='ETH')['free'] print("Tilillä yhteensä ", balance, " ETH") osto_lkm = 0 sleep(5) else: print("Odotetaan ostoa...")
def test_sma(self): self.assertEqual(indicators.sma([2,3,5,6],3),[3,4])
def testPolicy(self, symbol = "IBM", \ sd=dt.datetime(2009,1,1), \ ed=dt.datetime(2010,1,1), \ sv = 10000): # here we build a fake set of trades # your code should return the same sort of data dates = pd.date_range(sd, ed) prices_all = ut.get_data([symbol], dates) # automatically adds SPY prices = prices_all[[ symbol, ]] # only portfolio symbols trades_SPY = prices_all['SPY'] # only SPY, for comparison later #print prices S = sma(prices, 20) upper, lower, bb, r_m, r_std = bollinger(prices) M = momentum(prices) SMA = pd.DataFrame({'SMA': S}) bb_val = pd.DataFrame({'Bollinger': bb}) Upper = pd.DataFrame({'Upper': upper}) Lower = pd.DataFrame({'Lower': lower}) Momentum = pd.DataFrame({'Momentum': M}) R_M = pd.DataFrame({'Rolling Mean': r_m}) R_STD = pd.DataFrame({"Rolling STD": r_std}) ind = pd.concat((SMA, bb_val, Upper, Lower, R_M, R_STD, Momentum), axis=1) ind.fillna(0, inplace=True) ind = ind[:-self.Days] x_test = ind.values ''' x_test = np.zeros(shape=(len(prices) - self.Days, 3)) for i in range(0, len(prices) - self.Days): if i<20: x_test[i][0] = 0 x_test[i][1] = 0 x_test[i][2] = 0 else: x_test[i][0] = SMA.iloc[i] x_test[i][1] = bb_val.iloc[i] x_test[i][2] = Momentum.iloc[i] ''' #print x_test y_ans = self.learner.query(x_test) #print(y_ans) trades = pd.DataFrame(0, columns=prices.columns, index=prices.index) shares = 0 for i in range(0, len(prices) - self.Days): if y_ans[i] == 1: trades[symbol].iloc[i] = 1000 - shares shares = 1000 elif y_ans[i] == -1: trades[symbol].iloc[i] = -shares - 1000 shares = -1000 #print trades ''' trades.values[:,:] = 0 # set them all to nothing trades.values[0,:] = 1000 # add a BUY at the start trades.values[40,:] = -1000 # add a SELL trades.values[41,:] = 1000 # add a BUY trades.values[60,:] = -2000 # go short from long trades.values[61,:] = 2000 # go long from short trades.values[-1,:] = -1000 #exit on the last day if self.verbose: print type(trades) # it better be a DataFrame! if self.verbose: print trades if self.verbose: print prices_all ''' return trades
def addEvidence(self, symbol = "JPM", \ sd=dt.datetime(2008,1,1), \ ed=dt.datetime(2009,12,31), \ sv = 100000): dates = pd.date_range(sd, ed) prices = ut.get_data([symbol], dates)[[symbol]] prices['Cash'] = 1.0 high = ut.get_data([symbol], dates, colname='High')[[symbol]] low = ut.get_data([symbol], dates, colname='Low')[[symbol]] orig_close = ut.get_data([symbol], dates, colname='Close')[[symbol]] adj_high = high * prices[[symbol]] / orig_close adj_low = low * prices[[symbol]] / orig_close orders = pd.DataFrame().reindex_like(prices) orders = orders.rename(index=str, columns={ 'Cash': 'Order', symbol: 'Shares' }) orders['Shares'] = 0 orders['Order'] = 'CASH' orders.index.name = 'Date' orders.index = pd.to_datetime(orders.index, format="%Y/%m/%d") positions = pd.DataFrame().reindex_like(prices) positions.fillna(0, inplace=True) positions.iloc[0, -1] = sv action = self.learner.querysetstate(0) sma_range = indicators.sma(prices[[symbol]], 10).iloc[:, 0] sma_bins = pd.qcut(sma_range, 10, labels=False) bb_range = indicators.bb(prices[[symbol]]) bb_range['value'] = bb_range.High - bb_range.Low bb_range.fillna(method='bfill', inplace=True) bb_range = bb_range['value'] bb_bins = pd.qcut(bb_range, 10, labels=False) comparisons = [ adj_high[symbol] - adj_low[symbol], abs(adj_low[symbol] - prices[symbol].shift(1)), abs(adj_high[symbol] - prices[symbol].shift(1)) ] tr = pd.concat(comparisons, axis=1).max(axis=1) tr.fillna(method='bfill', inplace=True) atr_range = tr.rolling(14, min_periods=1).mean() atr_bins = pd.qcut(atr_range, 10, labels=False) states = sma_bins * 100 + bb_bins * 10 + atr_bins states = atr_bins * 100 + bb_bins * 10 + sma_bins #states = pd.qcut(sma_range, 500, labels=False) # for experiment 1 to compare with manual strategy pre_shares = 0 normalized_close = prices[symbol] / prices.iloc[0, 0] daily_return = normalized_close - normalized_close.shift(1) daily_return.fillna(method='bfill', inplace=True) pre_orders = orders.copy() pre_orders.iloc[0, 0] = 1000 while not orders.equals(pre_orders): # check if converges pre_cash = sv pre_holdings = 0 pre_orders = orders.copy() for date, row in orders.iterrows(): cur_state = states[date] reward = daily_return[date] * pre_holdings * (1 - self.impact) action = self.learner.query(cur_state, reward) orders.loc[date, 'Order'] = action if action == 0: orders.loc[date, 'Shares'] = -1000 - pre_shares positions.loc[date, symbol] = -1000 if action == 1: orders.loc[date, 'Shares'] = 0 - pre_shares positions.loc[date, symbol] = 0 if action == 2: orders.loc[date, 'Shares'] = 1000 - pre_shares positions.loc[date, symbol] = 1000 positions.loc[date, 'Cash'] = pre_cash - orders.loc[ date, 'Shares'] * prices.loc[date, symbol] pre_cash = positions.loc[date, 'Cash'] pre_holdings = positions.loc[date, symbol]
def testPolicy(self, symbol = "JPM", \ sd=dt.datetime(2010,1,1), \ ed=dt.datetime(2011,12,31), \ sv = 100000): dates = pd.date_range(sd, ed) prices = ut.get_data([symbol], dates)[[symbol]] high = ut.get_data([symbol], dates, colname='High')[[symbol]] low = ut.get_data([symbol], dates, colname='Low')[[symbol]] orig_close = ut.get_data([symbol], dates, colname='Close')[[symbol]] adj_high = high * prices[[symbol]] / orig_close adj_low = low * prices[[symbol]] / orig_close sma_range = indicators.sma(prices[[symbol]], 10).iloc[:, 0] sma_bins = pd.qcut(sma_range, 10, labels=False) bb_range = indicators.bb(prices[[symbol]]) bb_range['value'] = bb_range.High - bb_range.Low bb_range.fillna(method='bfill', inplace=True) bb_range = bb_range['value'] bb_bins = pd.qcut(bb_range, 10, labels=False) comparisons = [ adj_high[symbol] - adj_low[symbol], abs(adj_low[symbol] - prices[symbol].shift(1)), abs(adj_high[symbol] - prices[symbol].shift(1)) ] tr = pd.concat(comparisons, axis=1).max(axis=1) tr.fillna(method='bfill', inplace=True) atr_range = tr.rolling(14, min_periods=1).mean() atr_bins = pd.qcut(atr_range, 10, labels=False) states = sma_bins * 100 + bb_bins * 10 + atr_bins states = atr_bins * 100 + bb_bins * 10 + sma_bins #states = pd.qcut(sma_range, 1000, labels=False) # for experiment 1 to compare with manual strategy trades = prices.copy() pre_position = 0 for date, row in trades.iterrows(): cur_state = states[date] # compute current state action = self.learner.querysetstate(cur_state) if action == 0: trades.loc[date, symbol] = -1000 - pre_position pre_position = -1000 elif action == 1: trades.loc[date, symbol] = 0 - pre_position pre_position = 0 elif action == 2: trades.loc[date, symbol] = 1000 - pre_position pre_position = 1000 # here we build a fake set of trades # your code should return the same sort of data # dates = pd.date_range(sd, ed) # prices_all = ut.get_data([symbol], dates) # automatically adds SPY # trades = prices_all[[symbol,]] # only portfolio symbols # trades_SPY = prices_all['SPY'] # only SPY, for comparison later # trades.values[:,:] = 0 # set them all to nothing # trades.values[0,:] = 1000 # add a BUY at the start # trades.values[40,:] = -1000 # add a SELL # trades.values[41,:] = 1000 # add a BUY # trades.values[60,:] = -2000 # go short from long # trades.values[61,:] = 2000 # go long from short # trades.values[-1,:] = -1000 #exit on the last day if self.verbose: print(type(trades)) # it better be a DataFrame! if self.verbose: print(trades) if self.verbose: print(prices_all) return trades def author(self): return 'hwang404'
def testPolicy(self, symbol="JPM", sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31), sv=100000): dates = pd.date_range(sd, ed) syms = [] syms.append(symbol) prices_SPY = get_data(syms, dates, addSPY=True, colname='Adj Close') prices_sym = prices_SPY[syms] init_trade = prices_sym.copy() init_trade[:] = 0 # benchmark - buy and hold 1000 shares init_trade.iloc[0, 0] = 1000 benchmark_portfolio = compute_portvals(init_trade, start_val=100000, commission=0.0, impact=0.0) # manual strategy man_trade = prices_sym.copy() man_trade[:] = 0 window = 14 lookback = 3 # I can look back at historical data before # the actual start date of the portfolio as # long as I only use that for technical analysis lookback_dates = pd.date_range(dates[0] - (window * 2), ed) prices_w_lookback = get_data(syms, lookback_dates, addSPY=True, colname='Adj Close')[syms] bbp = ind.bollinger_percentage(prices_w_lookback, window) sma = ind.sma(prices_w_lookback, window) momentum = ind.momentum(prices_w_lookback, lookback) # One DF for iterating indicators = pd.concat([bbp, sma, momentum], axis=1) indicators.columns = ['BBP', 'SMA', 'Momentum'] indicators = indicators.dropna() # Just drop any day where we have NAN man_trade = init_trade.copy() man_trade.iloc[:, :] = 0 man_trade.iloc[:, -1] = 0.0 # track long and short positions longPos = [] shortPos = [] position = 0 for i in range(indicators.shape[0] - 1): # dropna removes some dates from indicators, can't rely on index date = indicators.iloc[i].name.strftime('%Y-%m-%d') if (indicators.iloc[i]['BBP'] < .03) and (indicators.iloc[i]['Momentum'] > -0.2) and (indicators.iloc[i]['SMA'] < .97): #BUY if position != 1000: man_trade.loc[date][syms] = 1000 - position position = 1000 longPos.append(date) elif (indicators.iloc[i]['BBP'] > .97) and (indicators.iloc[i]['Momentum'] < 0.2) and (indicators.iloc[i]['SMA'] > 1.03): #SELL if position != -1000: man_trade.loc[date][syms] = -1000 - position position = -1000 shortPos.append(date) man_portfolio = compute_portvals(man_trade, start_val=100000, commission=self.commission, impact=self.impact) # Strategy vs Benchmark fig = plt.figure() plt.title('Manual Strategy') x = benchmark_portfolio.index.values # dates y = benchmark_portfolio.values y = y / y[0] # normalize plt.plot(x, y, color='green', label='Benchmark') x2 = man_portfolio.index.values y2 = man_portfolio.values y2 = y2 / y2[0] plt.plot(x2, y2, color='red', label='Manual Strategy') plt.tight_layout() plt.legend() plt.savefig('MS_' + str(sd.year) + '.png') # Entry points plt.clf() fig = plt.figure plt.title('Entry Points') x = prices_sym.index.values y = prices_sym.values / prices_sym.values[0] plt.plot(x, y, color='orange', label='Prices') # plot longs for l in longPos: y = prices_sym.loc[l][0] / prices_sym.iloc[0, 0] plt.plot([l, l], [y + .1, y - .1], color='blue') for s in shortPos: y = prices_sym.loc[s][0] / prices_sym.iloc[0, 0] plt.plot([s, s], [y + .1, y - .1], color='black') plt.grid() # custom legend entries for long and short ax = plt.gca() handles, labels = ax.get_legend_handles_labels() long_line = mlines.Line2D([], [], color='blue', label='Long') short_line = mlines.Line2D([], [], color='black', label='Short') handles.append(long_line) handles.append(short_line) plt.legend(handles=handles) plt.tight_layout() plt.savefig('entrypoints_MS_' + str(sd.year) + '.png') # Stats daily_returns_bench = benchmark_portfolio / benchmark_portfolio.shift( 1) - 1 c_return_bench = benchmark_portfolio.iloc[ -1] / benchmark_portfolio.iloc[0] - 1 stdev_daily_bench = daily_returns_bench.std() mean_daily_bench = daily_returns_bench.mean() daily_returns_opt = man_portfolio / man_portfolio.shift(1) - 1 c_return_opt = man_portfolio.iloc[-1] / man_portfolio.iloc[0] - 1 stdev_daily_opt = daily_returns_opt.std() mean_daily_opt = daily_returns_opt.mean() print('Benchmark Stats') print('Cumulative Return: ' + str(c_return_bench)) print('StDev Daily: ' + str(stdev_daily_bench)) print('Mean Daily: ' + str(mean_daily_bench)) print('Manual Stats') print('Cumulative Return: ' + str(c_return_opt)) print('StDev Daily: ' + str(stdev_daily_opt)) print('Mean Daily: ' + str(mean_daily_opt))
def addEvidence(self, symbol = "IBM", \ sd=dt.datetime(2008,1,1), \ ed=dt.datetime(2009,1,1), \ sv = 10000): # add your code to do learning here # example usage of the old backward compatible util function syms = [symbol] dates = pd.date_range(sd, ed) prices_all = ut.get_data(syms, dates) # automatically adds SPY prices = prices_all[syms] # only portfolio symbols prices_SPY = prices_all['SPY'] # only SPY, for comparison later #if self.verbose: print prices #print prices # example use with new colname volume_all = ut.get_data(syms, dates, colname="Volume") # automatically adds SPY volume = volume_all[syms] # only portfolio symbols volume_SPY = volume_all['SPY'] # only SPY, for comparison later if self.verbose: print volume #print volume S = sma(prices, 20) upper, lower, bb, r_m, r_std = bollinger(prices) M = momentum(prices) SMA = pd.DataFrame({'SMA': S}) bb_val = pd.DataFrame({'Bollinger': bb}) Upper = pd.DataFrame({'Upper': upper}) Lower = pd.DataFrame({'Lower': lower}) Momentum = pd.DataFrame({'Momentum': M}) R_M = pd.DataFrame({'Rolling Mean': r_m}) R_STD = pd.DataFrame({"Rolling STD": r_std}) ind = pd.concat((SMA, bb_val, Upper, Lower, R_M, R_STD, Momentum), axis=1) ind.fillna(0, inplace=True) ind = ind[:-self.Days] x_train = ind.values ''' for i in range(0,len(prices)-self.Days): if i<20: x_train[i][0] = 0 x_train[i][1] = 0 x_train[i][2] = 0 x_train[i][3] = prices.iloc[i] x_train[i][4] = prices.iloc[i + self.Days] else: x_train[i][0] = SMA.iloc[i] x_train[i][1] = bb_val.iloc[i] x_train[i][2] = Momentum.iloc[i] x_train[i][3]=prices.iloc[i] x_train[i][4]=prices.iloc[i+self.Days] ''' #print x_train y_temp = [] for i in range(0, len(prices) - self.Days): if prices.ix[i + self.Days, symbol] / prices.ix[i, symbol] > 1.008 + self.impact: y_temp.append(1) elif prices.ix[i + self.Days, symbol] / prices.ix[ i, symbol] < 0.992 - self.impact: y_temp.append(-1) else: y_temp.append(0) y_train = np.array(y_temp) self.learner.addEvidence(x_train, y_train)