def open_market(): from datetime import datetime market = False time_now =datetime.now().time() import datetime market_open = datetime.time(9,30,0) # 9:30AM market_close = datetime.time(15,59,0) # 3:59PM if time_now > market_open and time_now < market_close: market = True else: # print('### market is closed') pass return(market) def logout(): rh.authentication.logout() #import config def get_cash(): rh_cash = rh.profiles.load_account_profile() cash = float(rh_cash['margin_balances']["day_trade_buying_power"]) return(cash) def get_holdings_and_bought_price(stocks): holdings = {stocks[i]: 0 for i in range(0, len(stocks))} bought_price = {stocks[i]: 0 for i in range(0, len(stocks))} rh_holdings = rh.account.build_holdings() for stock in stocks: try: holdings[stock] = int(float((rh_holdings[stock]['quantity']))) bought_price[stock] = float((rh_holdings[stock]['average_buy_price'])) except: holdings[stock] = 0 bought_price[stock] = 0 return(holdings, bought_price) #holdings, bought_price = get_holdings_and_bought_price(stocks) def sell(stock, holdings): # # sell_price = round((price-0.10), 2) # # un-comment when ready to trade on the live market # # print('sell is currently commented') # sell_order = rh.orders.order_sell_market(symbol=stock, # quantity=holdings, # timeInForce='gfd') print('### Trying to SELL {} at ${}'.format(stock, price)) #stock = 'ROP' #allowable_holdings =1000 # def buy(stock, allowable_holdings): # # #buy_price = round((price+0.10), 2) # # # un-comment when ready to trade on the live market # # print('buy is currently commented') # # buy_order = rh.orders.order_buy_market(symbol=stock, # # quantity=allowable_holdings, # # timeInForce='gfd') # buy_order = rh.orders.order_buy_fractional_by_price(stock, # allowable_holdings, # timeInForce='gtc', # extendedHours=False) # print('### Trying to BUY {} at ${}'.format(stock, price)) # rs.orders.order_buy_fractional_by_price(symbol, # ammountInDollars, # timeInForce='gtc', # extendedHours=False) def build_dataframes(df_trades, trade_dict, df_prices, price_dict): import datetime as dt time_now = str(dt.datetime.now().time())[:8] df_trades.loc[time_now] = trade_dict df_prices.loc[time_now] = price_dict return(df_trades, df_prices) # dg = pd.read_csv(r'C:/Users/jizha/Desktop/three_strategy_buy_point_2022_3_4.csv') # dg.columns # g =dg['0'].tolist() # l =g # stocks = l def get_historical_prices(stocks): def price_5mins(stock): from datetime import datetime as dt import datetime import requests api_key = '86dd63f6b8ae774b061232685b78eb52' today = dt.today() a=str(today.year) b=str(today.month) c=str(today.day) d=str(today.day-1) e=int(today.day) start = a +'-'+ b +'-'+d end =a +'-'+ b +'-'+c bs = requests.get(f'https://financialmodelingprep.com/api/v3/historical-chart/5min/{stock}?from={start}&to={end}&apikey={api_key}').json() #bs1 = requests.get(f'https://financialmodelingprep.com/api/v3/historical-chart/5min/AAPL?apikey={api_key}').json() df = pd.DataFrame(bs) dates_times = pd.to_datetime(df.loc[:, 'date']) close_prices = df.loc[:, 'close'].astype('float') df_price = pd.concat([close_prices, dates_times], axis=1) df_price = df_price.set_index('date') df_price1 = df_price.loc[(df_price.index.day==e),:] # df_price = df_price.iloc[date, :] df_price1 = df_price1.rename(columns={'close': stock}) df_price1 =df_price1.sort_index() return df_price1 def close_price(stock): from datetime import datetime as dt import datetime import requests api_key = '86dd63f6b8ae774b061232685b78eb52' today = dt.today() a=str(today.year) b=str(today.month) c=str(today.day-1) d = str(today.day-2) start = a +'-'+ b +'-'+d end =a +'-'+ b +'-'+c bs1 = requests.get(f'https://financialmodelingprep.com/api/v3/historical-price-full/{stock}?from={start}&to={end}&apikey={api_key}').json() df_1 = pd.DataFrame(bs1['historical']) # stock = pd.DataFrame(bs) df_1 =df_1[['date','open','high','low','close','volume']] dates = pd.to_datetime(df_1.loc[:, 'date']) close= df_1.loc[:, 'close'].astype('float') df_2 = pd.concat([close, dates], axis=1) #= df_2.iloc[:10, :] df_2 = df_2.rename(columns={'close': stock}) df_2 = df_2.set_index('date') # df_2 = df_2.sort_index() return df_2 df_close = pd.DataFrame() for stock in stocks: print(stock) df_price2 = close_price(stock) df_close = pd.concat([df_close,df_price2], axis =1) df_price = pd.DataFrame() for stock in stocks: print(stock) df_price1 = price_5mins(stock) df_price = pd.concat([df_price,df_price1], axis =1) #stock = 'AAPL' final_data1 = pd.DataFrame() for stock in stocks: price_5min = df_price[stock][1] price_10min = df_price[stock][2] close_p = df_close[stock][0] pct_change = ((price_10min-close_p)/ close_p) *100 final_data = pd.DataFrame(columns = ['price_5min','price_10min','close_p','pct_change']) final_data = final_data.append({'price_5min':price_5min, 'price_10min':price_10min ,'close_p':close_p,'pct_change':pct_change}, ignore_index = True) final_data =final_data .T final_data = final_data.rename(columns = {0:stock}) final_data1 =pd.concat([final_data1 ,final_data], axis =1) # final_data1['pct_change'] =round( final_data1['price_10m']/final_data1['close_p'],2) return final_data1 #stocks = final_trade_stock def final_trade_stock(stocks): final_data1 = get_historical_prices(stocks) trade_stock = [] for stock in stocks: if final_data1[stock]['price_5min'] <= final_data1[stock]['price_10min'] and final_data1[stock]['price_10min'] >= final_data1[stock]['close_p']: trade_stock.append(stock) f = pd.DataFrame(final_data1[trade_stock]) final_trade_stock = [] for t in f.columns: if 0