def get_stock_price(self, content): name_to_ticker = { "amazon": "amzn", "google": "goog", "chevron": "cvx", "yahoo": "yhoo", "walmart": "wal", } s_content = content.split() ticker = s_content[-1] if ticker in ("ticker", "stock") and len(ticker) >= 2: ticker = s_content[-2] if ticker in name_to_ticker: ticker = name_to_ticker[ticker] try: price = web.get_last_iex(ticker).to_dict()[0]["price"] self.respond( "{} is at {}, this information has 15 minute delay".format( ticker, price)) except Exception as exc: print("Could not get price for ticker: {}".format(ticker))
def download_stock(stock): """ try to query the iex for a stock, if failed note with print """ """ set the download window """ now_time = datetime.datetime.now() past_five_pm=now_time.replace(hour=18, minute=0, second=0, microsecond=0) start_time = datetime.datetime(now_time.year - 5, now_time.month , now_time.day) weekno=datetime.datetime.today().weekday() try: print(stock) stock_df='' if(IEX==True): stock_df = web.DataReader(stock,'iex', start_time, now_time) stock_df['Name'] = stock else: stock_df = web.DataReader(stock,'robinhood', start_time, now_time) output_name = os.path.join('.','stocks',stock+'_data.csv') stock_df.to_csv(output_name) if(now_time>=past_five_pm and weekno<5): #get the last value padding ohlcv if(IEX==True): current=web.get_last_iex(stock)[0][0] temphigh=stock_df['close'][len(stock_df)-1] templow=stock_df['close'][len(stock_df)-1] previous_close=stock_df['close'][len(stock_df)-1] else: current = float(web.get_quotes_robinhood(stock)[stock][7]) temphigh=float(stock_df['close_price'][len(stock_df)-1]) templow=float(stock_df['close_price'][len(stock_df)-1]) previous_close=float(stock_df['close_price'][len(stock_df)-1]) tempvol=int(stock_df['volume'][len(stock_df)-1]) current_date=datetime.datetime.today().strftime('%Y-%m-%d') if(current>temphigh): temphigh=current if(templow>current): templow=current #df.append({ 'date':current_date, 'open':previous_close, 'high':temphigh, 'low':templow, 'close':current, 'volume':tempvol, 'Name':stock }) with open(os.path.join('.','stocks',stock+'_data.csv'), 'a') as f: if(IEX==True): f.write( '%s,%0.2f,%0.2f,%0.2f,%0.2f,%d,%s\n'%(current_date, previous_close, temphigh, templow, current, tempvol, stock)) else: f.write( '%s,%s,%0.6f,%0.6f,False,%0.6f,%0.6f,reg,%d\n'%(stock, current_date, current, temphigh, templow, previous_close, tempvol)) except Exception as e: bad_names.append(stock) print('bad: %s %s' % (e,stock))
def getQuoteGoogle(): tickers = ['AAPL', 'MSFT', '^GSPC'] start_date = '2010-01-01' end_date = '2016-12-31' panel_data = web.DataReader('INPX', 'google', start_date, end_date) web.get_last_iex()
def test_live_prices(self): dftickers = get_iex_symbols() tickers = dftickers[:5].symbol.values df = get_last_iex(tickers[:5]) assert df["price"].mean() > 0
def test_false_ticker(self): df = get_last_iex("INVALID TICKER") assert df.shape[0] == 0
def test_false_ticker(self): df = get_last_iex("INVALID TICKER") tm.assert_frame_equal(df, DataFrame())
def do_main(argv): stock_dataset = '' if (len(argv) >= 3 and argv[2] == '-d'): stock = argv[1] now_time = datetime.datetime.now() past_five_pm = now_time.replace(hour=18, minute=0, second=0, microsecond=0) weekno = datetime.datetime.today().weekday() stock_dataset = web.DataReader( argv[1], 'iex', datetime.datetime(datetime.datetime.now().year - 5, datetime.datetime.now().month, datetime.datetime.now().day), datetime.datetime.now() + datetime.timedelta(days=1)) stock_dataset['Name'] = stock stock_dataset.to_csv('./stocks/' + argv[1] + '_data.csv') if (now_time >= past_five_pm and weekno < 5): #get the last value padding ohlcv current = web.get_last_iex(stock)[0][0] temphigh = stock_dataset['close'][len(stock_dataset) - 1] templow = stock_dataset['close'][len(stock_dataset) - 1] tempvol = int(stock_dataset['volume'][len(stock_dataset) - 1]) previous_close = stock_dataset['close'][len(stock_dataset) - 1] current_date = datetime.datetime.today().strftime('%Y-%m-%d') if (current > temphigh): temphigh = current if (templow > current): templow = current with open(os.path.join('.', 'stocks', stock + '_data.csv'), 'a') as f: f.write('%s,%0.2f,%0.2f,%0.2f,%0.2f,%d,%s\n' % (current_date, previous_close, temphigh, templow, current, tempvol, stock)) stock_dataset = pd.read_csv('./stocks/' + argv[1] + '_data.csv') else: stock_dataset = pd.read_csv('./stocks/' + argv[1] + '_data.csv') dataset = stock_dataset['close'] dataset2 = stock_dataset['low'] #x_scaler = MinMaxScaler(feature_range=(0, 1)) #y_scaler = MinMaxScaler(feature_range=(0, 1)) window_size = 10 X = [] y = [] for i in range(window_size, len(dataset)): X.append(dataset[i - window_size:i]) for i in range(window_size, len(dataset2)): y.append([dataset2[i]]) X.append(dataset[len(dataset) - window_size:]) X = np.asarray(X) y = np.asarray(y) #X=x_scaler.fit_transform(X) #y_train=y_scaler.fit_transform(y) y_train = y X_train = X[:-1, ] X_test = X[-1:, ] # NOTE: to use keras's RNN LSTM module our input must be reshaped to [samples, window size, stepsize] X_train = np.asarray( np.reshape(X_train, (X_train.shape[0], window_size, 1))) X_test = np.asarray(np.reshape(X_test, (X_test.shape[0], window_size, 1))) # start with fixed random seed np.random.seed(0) # Build an RNN to perform regression on our time series input/output data model = Sequential() model.add(LSTM(128, input_shape=(window_size, 1), return_sequences=True)) model.add(LSTM(64, return_sequences=True)) model.add(LSTM(32)) model.add(Dense(16)) model.add(Dense(1)) optimizer = keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0) model.summary() # compile the model model.compile(loss='mean_squared_error', optimizer=optimizer) model.fit(X_train, y_train, epochs=500, batch_size=256, verbose=1) # generate predictions for training test_predict = model.predict(X_test) #prediction=y_scaler.inverse_transform(test_predict)[0][0] prediction = test_predict[0][0] dataset = np.asarray(dataset2) history = dataset[-1] print("Prediction %s: %f vs Last Value: %f" % (argv[1], prediction, history)) if (prediction > history): return True else: return False