def in_stock(self): self.status_signal.emit(create_msg("Checking stock", "normal")) url = "https://www.bestbuy.com/api/tcfb/model.json?paths=%5B%5B%22shop%22%2C%22scds%22%2C%22v2%22%2C%22page%22%2C%22tenants%22%2C%22bbypres%22%2C%22pages%22%2C%22globalnavigationv5sv%22%2C%22header%22%5D%2C%5B%22shop%22%2C%22buttonstate%22%2C%22v5%22%2C%22item%22%2C%22skus%22%2C{}%2C%22conditions%22%2C%22NONE%22%2C%22destinationZipCode%22%2C%22%2520%22%2C%22storeId%22%2C%22%2520%22%2C%22context%22%2C%22cyp%22%2C%22addAll%22%2C%22false%22%5D%5D&method=get".format( self.sku_id ) # TODO: Add random delay configuration response = self.session.get(url, headers=DEFAULT_HEADERS) self.status_signal.emit(create_msg(f"Stock check response code: {response.status_code}", "normal")) try: response_json = response.json() item_json = find_values( json.dumps(response_json), "buttonStateResponseInfos" ) item_state = item_json[0][0]["buttonState"] self.status_signal.emit(create_msg(f"Item state is: {item_state}", "normal")) if item_json[0][0]["skuId"] == self.sku_id and item_state in [ "ADD_TO_CART", "PRE_ORDER" ]: return True else: return False except Exception as e: self.status_signal.emit(create_msg("Error parsing json. Using string search to determine state.", "error")) self.status_signal.emit(create_msg(f"{response_json}", "normal")) self.status_signal.emit(create_msg(f"{e}", "error")) if "ADD_TO_CART" in response.text: #TODO: Make this case insensitive self.status_signal.emit(create_msg("Item is in stock!", "normal")) return True else: self.status_signal.emit(create_msg("Item is out of stock", "normal")) webdriver.refresh() return False
def link_to_reset_pswd(self, webdriver): self.restore_link = None webdriver.get('https://mail.yandex.ru/lite') while self.restore_link == None: elements = webdriver.find_elements_by_class_name( 'b-messages__message__left') for i in range(len(elements)): time.sleep(2) try: element = elements[i].text if len( re.findall( 'https://accounts.epicgames.com/resetPassword\?code=(\w{32})', element)) != 0: self.restore_link = \ re.findall('https://accounts.epicgames.com/resetPassword\?code=(\w{32})', element)[0] except: pass else: time.sleep(REFRESH_SEC) webdriver.refresh() time.sleep(REFRESH_SEC) webdriver.refresh() print(self.restore_link) return 'https://accounts.epicgames.com/resetPassword\?code=' + self.restore_link
def get_signal(ticker, interval): #Declare variable analysis = [] #Open tradingview's site webdriver.get( "https://s.tradingview.com/embed-widget/technical-analysis/?locale=en#%7B%22interval%22%3A%22{}%22%2C%22width%22%3A%22100%25%22%2C%22isTransparent%22%3Afalse%2C%22height%22%3A%22100%25%22%2C%22symbol%22%3A%22{}%22%2C%22showIntervalTabs%22%3Atrue%2C%22colorTheme%22%3A%22dark%22%2C%22utm_medium%22%3A%22widget_new%22%2C%22utm_campaign%22%3A%22technical-analysis%22%7D" .format(interval, ticker)) webdriver.refresh() #Wait for site to load elements while len( webdriver.find_elements_by_class_name( "speedometerSignal-pyzN--tL")) == 0: sleep(0.1) #Recommendation recommendation_element = webdriver.find_element_by_class_name( "speedometerSignal-pyzN--tL") analysis.append(recommendation_element.get_attribute('innerHTML')) #Counters counter_elements = webdriver.find_elements_by_class_name( "counterNumber-3l14ys0C") #Sell analysis.append(int(counter_elements[0].get_attribute('innerHTML'))) #Neutral analysis.append(int(counter_elements[1].get_attribute('innerHTML'))) #Buy analysis.append(int(counter_elements[2].get_attribute('innerHTML'))) last_analysis = analysis signal = last_analysis[0] num_sell = last_analysis[1] num_neutral = last_analysis[2] num_buy = last_analysis[3] line = '-' * 50 ticker = ticker.strip('"') interval = interval.strip('"') line = line.strip('"') signal = signal.strip('"') ticker = json.dumps(ticker) interval = json.dumps(interval) signal = json.dumps(signal) num_sell = json.dumps(num_sell) num_neutral = json.dumps(num_neutral) num_buy = json.dumps(num_buy) line = json.dumps(line) value = f'TradingView Data for {ticker} for {interval}: ' + '<br/>' + line + '<br/>' + f'Overall Signal: {signal}' + '<br/>' + f'Number of Sell Indicators: {num_sell}' + '<br/>' + f'Number of Neutral Indicators: {num_neutral}' + '<br/>' + f'Number of Buy Indicators: {num_buy}' return value
def take_first_code(self, webdriver): self.first_code = None webdriver.get('https://mail.yandex.ru/lite') while self.first_code == None: elements = webdriver.find_elements_by_class_name( 'b-messages__message__left') for i in range(len(elements)): try: element = elements[i].text if len(re.findall('! (\d{6})', element)) != 0: self.first_code = re.findall('! (\d{6})', element)[0] except: pass else: time.sleep(REFRESH_SEC) webdriver.refresh() time.sleep(REFRESH_SEC) webdriver.refresh() print(self.first_code) return self.first_code
options = Options() options.add_argument("--headless") options.add_argument('window-size=1200x600') webdriver = webdriver.Chrome( executable_path= '/Users/shashank/Documents/GitHub/Code/Finance/chromedriver.exe', options=options) #Declare variable analysis = [] #Open tradingview's site webdriver.get( "https://s.tradingview.com/embed-widget/technical-analysis/?locale=en#%7B%22interval%22%3A%22{}%22%2C%22width%22%3A%22100%25%22%2C%22isTransparent%22%3Afalse%2C%22height%22%3A%22100%25%22%2C%22symbol%22%3A%22{}%22%2C%22showIntervalTabs%22%3Atrue%2C%22colorTheme%22%3A%22dark%22%2C%22utm_medium%22%3A%22widget_new%22%2C%22utm_campaign%22%3A%22technical-analysis%22%7D" .format(interval, ticker)) webdriver.refresh() #Wait for site to load elements while len(webdriver.find_elements_by_class_name( "speedometerSignal-pyzN--tL")) == 0: sleep(0.1) #Recommendation recommendation_element = webdriver.find_element_by_class_name( "speedometerSignal-pyzN--tL") analysis.append(recommendation_element.get_attribute('innerHTML')) #Counters counter_elements = webdriver.find_elements_by_class_name( "counterNumber-3l14ys0C")
def get_signal(ticker, interval): try: ticker = ticker.strip() interval = interval.strip() #Declare variable analysis = [] #Open tradingview's site webdriver.get( "https://s.tradingview.com/embed-widget/technical-analysis/?locale=en#%7B%22interval%22%3A%22{}%22%2C%22width%22%3A%22100%25%22%2C%22isTransparent%22%3Afalse%2C%22height%22%3A%22100%25%22%2C%22symbol%22%3A%22{}%22%2C%22showIntervalTabs%22%3Atrue%2C%22colorTheme%22%3A%22dark%22%2C%22utm_medium%22%3A%22widget_new%22%2C%22utm_campaign%22%3A%22technical-analysis%22%7D" .format(interval, ticker)) webdriver.refresh() #Wait for site to load elements while len( webdriver.find_elements_by_class_name( "speedometerSignal-pyzN--tL")) == 0: sleep(0.1) #Recommendation recommendation_element = webdriver.find_element_by_class_name( "speedometerSignal-pyzN--tL") analysis.append(recommendation_element.get_attribute('innerHTML')) #Counters counter_elements = webdriver.find_elements_by_class_name( "counterNumber-3l14ys0C") #Sell analysis.append(int(counter_elements[0].get_attribute('innerHTML'))) #Neutral analysis.append(int(counter_elements[1].get_attribute('innerHTML'))) #Buy analysis.append(int(counter_elements[2].get_attribute('innerHTML'))) last_analysis = analysis signal = last_analysis[0] num_sell = last_analysis[1] num_neutral = last_analysis[2] num_buy = last_analysis[3] line = '-' * 60 def get_symbol(symbol): url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}®ion=1&lang=en".format( symbol) result = requests.get(url).json() for x in result['ResultSet']['Result']: if x['symbol'] == symbol: return x['name'] company_name = get_symbol(ticker.upper()) current_price = round(si.get_live_price(ticker), 2) if company_name.lower() == 'none': company_name = ticker if interval == "1m": long_interval = "1 minute" elif interval == "5m": long_interval = "5 minutes" elif interval == "15m": long_interval = "15 minutes" elif interval == "1h": long_interval = "1 hour" elif interval == "4h": long_interval = "4 hours" elif interval == "1D": long_interval = "1 day" elif interval == "1W": long_interval = "1 week" elif interval == "1M": long_interval = "1 month" ticker = json.dumps(ticker) interval = json.dumps(interval) signal = json.dumps(signal) num_sell = json.dumps(num_sell) num_neutral = json.dumps(num_neutral) num_buy = json.dumps(num_buy) line = json.dumps(line) return render_template('output.html', company_name=company_name, long_interval=long_interval, signal=signal, current_price=current_price, num_buy=num_buy, num_neutral=num_neutral, num_sell=num_sell) except Exception as e: return f"{e} <br> Sorry, this ticker or interval is unavailable {line}"
def getData(list_of_stocks): for stock in list_of_stocks: df = DataReader(stock, 'yahoo', start, end) print(stock) # Current Price price = si.get_live_price('{}'.format(stock)) price = round(price, 2) # Sharpe Ratio x = 5000 y = (x) stock_df = df stock_df['Norm return'] = stock_df['Adj Close'] / stock_df.iloc[0][ 'Adj Close'] allocation = float(x / y) stock_df['Allocation'] = stock_df['Norm return'] * allocation stock_df['Position'] = stock_df['Allocation'] * x pos = [df['Position']] val = pd.concat(pos, axis=1) val.columns = ['WMT Pos'] val['Total Pos'] = val.sum(axis=1) val.tail(1) val['Daily Return'] = val['Total Pos'].pct_change(1) Sharpe_Ratio = val['Daily Return'].mean() / val['Daily Return'].std() A_Sharpe_Ratio = (252**0.5) * Sharpe_Ratio A_Sharpe_Ratio = round(A_Sharpe_Ratio, 2) # News Sentiment finwiz_url = 'https://finviz.com/quote.ashx?t=' news_tables = {} url = finwiz_url + stock req = Request(url=url, headers={'user-agent': 'my-app/0.0.1'}) response = urlopen(req) html = BeautifulSoup(response, features="lxml") news_table = html.find(id='news-table') news_tables[stock] = news_table parsed_news = [] # Iterate through the news for file_name, news_table in news_tables.items(): for x in news_table.findAll('tr'): text = x.a.get_text() date_scrape = x.td.text.split() if len(date_scrape) == 1: time = date_scrape[0] else: date = date_scrape[0] time = date_scrape[1] ticker = file_name.split('_')[0] parsed_news.append([ticker, date, time, text]) vader = SentimentIntensityAnalyzer() columns = ['ticker', 'date', 'time', 'headline'] dataframe = pd.DataFrame(parsed_news, columns=columns) scores = dataframe['headline'].apply(vader.polarity_scores).tolist() scores_df = pd.DataFrame(scores) dataframe = dataframe.join(scores_df, rsuffix='_right') dataframe['date'] = pd.to_datetime(dataframe.date).dt.date dataframe = dataframe.set_index('ticker') sentiment = round(dataframe['compound'].mean(), 2) # TradingView Recommendation try: #Declare variable analysis = [] #Open tradingview's site webdriver.get( "https://s.tradingview.com/embed-widget/technical-analysis/?locale=en#%7B%22interval%22%3A%22{}%22%2C%22width%22%3A%22100%25%22%2C%22isTransparent%22%3Afalse%2C%22height%22%3A%22100%25%22%2C%22symbol%22%3A%22{}%22%2C%22showIntervalTabs%22%3Atrue%2C%22colorTheme%22%3A%22dark%22%2C%22utm_medium%22%3A%22widget_new%22%2C%22utm_campaign%22%3A%22technical-analysis%22%7D" .format(interval, ticker)) webdriver.refresh() #Wait for site to load elements while len( webdriver.find_elements_by_class_name( "speedometerSignal-pyzN--tL")) == 0: sleep(0.1) #Recommendation recommendation_element = webdriver.find_element_by_class_name( "speedometerSignal-pyzN--tL") analysis.append(recommendation_element.get_attribute('innerHTML')) #Counters counter_elements = webdriver.find_elements_by_class_name( "counterNumber-3l14ys0C") #Sell analysis.append(int( counter_elements[0].get_attribute('innerHTML'))) #Neutral analysis.append(int( counter_elements[1].get_attribute('innerHTML'))) #Buy analysis.append(int( counter_elements[2].get_attribute('innerHTML'))) signal = analysis[0] except: signal = 'None' # Beta df = DataReader(stock, 'yahoo', start, end) dfb = DataReader('^GSPC', 'yahoo', start, end) rts = df.resample('M').last() rbts = dfb.resample('M').last() dfsm = pd.DataFrame( { 's_adjclose': rts['Adj Close'], 'b_adjclose': rbts['Adj Close'] }, index=rts.index) dfsm[['s_returns','b_returns']] = dfsm[['s_adjclose','b_adjclose']]/\ dfsm[['s_adjclose','b_adjclose']].shift(1) -1 dfsm = dfsm.dropna() covmat = np.cov(dfsm["s_returns"], dfsm["b_returns"]) beta = covmat[0, 1] / covmat[1, 1] beta = round(beta, 2) # Relative Strength Index df["rsi"] = talib.RSI(df["Close"]) values = df["rsi"].tail(14) value = values.mean() rsi = round(value, 2) output = ("\nTicker: " + str(stock) + "\nCurrent Price : " + str(price) + "\nSharpe Ratio: " + str(A_Sharpe_Ratio) + "\nNews Sentiment: " + str(sentiment) + "\nTradingView Rec for {}: ".format(interval) + str(signal) + "\nRelative Strength Index: " + str(rsi) + "\nBeta Value for 1 Year: " + str(beta)) sendMessage(output)