def action2(stock_name, day=None, short_w=30, long_w=60, debug=False): # Initialize the `signals` DataFrame with the `signal` column if day is None: today = date.today() - timedelta(days=2) day = utils.getPreviousWeekDay(today) tomorrow = day + timedelta(days=1) appl = yf.Ticker(stock_name).history(period='1d', start=day, end=tomorrow, interval='1m') buy = 0.0 sel = 0.0 total_percent = 0.0 prev_s = 0.0 END_TIME = "15:00" for i in range(30, len(appl['Close'])): stock = appl[:i].copy() signals = getSignals(stock, short_w, long_w) stock = stochastic_oscillator_d(stock, 14) index = i - 1 s = signals['positions'][index] current_close = stock['Close'][index] current_time = stock.index[index].strftime("%H:%M") # stock_trend = 1.0 if stock['SOD'][index-1] < stock['SOD'][index] else -1.0 sod_value = stock['SOD'][index] sod_trend = (sod_value > 80 and s == -1.0) or (sod_value < 20 and s == 1.0) stock = relative_strength_index(stock, 14) rsi_value = stock['RSI'][index] rsi_trend = (rsi_value > 70 and s == -1.0) or (rsi_value < 30 and s == 1.0) # if stock_trend == s: if s != 0.0: if buy != 0.0: sel = current_close percent = getPercent( buy, sel) if prev_s == -1.0 else getPercent(sel, buy) total_percent += percent if debug: print("Selling" if prev_s == -1.0 else "Buying", sel, "BUY", buy, percent, index, current_time) if rsi_trend and sod_trend: if debug: print("BUYING" if s == -1.0 else "SELLING", s, current_close, index, current_time) if debug: print("STOCKA", stock['SOD'][index - 1], stock['SOD'][index]) if debug: print("RSI", rsi_value, s) buy = current_close prev_s = s if current_time > END_TIME and buy != 0.0: sel = current_close percent = getPercent(buy, sel) if prev_s == -1.0 else getPercent( sel, buy) total_percent += percent if debug: print("Selling LAST", sel, buy, percent, index, current_time) break return total_percent, 0.0
def main(): TICKERS_PATH = "/Users/ignacio/workspace/Projects/stockBuyer/data/tickers.json" with open(TICKERS_PATH) as json_file: data = json.load(json_file) stocks = [v for s in data for v in data[s]] #stocks = ['ETR', 'LKQ', 'KIM', 'ATO', 'MAC', 'EXC', 'DLTR', 'CNP', 'WDC', 'ADI', 'PEG', 'CBOE', 'CME', 'FE', 'PBCT', 'ZBH', 'PWR', 'ABBV', 'HD', 'ED', 'WCG', 'EXPD', 'DAL', 'KHC', 'ETFC', 'BAC', 'STI', 'BXP', 'ZION', 'NUE', 'DG', 'EVRG', 'NTRS', 'PPL', 'EMR', 'AAPL', 'BBT', 'MXIM', 'FL', 'SEE', 'SO'] #BEST short 30! # stocks = [ 'HES', 'CFG', 'HII', 'MTB', 'SEE', 'TXN', 'PNC', 'CL', 'PBCT', 'HP', 'ALL', 'RCL', 'PPL', 'ABBV', 'INCY', 'PG', 'VLO', 'STI', 'MCHP', 'APH', 'SCHW', 'NUE', 'AAPL', 'AON', 'ADBE', 'DAL', 'STZ', 'DG', 'NTRS', 'KIM', 'PFE', 'AMD', 'JCI', 'TEL', 'CMI', 'EXPD', 'HD', 'CBOE', 'KLAC', 'WCG', 'EMR' ] # stocks = ['BBY', 'WMT', 'COF', 'APTV', 'RMD', 'LNC', 'DFS', 'SPGI', 'TAP', 'OMC', 'XEL', 'TRIP', 'BBT', 'OKE', 'CCI', 'RJF', 'ICE', 'CNP', 'GOOG', 'NWSA', 'IFF', 'AME', 'JEC', 'XRAY', 'XLNX', 'EL', 'SLG', 'CAH', 'SCHW', 'ALB', 'LW', 'PKI', 'CMCSA', 'FCX', 'RE', 'FE', 'GPS', 'ADP', 'FISV', 'DUK'] short_range = [30] long_range = [60] results = {} days = [1] for day_num in days: today = date.today() - timedelta(days=day_num) day = utils.getPreviousWeekDay(today) print("DAY:", day) for sr in short_range: for lr in long_range: percent = 0 max_percent = 0 wrong_stocks = 0 negative_stocks = [] positive_stocks = [] signals_dict = {} # printProgressBar(0, len(stocks), prefix = 'Progress:', suffix = 'Complete', length = 50) for i, stock in enumerate(stocks): try: tmp_percent, tmp_max_percent = action(stock, day, sr, lr, debug=False) if tmp_percent == -100.0: wrong_stocks += 1 continue if tmp_percent <= 0: negative_stocks.append(stock) else: positive_stocks.append(stock) if tmp_percent: print(stock, tmp_percent) percent += tmp_percent max_percent += tmp_max_percent except Exception as e: print("FAIL", e) wrong_stocks += 1 continue printProgressBar(i, len(stocks), prefix='Progress:', suffix='Complete', length=50) print("RANGE:", sr, lr) print("TOTAL PERCENT", percent, "MAX:", max_percent, "for", len(stocks) - wrong_stocks) print("TOTAL POSITIVE", len(positive_stocks)) print("TOTAL NEGATIVE", len(negative_stocks)) print("") all_n_stocks.append(negative_stocks) all_p_stocks.append(positive_stocks)
def main(days=1): today = date.today() # today = today - timedelta(days=1) # today = today - timedelta(days=1) # today = today - timedelta(days=1) today = today - timedelta(days=1) # today = today - timedelta(days=1) today = today - timedelta(days=1) # today = today - timedelta(days=1) # today = today - timedelta(days=1) plot = Plotter() total_gain = 0 for i in range(days): today = getPreviousWeekDay(today) if today.day == 4: continue print(today, "-" * 40) manager = StockManager(today) print("FOUND {0} STOCKS TO PLAY".format(len(manager.relaxedTickers()))) manager.buy() prPurple("DAY GAIN", None, [manager.gain]) total_gain += manager.gain plot.create_plot(manager.stocks) today = today - timedelta(days=1) prYellow("TOTAL GAIN", None, [total_gain])
def finishedRelax(self, day, period=PERIOD, intervals=INTERVALS): # Get previous day that is not a weekend yesterday = day - timedelta(days=1) yesterday = getPreviousWeekDay(yesterday) # day = day.strftime("%Y-%m-%d") # yesterday = yesterday.strftime("%Y-%m-%d") data = self.getData(yesterday, day, period, intervals) # Convert interval to int i_interval = int(intervals[:-1]) last_2_hours_index = int(len(data) - (60/i_interval)) temp_hist = data[last_2_hours_index:len(data)] deviation = temp_hist['Close'].std() self._average_height = data.loc[:,"Height"].mean() self._average_volume = data.loc[:,"Volume"].mean() if deviation < self.RELAX_DEVIATION: return True # IF only has 2 digits after . then false # if all([self.isTwoDigits(data['Close'].iloc[-i]) # for i in range(1,3) # ]): # # prRed("Skipping STOCK", None, [self.name]) # return False # FIXME: HACK! return True
def getYesterdaySignalsLength(stock_name, day): yesterday = day - timedelta(days=1) day = utils.getPreviousWeekDay(yesterday) tomorrow = day + timedelta(days=1) data = yf.Ticker(stock_name).history(period='1d', start=day, end=tomorrow, interval='1m') signals = getSignals(data) return len(signals.loc[signals.positions == 1.0] + signals.loc[signals.positions == -1.0])
def finishedRelaxed(stock_name, day): yesterday = day - timedelta(days=1) day = utils.getPreviousWeekDay(yesterday) tomorrow = day + timedelta(days=1) data = yf.Ticker(stock_name).history(period='1d', start=day, end=tomorrow, interval='1m') last_2_hours_index = int(len(data) - (60 / 1.0)) temp_hist = data[last_2_hours_index:len(data)] deviation = temp_hist['Close'].std() if deviation < 0.015: print("RELAXED:", stock_name) return True return False
fig = dict(data=data, layout=layout) py.plot(fig, filename=path, validate=False) stock = 'NBL' #stock = 'PXD' # stock = 'MPC' #stock = 'FTI' #stock = 'PSX' # stock = 'MMM' stock = 'ROL' # main() today = date.today() - timedelta(days=1) day = utils.getPreviousWeekDay(today) print("DAY:", day) result, _ = action(stock, day=day, debug=True) print("RESULT", result) plot(stock, day=day) """ 14 Aug 2019 RANGE: 20 60 TOTAL PERCENT -28.61646194563238 MAX: 176.46724478513283 for 493 TOTAL POSITIVE 137 TOTAL NEGATIVE 356 RANGE: 20 65 TOTAL PERCENT -33.97726175675935 MAX: 179.96781402741664 for 493 TOTAL POSITIVE 132