def process(self, symbol="AAPL", sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31)): dates = pd.date_range(sd, ed) prices_all = get_data([symbol], dates) indi = Indicators() indi.get_indicators(prices_all, self.indicator_window) pd.concat([ indi.momentum.iloc[:, 1], indi.smap.iloc[:, 1], indi.bbp.iloc[:, 1] ], axis=1) prices_norm = prices_all / prices_all.iloc[0] on_coming_returns = prices_norm.iloc[:, 1].pct_change( periods=self.return_window).shift(-self.return_window).dropna( axis=0) on_coming_returns[on_coming_returns > self.order_threshold] = 1 on_coming_returns[on_coming_returns < -self.order_threshold] = -1 on_coming_returns[on_coming_returns.abs() <> 1] = 0 data = pd.concat([ indi.momentum.iloc[:, 1], indi.smap.iloc[:, 1], indi.bbp.iloc[:, 1], on_coming_returns ], axis=1).dropna(axis=0) data.columns = ['MOMENTUM', 'SMAP', 'BBP', 'ORDER'] x = data.loc[:, ['MOMENTUM', 'SMAP', 'BBP']].values y = data.loc[:, ['ORDER']].values return data, x, y
def gen_manual_trades(self): indicators = Indicators(symbols = self.symbol, sd=self.sd, ed=self.ed) indicators.gen_all_indicators() momentum, sma, bollinger_minus, bollinger_plus = indicators.get_all_inidcators() # EXECUTE MANUAL STRATEGY cols = ["Symbol", "Order", "Shares"] trades = np.zeros(shape = (self.data.shape[0],3)) trades = pd.DataFrame(trades, index = self.data.index.values, columns = cols) holdings = 0 # initial holdsing value: momentum_cutoff = 0.075 for i in range(self.data.shape[0]): # if it's the first day, buy because the general trend of the economy is up: if i == 0 and holdings < 1000: to_buy = 1000 - holdings trades.ix[i] = (self.symbol, "BUY", to_buy) holdings = holdings + to_buy # first, buy/sell based on bollinger bands: # if price is below lower bollinger band, buy: elif bollinger_minus.ix[i] > self.data.ix[i].values[0] and holdings < 1000: to_buy = 1000 - holdings trades.ix[i] = (self.symbol, "BUY", to_buy) holdings = holdings + to_buy # elif price is above upper bollinger band, sell: elif bollinger_plus.ix[i] < self.data.ix[i].values[0] and holdings > -1000: to_sell = 1000 + holdings trades.ix[i] = (self.symbol, "SELL", to_sell) holdings = holdings - to_sell # if momentum slope is above a value, buy because we expect it to go up: elif self.get_momentum_slope(momentum, i) > momentum_cutoff and holdings < 1000: to_buy = 1000 - holdings trades.ix[i] = (self.symbol, "BUY", to_buy) holdings = holdings + to_buy # else if momentum slope is below a value, sell because we expect price to then go down: elif self.get_momentum_slope(momentum, i) < -momentum_cutoff and holdings > -1000: to_sell = 1000 + holdings trades.ix[i] = (self.symbol, "SELL", to_sell) holdings = holdings - to_sell # if sma is larger than the price, buy: elif self.sma_is_consistently_higher(sma, i) and holdings < 1000: to_buy = 1000 - holdings trades.ix[i] = (self.symbol, "BUY", to_buy) holdings = holdings + to_buy # elif sma is lower than price, sell: elif self.sma_is_consistently_lower(sma, i) and holdings > -1000: to_sell = 1000 + holdings trades.ix[i] = (self.symbol, "SELL", to_sell) holdings = holdings - to_sell trades["Symbol"] = self.symbol return trades
def get_indicators(self, prices): calc_indicators = Indicators(self.syms, self.sd, self.ed) calc_indicators.gen_all_indicators() momentum, sma, low_bollinger, high_bollinger = calc_indicators.get_normed_indicators( ) df = pd.DataFrame(index=prices.index) df['Momentum'] = momentum df['SMA'] = sma df['Bollinger Low'] = low_bollinger df['Bollinger High'] = high_bollinger return df
def masub(market): ind = Indicators() binl = binance.fetch_ohlcv(market, timeframe='1h', since=None, limit=None, params={}) closes = list(map(lambda binl: binl[-2], binl)) ind = Indicators() maslow = ind.movingAverage(closes, MA_SLOW_PERIOD) mafast = ind.movingAverage(closes, MA_FAST_PERIOD) masub = (mafast / maslow) - 1 return masub
def make_example_report(fdc_round, category, nb_files_on=True, nb_labels_on=True, nb_uploaders_on=True, pct_labels_on=True, nb_usages_on=False, pixel_count_on=False): """Quick report maker. Indicators can be disabled by passing argument False""" # Quick and dirty metrics object try: db = commons_cat_metrics.get_commons_db() db_cursor = db.cursor() # Metrics metrics = Indicators( category, fdc_round, cursor=db_cursor) # Init indicators with None so they can be enabled/disabled by option nb_files = None nb_labels = None nb_uploaders = None pct_labels = None nb_usages = None pixel_count = None template_photo = template_photo_start # Retrieving all indicators if nb_files_on: nb_files = metrics.nb_files_indicator("nb") template_photo += nb_files_tmpl if nb_labels_on: nb_labels = metrics.nb_labels_indicator("nb_featured") template_photo += nb_labels_tmpl if nb_uploaders_on: nb_uploaders = metrics.nb_uploaders_indicator("uploaders") template_photo += nb_uploaders_tmpl if pct_labels_on: pct_labels = metrics.pct_labels_indicator("featured") template_photo += pct_labels_tmpl if nb_usages_on: nb_usages = metrics.total_usage_indicator("usages") template_photo += nb_usages_tmpl if pixel_count_on: pixel_count = metrics.pixel_count_indicator("pixels") template_photo += pixel_count_tmpl template_photo += template_photo_end # List of indicators selected list_of_indicators = [indicator for indicator in [ nb_files, pct_labels, nb_uploaders, nb_labels, nb_usages, pixel_count] if indicator is not None] report = Report(list_of_indicators, template_string=template_photo) fdc_report = report.generate() # Ending mysql db_cursor.close() db.close() return fdc_report except _mysql_exceptions.OperationalError: raise WMmetricsException("Problem with database connection")
def __init__(self, scope, q, alpha, reward, discount, quotes, bankroll, log=None): self.logger = log self.actions = ACTIONS # BUY, SELL, DO_NOTHING Indicators.__init__(self, log) Learning.__init__(self, q, alpha, reward, discount, self.state, \ self.actions) Order.__init__(self, scope, bankroll, log) self.num_trades = 0 self.performance = 1 self.volume = max(self.performance, 1) self.logger = log self.status = {'status':'','action':''} self.quotes = quotes self.states = None
def main(): oanda = Broker(API_KEY, ACCOUNT_ID) position_size = 2000 pairs = ["EUR_USD", "GBP_USD", "USD_CHF", "AUD_USD", "USD_CAD"] upward_sma_dir = {x: False for x in pairs} downward_sma_dir = {x: False for x in pairs} print("trying") open_trades = oanda.get_open_trades() curr_ls = [] for i in range(len(open_trades)): curr_ls.append(open_trades[i]['instrument']) currencies = [i for i in pairs if i not in curr_ls] # Look to see if it's a good time to buy a new pair for currency in currencies: data = oanda.get_candles(currency) technicals = Indicators(data) ohlc_df = technicals.stochastic(data) ohlc_df = technicals.SMA(ohlc_df) signal = oanda.trade_signal( ohlc_df, currency, upward_sma_dir, downward_sma_dir) if signal == "Buy": oanda.make_order(currency, position_size, 3*technicals.ATR(ohlc_df)) print("New long position initiated for ", currency) # Look to see if it's a good time to sell a pair: for currency in curr_ls: data = oanda.get_candles(currency) technicals = Indicators(data) ohlc_df = technicals.stochastic(data) ohlc_df = technicals.SMA(ohlc_df) signal = oanda.trade_signal( ohlc_df, currency, upward_sma_dir, downward_sma_dir) if signal == "Sell": oanda.make_order(currency, -1*position_size, 3*technicals.ATR(ohlc_df)) print("New short position initiated for ", currency)
def chartEMA(self, n, color='red'): date = toDateTime(Data.getDates(self,self.interval,self.unit)) closep = Data.getCloses(self,self.interval,self.unit) ema = Indicators.ema(self,closep,n) self.p.line(date, ema, color=color)
def build(self, df, **kwargs): overlays = Overlays(df, **kwargs).get() if kwargs.get( 'overlays', True) else [] indicators = Indicators(df, **kwargs).get() if kwargs.get( 'indicators', True) else [] return self.change( df, **kwargs).join(overlays + indicators) if not kwargs.get( 'include_historicals', True) else df.join(overlays + indicators)
def __init__(self, lookback, eigenvector, pseudoLive=True): #pseudoLive is where I run the 'live' algorithm on historical data self.lookback = lookback self.eigenvector = eigenvector self.priceAr = [] self.pnl = 0 self.pnlCumSum = [] self.returnsCumSum = [] self.returns = 0 self.marketValue = [] self.positions = [] #self.indicators.priceAr = [[ts1, ts2, ... ], [ts1, ts2, ...] ... ] self.indicators = Indicators(lookback) self.openTradesAr = [] self.balance = 0
def chartSMA(self, n, color='blue'): date = toDateTime(Data.getDates(self,self.interval,self.unit)) closep = Data.getCloses(self,self.interval,self.unit) sma = Indicators.sma(self,closep,n) self.p.line(date, sma, color=color)
def __init__(self, pin, player, latching=False, dir=None): self.pin = pin self.player = player GPIO.setup(pin, GPIO.IN) # enumerate this instance TardisButton.__number += 1 self.__name = str(TardisButton.__number) # Grab a light self.light = Indicators() self.light.on() # which file to play next self.__next = 0 # Where do we find our data files? if dir: self.__dir = dir else: dir = os.path.dirname(os.path.abspath( inspect.getfile(inspect.currentframe()))) self.__dir = os.path.join(dir, 'Sounds', self.__name) # Create directory if it doesn't exist try: subprocess.call(['mkdir', '-p', self.__dir]) except: pass # Set Permissions try: subprocess.call(['chown', '-R', 'pi.pi', self.__dir, '..', '..', 'Sounds']) except: pass # Scan for data files self._getFiles() # are we active self.enable() # Add a callback if latching: type = GPIO.BOTH else: type = GPIO.RISING GPIO.add_event_detect(pin, type, callback=self.__event) # which track are we playing self.playing = -1 # Switch off our light self.light.off()
def testPolicy(symbol='JPM', sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31)): dates = pd.date_range(sd, ed) prices = get_data([symbol], dates) prices_norm = prices / prices.iloc[0] indi = Indicators() indi.get_indicators(prices, 21) momentum = indi.momentum smap = indi.smap bbp = indi.bbp upper_limit = 1000 lower_limit = -1000 prices['Holding'] = 0 prices['Trade'] = 0 for i in range(30, prices.shape[0]): # if smap.iloc[i, 1] < -0.05 and bbp.iloc[i, 1] < 0: if momentum.iloc[ i, 1] < 0 or smap.iloc[i, 1] < -0.05 and bbp.iloc[i, 1] < 0: prices.iloc[i, 3] = upper_limit - prices.iloc[i - 1, 2] elif momentum.iloc[i, 1] > 0 and smap.iloc[i, 1] > 0.05 and bbp.iloc[ i, 1] > 1: # elif smap.iloc[i, 1] > 0.05 and bbp.iloc[i, 1] > 1: prices.iloc[i, 3] = lower_limit - prices.iloc[i - 1, 2] # prices.iloc[i, 2] = prices.iloc[i - 1, 2] + prices.iloc[i, 3] prices.iloc[i, 2] = prices.iloc[i - 1, 2] + prices.iloc[i, 3] price_order = prices.loc[prices.iloc[:, 3] != 0] price_order['Order'] = '' price_order.loc[price_order['Trade'] > 0, 'Order'] = 'BUY' price_order.loc[price_order['Trade'] < 0, 'Order'] = 'SELL' price_order['Shares'] = price_order.loc[:, 'Trade'].abs() price_order['Symbol'] = symbol price_order.reset_index(inplace=True) price_order = price_order.iloc[:, [0, 7, 5, 6]] price_order.columns = ['Date', 'Symbol', 'Order', 'Shares'] return price_order
def plot_macd_histogram(self, plot, macd_data, dates=None): close = [f['close'] for f in macd_data] xs = [x for x in range(len(close))] i = Indicators() ema_slow, ema_fast, macd = i.moving_average_convergence(close, nslow=26, nfast=12) sig_line = i.exp_moving_average(macd, 9) if dates: self.axis_list[plot].plot(dates, macd) self.axis_list[plot].plot(dates, sig_line) self.axis_list[plot].plot(dates, macd - sig_line, 'k') self.axis_list[plot].axhline(y=0, color='b', linestyle='-') self.axis_list[plot].fill_between(dates, macd - sig_line, 0, alpha=.5, facecolor='#00ffe8', edgecolor='#00ffe8') self.axis_list[plot].spines['bottom'].set_color('#5998ff') self.axis_list[plot].spines['top'].set_color('#5998ff') self.axis_list[plot].spines['left'].set_color('#5998ff') self.axis_list[plot].spines['right'].set_color('#5998ff') else: # self.axis_list[plot].plot(macd) # self.axis_list[plot].plot(sig_line) self.axis_list[plot].plot(macd - sig_line, color='k') self.axis_list[plot].axhline(y=0, color='b', linestyle='-') self.axis_list[plot].fill_between(xs, macd - sig_line, 0, alpha=.5, facecolor='#00ffe8', edgecolor='#00ffe8') self.axis_list[plot].spines['bottom'].set_color('#5998ff') self.axis_list[plot].spines['top'].set_color('#5998ff') self.axis_list[plot].spines['left'].set_color('#5998ff') self.axis_list[plot].spines['right'].set_color('#5998ff')
def testPolicy(self, symbol="JPM", sd=dt.datetime(2008,1,1), ed=dt.datetime(2009,12,31), sv=100000): self.getPrices(sd,ed, [symbol]) dateRange = pd.date_range(sd, ed) indicators = Indicators(self.prices) self.rollingMean, self.largerSMA = indicators.computeRollingMean(plot=False) self.lowerBB, self.upperBB, self.bollingerIndex = indicators.computeBollinger(plot=False) self.cci = indicators.computeCCI(plot=False) self.MACD, self.ema9MACD = indicators.computeMACD(plot=False) self.df_trades = pd.DataFrame(index=self.prices.index) self.df_trades[symbol] = 0.0 self.df_trades['current'] = 0.0 for i in range(20, len(self.df_trades)): self.computeTrade(i, symbol) self.benchmarkTrades = pd.DataFrame(index=self.prices.index) self.benchmarkTrades[symbol] = 0.0 self.benchmarkTrades[symbol].ix[0] = 1000.0 df_trades = self.df_trades.drop('current',axis=1) self.portVals = compute_portvals(df_trades, start_val = sv, commission= 0.00, impact=0.0) self.portVals_bench = compute_portvals(self.benchmarkTrades, start_val = sv, commission= 9.95, impact=0.005) self.portVals = self.portVals/self.portVals.ix[0] self.portVals_bench = self.portVals_bench/self.portVals_bench.ix[0] self.plot(symbol) self.computeMetrics()
def shutdown(channel): global SHUTDOWN_IN_PROGRESS global m if SHUTDOWN_IN_PROGRESS: return SHUTDOWN_IN_PROGRESS = True # Kill the music and set RGB panels to red m.stop() m.redAlert() # Turn off indicators (since they won't go off later) Indicators.allOff() # Turn on all 10mm LEDs w.on() r.on() g.on() b.on() subprocess.call(["/sbin/shutdown", "-h", "now"])
def indicators(self, ticker): if self.exchange == 'poloniex': directory = self.directory + 'Data/Raw_data/' + self.exchange + '/5m/' + tickDir( ticker) + '.pickle' data = dePickler(directory) else: data = dePickler(self.directory + 'Data/Raw_data/' + self.exchange + '/1d/' + ticker + '.pickle') indicator_data = Indicators(data) for count, close in enumerate(data['Close']): indicator_data.tick(close) percentages = pd.Series(indicator_data.percentChangelist) SMA = pd.Series(indicator_data.SMAlist) EMAslow = pd.Series(indicator_data.EMAslow) EMAfast = pd.Series(indicator_data.EMAfast) MACD = pd.Series(indicator_data.MACD) Signal = pd.Series(indicator_data.signal) smaDiff = pd.Series(indicator_data.smaDiff) data['PercentChange'] = percentages.values data['SMA'] = SMA.values data['EMAslow'] = EMAslow.values data['EMAfast'] = EMAfast.values data['MACD'] = MACD.values data['Signal'] = Signal.values data['SmaDiff'] = smaDiff.values if self.exchange == 'poloniex': directory = self.directory + 'Data/Raw_data/' + self.exchange + '/5m/' + tickDir( ticker) + '.pickle' pickler(directory, data) else: pickler( self.directory + 'Data/Raw_data/' + self.exchange + '/1d/' + ticker + '.pickle', data) return data
def __init__(self, scope, q, alpha, reward, discount, quotes, bankroll, log=None): self.logger = log self.scope = scope self.actions = ACTIONS Indicators.__init__(self, log) Order.__init__(self, scope, bankroll, log) Learning.__init__(self, q, alpha, reward, discount, self.state, \ self.actions) self.num_trades = 0 self.performance = 1 self.volume = max(self.performance, 1) self.logger = log self.status = {'status': 'idle', 'action': ''} self.quotes = quotes self.states = None
def chartSMA(self,bars): chartData = self.readChartData(3,'d') dateconv = np.vectorize(dt.datetime.fromtimestamp) closep = chartData['close'] sma = Indicators.sma(self,closep,bars) date = mdates.date2num(dateconv(chartData['date'])) self.ax.plot(date,sma) plt.show()
def __init__(self, length, numsimul): self.prices = [] self.btcPrices = [] self.trades = [] self.indicators = Indicators() self.length = length self.USDpertrade = 100 #binary lists for graphing results self.buylist = [] self.selllist = [] #profit init self.coinVolume = 0 self.print = False self.profit = 0 self.balance = 0 self.balanceList = [] self.numSimul = numsimul self.maxDiff = 0 self.numtrades=0 #moving average init self.MAlong = [] self.MAshort = [] #MACD init self.EMAfast = [] self.EMAslow = [] self.previousEMAfast = None self.currentEMAfast = None self.previousEMAslow = None self.currentEMAslow = None self.previousEMAmacd = None self.currentEMAmacd = None self.MACD = [] self.signal = []
import sys from indicators import Indicators action = sys.argv[1] availbleActions = [ "error", "welcome", "isWaiting", "isDownloading", "isPaired", "needToPair", "needToLogin", "uploadSuccessfully", "buttonPress", "buttonPressOffline", "done" ] if (action in availbleActions): getattr(Indicators(), action)()
def make_graph_year(self, stock): self.current_view = 'Year' print('Current view year') i = Indicators() ema_slow, ema_fast, macd = i.moving_average_convergence( stock.get_closes(), nslow=26, nfast=12) sig_line = i.exp_moving_average(macd, 9) rsi = i.relative_strength(stock.get_closes()) sma_window = 9 ema_window = 9 my_sma = i.simple_moving_average(stock.get_closes(), sma_window) my_ema = i.exp_moving_average(stock.get_closes(), ema_window) dates = stock.get_dates_as_formatted(fmt='3') for x in range(len(dates)): dates[x] = x # self.axis_list[3].plot(dates, macd) # self.axis_list[3].plot(dates, sig_line) # self.axis_list[3].plot(dates, macd - sig_line, 'k') # self.axis_list[3].axhline(y=0, color='b', linestyle='-') # self.axis_list[3].fill_between(dates, macd - sig_line, 0, alpha=.5, facecolor='#00ffe8', edgecolor='#00ffe8') # self.axis_list[3].spines['bottom'].set_color('#5998ff') # self.axis_list[3].spines['top'].set_color('#5998ff') # self.axis_list[3].spines['left'].set_color('#5998ff') # self.axis_list[3].spines['right'].set_color('#5998ff') ohlc = stock.get_candle_stick_data(fmt='np') for x in range(len(ohlc)): ohlc[x][0] = x candlestick_ohlc(self.axis_list[2], ohlc, colorup='green', colordown='red', width=.6) # self.axis_list[2].plot(dates[sma_window - 1:], my_sma, label='SMA') # self.axis_list[2].plot(dates, my_ema, label='EMA') self.axis_list[2].set_ylabel('Price') self.axis_list[2].legend(loc='upper right') self.__plot.suptitle(stock.get_symbol()) # self.axis_list[1].plot(dates, rsi) # self.axis_list[1].xaxis.set_major_locator(mticker.MaxNLocator(10)) # self.axis_list[1].get_xaxis().set_visible(False) # self.axis_list[2].get_xaxis().set_visible(False) self.axis_list[3].xaxis.set_major_locator(mticker.MaxNLocator(10)) # md_dates = [datetime.datetime.strftime(mdates.num2date(i), '%Y-%m-%d') for i in dates] def my_date(x, pos): try: return md_dates[int(x)] except IndexError: return '' # self.axis_list[3].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) for lab in self.axis_list[3].xaxis.get_ticklabels(): lab.set_rotation(30) return self.__plot
def make_graph_rt(self, stock): self.current_view = 'RT' print('Current view real-time') i = Indicators() close = stock.get_rt_closes() ema_slow, ema_fast, macd = i.moving_average_convergence(close, nslow=26, nfast=12) sig_line = i.exp_moving_average(macd, 9) rsi = i.relative_strength(close) sma_window = 10 ema_window = 10 my_sma = i.simple_moving_average(close, sma_window) my_ema = i.exp_moving_average(close, ema_window) dates = stock.get_dates_as_formatted(fmt='3', rt=True) ohlc = stock.get_rt_candle_stick_data(fmt='np') for i in range(len(dates)): ohlc[i][0] = dates[i] for x in range(len(ohlc)): ohlc[x][0] = x print('OHLC RT is: %s' % ohlc) # self.axis_list[3].plot(dates, macd) # self.axis_list[3].plot(dates, sig_line) # self.axis_list[3].plot(dates, macd - sig_line, 'k') # self.axis_list[3].axhline(y=0, color='b', linestyle='-') # self.axis_list[3].fill_between(dates, macd - sig_line, 0, alpha=.5, facecolor='#00ffe8', edgecolor='#00ffe8') # self.axis_list[3].spines['bottom'].set_color('#5998ff') # self.axis_list[3].spines['top'].set_color('#5998ff') # self.axis_list[3].spines['left'].set_color('#5998ff') # self.axis_list[3].spines['right'].set_color('#5998ff') candlestick_ohlc(self.axis_list[2], ohlc, width=(.001 / 2), colorup='green', colordown='red') # self.axis_list[2].plot(dates[sma_window - 1:], my_sma, label='SMA') # self.axis_list[2].plot(dates, my_ema, label='EMA') self.axis_list[2].set_ylabel('Price') self.axis_list[2].legend(loc='upper right') self.__plot.suptitle(stock.get_symbol()) # self.axis_list[1].plot(dates, rsi) # self.axis_list[1].xaxis.set_major_locator(mticker.MaxNLocator(10)) # self.axis_list[1].get_xaxis().set_visible(False) # self.axis_list[2].get_xaxis().set_visible(False) # # self.axis_list[3].xaxis.set_major_locator(mticker.MaxNLocator(10)) # self.axis_list[3].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # # for lab in self.axis_list[3].xaxis.get_ticklabels(): # lab.set_rotation(30) return self.__plot
from _datetime import datetime, timedelta import threading from tkinter import * from indicators import Indicators from bot import HBot # INSTANCES OF BOT AND INDICATORS cbot = HBot() indicator = Indicators() def main_flow(): cbot.start_application() print('iniciou') # WORKING WITH CURRENT CONTACTS LIST # EACH LINE REFERS TO A DIFFERENT CONTACT # EACH COLUMN REFERS TO A SPECIFIC INFORMATION OF THIS CONTACT # [0 = CONTACT NAME (retrieved from top of whatsapp page), # 1 = STATUS, # 2 = LAST INTERACTION DATE, # 3 = LAST WRITTEN TEXT, # 4= ADDITIONAL INFORMATION (rating/ticket/ok/x), # 5= IS FINAL (0 = no, 1= final with rating, 2= final with no help), # 6= CONVERSATION ID (retrieved from database)] contacts_list = [] # MAIN LOOP, ALWAYS LOOKING FOR UNREAD CONVERSATIONS while True:
import pandas as pd import numpy as np import re # Data was retrieved from https://data.oecd.org/hha/household-debt.htm#indicator-chart from indicators import Indicators from numpy import diff consumer_conf_data_eu = pd.read_csv('eu_consumer_conf_2000_2020.csv') print(consumer_conf_data_eu.head()) object = Indicators() object.consumer_confidence(data=consumer_conf_data_eu)
import pandas import plotly.graph_objects as go from indicators import Indicators dataframes = {} # df = pandas.read_csv('1h.csv') candels_h1=Indicators.get_candels('1h.txt') candels_h6=Indicators.candels_change(candels_h1,6) df=pandas.DataFrame(candels_h6) df['20sma'] = df['close'].rolling(window=20).mean() df['stddev'] = df['close'].rolling(window=20).std() df['lower_band'] = df['20sma'] - (1.5 * df['stddev']) df['upper_band'] = df['20sma'] + (1.5 * df['stddev']) df['TR'] = df['high'] - df['low'] df['ATR'] = df['TR'].rolling(window=20).mean() df['lower_keltner'] = df['20sma'] - (df['ATR'] * 1.5) df['upper_keltner'] = df['20sma'] + (df['ATR'] * 1.5) def in_squeeze(df): return df['lower_band'] > df['lower_keltner'] and df['upper_band'] < df['upper_keltner'] df['squeeze_on'] = df.apply(in_squeeze, axis=1)
class Strategy(object): def __init__(self, length, numsimul): self.prices = [] self.btcPrices = [] self.trades = [] self.indicators = Indicators() self.length = length self.USDpertrade = 100 #binary lists for graphing results self.buylist = [] self.selllist = [] #profit init self.coinVolume = 0 self.print = False self.profit = 0 self.balance = 0 self.balanceList = [] self.numSimul = numsimul self.maxDiff = 0 self.numtrades=0 #moving average init self.MAlong = [] self.MAshort = [] #MACD init self.EMAfast = [] self.EMAslow = [] self.previousEMAfast = None self.currentEMAfast = None self.previousEMAslow = None self.currentEMAslow = None self.previousEMAmacd = None self.currentEMAmacd = None self.MACD = [] self.signal = [] def tick(self, price, btcPrice=None, indicator = None): self.currentPrice = price self.currentBTC = btcPrice self.btcPrices.append(self.currentBTC) self.prices.append(self.currentPrice) def movingaverage(self, MAlong, MAshort, count): if self.currentBTC == None: self.coinVolume = 1 else: buy_volume = self.USDpertrade/self.currentBTC self.coinVolume = buy_volume/self.currentPrice self.coinVolume = 1 newOpenedTrades = 0 newClosedTrades = 0 openTrades = [] for trade in self.trades: if trade.status == 'OPEN': openTrades.append(trade) self.MAlong.append(self.indicators.SMA(self.prices,MAlong)) self.MAshort.append(self.indicators.SMA(self.prices,MAshort)) if self.MAlong[-1]==None: pass else: if self.print: print('Price:',self.currentPrice,'\tMAlong:',self.MAlong[-1], 'MAshort:',self.MAshort[-1]) if count > MAlong: if ((self.MAshort[-1])>self.MAlong[-1]): if len(openTrades)<self.numSimul: #need to embed the trade volume into the trade object, otherwise we sell more volume than be buy. self.trades.append(BotTrade(self.currentPrice,self.coinVolume, self.print)) newOpenedTrades+=1 self.balance -= self.coinVolume*self.trades[-1].entryPrice for trade in openTrades: if self.MAshort[-1]<self.MAlong[-1]:# or (self.data[count]/trade.entryPrice)>1.05 or (self.data[count]/trade.entryPrice)<0.95: newClosedTrades+=1 if count == self.length: trade.close(self.currentPrice) else: trade.close(self.currentPrice) self.profit+=trade.profit() self.balance+=trade.volume*trade.exitPrice self.balanceList.append(self.balance) if newClosedTrades>0: self.selllist.append(True) else: self.selllist.append(False) if newOpenedTrades>0: self.buylist.append(True) else: self.buylist.append(False) def macd(self, slow, fast, signal, count, lengthPrices): if self.currentBTC == None: self.coinVolume = self.USDpertrade/self.currentPrice else: buy_volume = self.USDpertrade/self.currentBTC self.coinVolume = buy_volume/self.currentPrice newOpenedTrades = 0 newClosedTrades = 0 openTrades = [] for trade in self.trades: if trade.status == 'OPEN': openTrades.append(trade) if len(self.prices)>slow: self.previousEMAslow = self.indicators.EMA(self.prices, slow, self.previousEMAslow) self.previousEMAfast = self.indicators.EMA(self.prices, fast, self.previousEMAfast) self.EMAfast.append(self.previousEMAfast) self.EMAslow.append(self.previousEMAslow) self.MACD.append(self.EMAfast[-1]-self.EMAslow[-1]) self.previousEMAmacd = self.indicators.EMA(self.MACD, signal, self.previousEMAmacd) self.signal.append(self.previousEMAmacd) if len(self.prices)>100: self.difference(self.signal[-1]-self.MACD[-1]) if (self.MACD[-1]>(self.signal[-1]+self.maxDiff/4)) and (self.MACD[-2]>self.signal[-2]): if len(openTrades)<self.numSimul: self.trades.append(BotTrade(self.currentPrice,self.coinVolume, self.print)) newOpenedTrades+=1 self.balance -= self.coinVolume*self.currentPrice self.numtrades+=1 for trade in openTrades: if ((self.MACD[-1]<self.signal[-1]) and (self.MACD[-2]>self.signal[-2])) or count == lengthPrices-1: trade.close(self.currentPrice) self.balance+=trade.volume*self.currentPrice self.profit+=trade.profit() newClosedTrades+=1 #graphing section self.balanceList.append(self.balance) if newClosedTrades>0: self.selllist.append(True) else: self.selllist.append(False) if newOpenedTrades>0: self.buylist.append(True) else: self.buylist.append(False) def difference(self, new): if self.maxDiff>abs(new): pass else: self.maxDiff = abs(new) def returnParam(self): ## return self.profit, self.balance return self.profit
Moving average cross strategy. """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from indicators import Indicators # import and clean data f = r'data/USD_CAD_H1_history.csv' df = pd.read_csv(f) df.drop("Unnamed: 0", axis=1, inplace=True) filename = f[5:-4] # add moving averages technical = Indicators() df['fast sma'] = technical.sma1(df['Close'], 7) df['slow sma'] = technical.sma1(df['Close'], 20) # graph the results df[['Close', 'fast sma', 'slow sma']].plot(figsize=(30, 20)).set_title("Moving Average Cross") plt.savefig('examples/max-%s.png' % filename) # set strategy df['Enter Short'] = (df['fast sma'].shift(1) < df['slow sma']) df['Enter Long'] = (df['fast sma'].shift(1) > df['slow sma']) df['Position'] = np.nan df.loc[df['Enter Short'], 'Position'] = -1 df.loc[df['Enter Long'], 'Position'] = 1 df['Position'].loc[0] = 0
if bool(re.match('[0-9]{4}-[0-9]{2}', end)) == False: print('Sorry, I did not quite catch that. Please try again') continue else: break while True: country = str(input('Please enter the country code: ')) if bool(re.match('[A-Z]{3}|[A-Z]{4}', country)) == False: print('Sorry, I did not quite catch that. Please try again') continue else: break # Return Information to User object = Indicators(country = country, begin = begin, end = end) try: object.consumer_confidence(data=consumer_conf_data_eu) print('\n') except IndexError: print('No consumer confidence data within the specified time window.') try: object.gdp(data = gdp_eu) print('\n') except IndexError: print('No gdp data within the specified time window.') try: object.household_debt(data = house_hold_debt_eu)
class TardisButton(object): __number = 0 def __init__(self, pin, player, latching=False, dir=None): self.pin = pin self.player = player GPIO.setup(pin, GPIO.IN) # enumerate this instance TardisButton.__number += 1 self.__name = str(TardisButton.__number) # Grab a light self.light = Indicators() self.light.on() # which file to play next self.__next = 0 # Where do we find our data files? if dir: self.__dir = dir else: dir = os.path.dirname(os.path.abspath( inspect.getfile(inspect.currentframe()))) self.__dir = os.path.join(dir, 'Sounds', self.__name) # Create directory if it doesn't exist try: subprocess.call(['mkdir', '-p', self.__dir]) except: pass # Set Permissions try: subprocess.call(['chown', '-R', 'pi.pi', self.__dir, '..', '..', 'Sounds']) except: pass # Scan for data files self._getFiles() # are we active self.enable() # Add a callback if latching: type = GPIO.BOTH else: type = GPIO.RISING GPIO.add_event_detect(pin, type, callback=self.__event) # which track are we playing self.playing = -1 # Switch off our light self.light.off() # Look for files def _getFiles(self): result = [] for pattern in PATTERNS: for f in glob(os.path.join(self.__dir, pattern)): result.append(f) self.__files = result self.__files.sort() def enable(self): self.__active = len(self.__files) > 0 def disable(self): self.__active = False def __event(self, channel): if self.playing < 0: self.player.stop() if self.playing >= 0: self.player.restart() else: self.playing = self.__next self.light.on() self.player.play( self.__name, self.__files[self.playing], self.__done) self.__next += 1 if self.__next == len(self.__files): self.__next = 0 def test(self): self.__event(self.pin) def __done(self): self.playing = -1 self.light.off() def fileEvent(self): if self.playing >= 0: self.player.stop() self.light.off() self.disable() time.sleep(0.1) self._getFiles() for i in range(3): self.light.on() time.sleep(0.01) self.light.off() time.sleep(0.05) self.__next = 0 self.playing = -1 self.enable()
class Live(object): def __init__(self, lookback, eigenvector, pseudoLive=True): #pseudoLive is where I run the 'live' algorithm on historical data self.lookback = lookback self.eigenvector = eigenvector self.priceAr = [] self.pnl = 0 self.pnlCumSum = [] self.returnsCumSum = [] self.returns = 0 self.marketValue = [] self.positions = [] #self.indicators.priceAr = [[ts1, ts2, ... ], [ts1, ts2, ...] ... ] self.indicators = Indicators(lookback) self.openTradesAr = [] self.balance = 0 def tick(self, priceList, count): print(self.portfolio) self.priceAr.append(priceList) if count > self.lookback: #calculate pnl from previous trade pnl = np.sum( multiply( self.positions[-1], divide(subtract(self.priceAr[-1], self.priceAr[-2]), self.priceAr[-2]))) self.pnlCumSum.append(self.pnlCumSum[-1] + pnl) if np.sum(np.abs(self.positions[-1])) == 0: value = 1 else: value = np.sum(np.abs(np.array(self.positions[-1]))) self.returnsCumSum.append(divide(float(pnl), value)) for i, trade in enumerate(self.openTradesAr): if trade[0] == 'BUY': self.balance += -priceList[0, i] * trade[2] * trade[3] elif trade[0] == 'SELL': self.balance += -priceList[0, i] * trade[2] * trade[3] self.openTrades = [] #find new parameters marketValue = self.eigenvector * transpose(priceList) self.marketValue.append(marketValue) self.indicators.tick(self.marketValue, count) numUnits = -(marketValue - self.indicators.movingAverage[-1] ) / self.indicators.movingStd[-1] positions = multiply(multiply(self.eigenvector, priceList), repmat(numUnits, 1, priceList.size)) openTrades = [] for i in range(size(positions)): if positions[0, i] > 0: openTrades.append([ 'BUY', priceList[0, i], self.eigenvector[i], numUnits[0, 0], positions[0, i] ]) else: openTrades.append([ 'SELL', priceList[0, i], self.eigenvector[i], numUnits[0, 0], positions[0, i] ]) self.balance += priceList[ 0, i] * self.eigenvector[i] * numUnits[0, 0] print(self.balance) self.openTradesAr.append(openTrades) self.positions.append(positions) else: marketValue = self.eigenvector * transpose(priceList) self.marketValue.append(marketValue) self.indicators.tick(self.marketValue, count) self.positions.append([0] * len(priceList)) self.pnlCumSum.append(0) self.returnsCumSum.append(float(0))
A momentum strategy using Bollinger Bands and a Stochastic Oscillator to generate singals. """ import numpy as np import pandas as pd from indicators import Indicators import matplotlib.pyplot as plt # import and clean data f = r'data/AUD_JPY_H1_history.csv' df = pd.read_csv(f) df.drop("Unnamed: 0", axis=1, inplace=True) filename = f[5:-4] # add the technical indicators to the dataframe technical = Indicators() df = technical.stoch(df, 14, 7) df = technical.bollBands(df, 10, 2) # graph the results fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(30, 20)) df[['Close', 'Rolling Mean', 'Bollinger High', 'Bollinger Low']].plot(ax=axes[0]).set_title("Close and Bollinger") df[['%K', '%D']].plot(ax=axes[1]).set_title("Stochastic") plt.savefig('examples/stoch-bands-%s.png' % filename) # add long/short signals to the dataframe df['Enter Short'] = ((df['%K'] < df['%D']) & (df['%K'].shift(1) > df['%D'].shift(1))) & ( df['%D'] > 80) & (df['Close'] < df['Rolling Mean']) df['Enter Long'] = ((df['%K'] > df['%D']) &
# make GTD new_trade.good_till_cancel(cancel_time=datetime.now() + timedelta(minutes=90)) # Change session new_trade.modify_session(session='am') # Add an Order leg new_trade.instrument(symbol='MSFT', quantity=2, asset_type='EQUITY') # Add a stop loss new_trade.add_stop_loss(stop_size=.10, percentage=False) # pprint.pprint(new_trade.order) indicator_client = Indicators(price_data_frame=stock_frame) indicator_client.rsi(period=14) indicator_client.sma(period=200) indicator_client.ema(period=50) indicator_client.set_indicator_signals(indicator='rsi', buy=40.0, sell=20.0, condition_buy=operator.ge, condition_sell=operator.le) trades_dict = { 'MSFT': {
def handler(): # df = pd.read_csv('results.csv') # plot_chart(df) # return previous_price = 0 transactionData = {} transactionData['raw'] = {} transactionData['sma'] = {} transactionData['sma']['low_period'] = 7 transactionData['sma']['high_period'] = 21 transactionData['sma']['low_previous'] = 0 transactionData['sma']['low_current'] = 0 transactionData['sma']['high_previous'] = 0 transactionData['sma']['high_current'] = 0 transactionData['last_price'] = 0 transactionData['previous_price'] = 0 mercado_repository = MercadoRepository("https://www.mercadobitcoin.net","api") indicators = Indicators() while(data_api_running): data = mercado_repository.get_ticker_cotation('BTC') transactionData['date'] = datetime.now().strftime("%d/%m/%Y %H:%M:%S") transactionData['raw'] = data.__dict__ transactionData['last_price'] = float(data.last) transactionData['previous_price'] = previous_price transactionData['sma']['low'] = 0 transactionData['sma']['high'] = 0 transactionData['percent_from_previous'] = 0 if previous_price > 0: transactionData['percent_from_previous'] = (( transactionData['last_price'] - transactionData['previous_price'] ) * 100) / transactionData['previous_price'] indicators.add_value_to_move_average_data( last=transactionData['last_price'], period=[transactionData['sma']['low_period'], transactionData['sma']['high_period']] ) transactionData['sma']['low_previous'], transactionData['sma']['low_current'] = indicators.calculate_simple_move_average('low') transactionData['sma']['high_previous'],transactionData['sma']['high_current'] = indicators.calculate_simple_move_average('high') transactionData['action_type'] = evaluate_buy_sell_action(transactionData) # last_action_type = '' json_data = json.dumps(transactionData) df = pd.json_normalize(json.loads(json_data), meta=['raw', 'sma']) file_path = 'results.csv' with open(file_path, 'a') as f: df.to_csv(f, mode='a', header=f.tell() == 0) #logging.info("Waiting 5 seconds for next request") previous_price = transactionData['last_price'] time.sleep(1)