def update_value(company): if (company == "AAPL"): model = apple_model elif (company == "GOOG"): model = google_model elif (company == "MSFT"): model = microsoft_model elif (company == "FB"): model = facebook_model starting_program = time.time() start = datetime.datetime.now() + datetime.timedelta(-1070) end = datetime.datetime.now() df = web.DataReader(company, 'yahoo', start, end) df.reset_index(inplace=True) df.set_index("Date", inplace=True) # current_stock_value = stock_info(company.lower()) current_stock_value = stock_info.get_live_price(company.lower()) dates = list(df.index[30:]) future_dates = [] for i in range(30): future_dates.append(datetime.datetime.now() + datetime.timedelta(i)) x_forecast = np.reshape(np.array(df['Adj Close']), (-1, 1)) predictions = model.predict(x_forecast) old_predictions = predictions[:-30] future_predictions = predictions[-30:] print("Total time taken:", time.time() - starting_program) return dcc.Graph(id='example-graph', figure={ 'data': [ { 'x': df.index[30:], 'y': df.Close[30:], 'type': 'line', 'name': 'Actual Value', 'line': dict(color='firebrick', width=3) }, { 'x': dates, 'y': old_predictions, 'type': 'line', 'name': 'Old Predictions', 'line': dict(color='royalblue', width=3) }, { 'x': future_dates, 'y': future_predictions, 'type': 'dashed-line', 'name': 'Future Predictions', 'line': dict(color='gray', width=2) }, ], 'layout': { 'title': { 'text': company_list[company], 'font': { 'size': 50, 'color': '#7FDBFF' }, 'x': 0.05, 'y': 1.4, 'xanchor': 'left', 'yanchor': 'bottom', }, 'annotations': [{ 'text': str(round(df.iloc[-1]['Close'], 2)), 'font': { 'size': 25, 'color': '#7FDBFF', }, 'showarrow': False, 'align': 'center', 'x': 0, 'y': 1.15, 'xref': 'paper', 'yref': 'paper', }, { 'text': 'USD', 'font': { 'size': 12, 'color': '#7FDBFF', }, 'showarrow': False, 'align': 'center', 'x': 0.06, 'y': 1.11, 'xref': 'paper', 'yref': 'paper', }, { 'text': str(round(df.iloc[-1]['Close'], 2)), 'font': { 'size': 18, 'color': '#7FDBFF', }, 'showarrow': False, 'align': 'center', 'x': 0.7, 'y': 1.15, 'xref': 'paper', 'yref': 'paper', }, { 'text': 'PREV', 'font': { 'size': 10, 'color': '#7FDBFF', }, 'showarrow': False, 'align': 'center', 'x': 0.7, 'y': 1.07, 'xref': 'paper', 'yref': 'paper', }, { 'text': str(round(df.iloc[-1]['Open'], 2)), 'font': { 'size': 18, 'color': '#7FDBFF', }, 'showarrow': False, 'align': 'center', 'x': 0.76, 'y': 1.15, 'xref': 'paper', 'yref': 'paper', }, { 'text': 'OPEN', 'font': { 'size': 10, 'color': '#7FDBFF', }, 'showarrow': False, 'align': 'center', 'x': 0.76, 'y': 1.07, 'xref': 'paper', 'yref': 'paper', }, { 'text': str(round(df.iloc[-1]['Volume'], 2)), 'font': { 'size': 18, 'color': '#7FDBFF', }, 'showarrow': False, 'align': 'center', 'x': 0.84, 'y': 1.15, 'xref': 'paper', 'yref': 'paper', }, { 'text': 'VOLUME', 'font': { 'size': 10, 'color': '#7FDBFF', }, 'showarrow': False, 'align': 'center', 'x': 0.84, 'y': 1.07, 'xref': 'paper', 'yref': 'paper', }], 'legend': { 'x': 0, 'y': 1 }, 'plot_bgcolor': '#111111', 'paper_bgcolor': '#111111', 'font': { 'color': '#7FDBFF' } } })
def limit_order_purchase(transaction_obj): user = UserDetails.objects.get(user=transaction_obj.user) user_buyingpower = float(user.identity.buyingpower) identity = IdentityDetails.objects.get(id=user.identity.id) live_price = si.get_live_price( transaction_obj.stockticker.symbol + ".NS") print("live_price ", num_quantize(float(live_price))) status_flag = 0 if transaction_obj.ordertype == "market_order": status_flag = 1 elif transaction_obj.ordertype == "limit_order" and num_quantize( float(live_price)) == num_quantize( float(transaction_obj.price)): status_flag = 1 if status_flag == 1: transaction_obj.status = "executed" transaction_obj.save() from accounts.models import Position position_obj, status = Position.objects.get_or_create( userid=transaction_obj.user, stockname=transaction_obj.stock, ticker=transaction_obj.stockticker.symbol, price=live_price, ordertype=transaction_obj.ordertype) position_obj.transaction_details = transaction_obj position_obj.save() try: history_obj = TransactionHistory.objects.get_or_create( position_obj=position_obj, stock_number=transaction_obj.size) except: pass try: total_cash = float(live_price) * int( transaction_obj.size) from accounts.models import GainLossHistory gl_history = GainLossHistory.objects.create( userid=transaction_obj.user, stock=transaction_obj.stock, total_cash=total_cash) gl_history.unrealised_gainloss = num_quantize( (float(live_price) - float( position_obj.transaction_details.price)) * int(transaction_obj.size)) gl_history.position_obj = position_obj gl_history.save() user_buyingpower -= total_cash identity.buyingpower = user_buyingpower identity.save() except: pass else: if transaction_obj.remove_date and transaction_obj.expires == "Good till canceled": if current_date.date( ) == transaction_obj.remove_date.date(): transaction_obj.delete() print("Status====", transaction_obj.status)
scaler = StandardScaler() X = scaler.fit_transform(X) X = pd.DataFrame(X, columns=predictors) load = today_input() now = datetime.now() today = now.strftime("%Y-%m-%d") target_MP = [] for i in range(0, len(load)): tick = load['Ticker'].tolist()[i] namefile = tick + '-' + today + '.csv' path = "C:\\Users\\Admin\\Desktop\\Week_2\\Options_before_earning\\" + namefile maxpain_value = maxpain(path) info = si.get_live_price(tick) direction = np.sign(maxpain_value - info) target_MP.append(direction) target_MP = np.asarray(target_MP) target_MP = target_MP.reshape(-1, 1) scaler = StandardScaler() XX = scaler.fit_transform(target_MP) XX = pd.DataFrame(XX, columns=predictors) nlp4_name = "LR_1_inv" nlp4 = LogisticRegression(C=0.001, penalty='l1') nlp4.fit(X, y) prediction_nlp1 = invertion_signal_array(nlp4.predict(XX))
import requests as r from yahoo_fin import stock_info as si key = str(input("stock name")) url = "https://www.cnbc.com/quotes/?symbol=." + key response = r.get(url) print(response.json) print(si.get_live_price("aapl"))
def get_stock_details_json(symbol): """ :param symbol: :return: """ try: from yahoo_fin import stock_info as si from accounts.models import Position response = {} from accounts.models import StockNames stock_obj = StockNames.objects.get(symbol=symbol) try: data = stock_obj.history.history_json data = data['data'] except: data = get_new_history(symbol) if not bool(data): data = get_new_history(symbol) data['symbol'] = symbol # 1day d_data = si.get_data(symbol + ".NS", interval="1d") d_price_list = d_data.values.tolist() prev_day_price = d_price_list[len(d_price_list) - 2][4] response['prev_day_price'] = prev_day_price # 1m today = datetime.datetime.now() start_date = today.date() - dateutil.relativedelta.relativedelta( months=2) prev_month = today.date() - dateutil.relativedelta.relativedelta( months=1) m_data = si.get_data(symbol + ".NS", start_date=start_date, end_date=prev_month, interval="1d") m_price_list = m_data.values.tolist() prev_month_price = m_price_list[len(m_price_list) - 1][4] response['prev_month_price'] = prev_month_price # 3m start_date = today.date() - dateutil.relativedelta.relativedelta( months=4) prev_3month = today.date() - dateutil.relativedelta.relativedelta( months=3) three_m_data = si.get_data(symbol + ".NS", start_date=start_date, end_date=prev_3month, interval="1d") three_m_price_list = three_m_data.values.tolist() prev_3m_price = three_m_price_list[len(three_m_price_list) - 1][4] response['prev_3m_price'] = prev_3m_price # 6m start_date = today.date() - dateutil.relativedelta.relativedelta( months=7) prev_6month = today.date() - dateutil.relativedelta.relativedelta( months=6) six_m_data = si.get_data(symbol + ".NS", start_date=start_date, end_date=prev_6month, interval="1d") six_m_price_list = six_m_data.values.tolist() prev_6m_price = six_m_price_list[len(six_m_price_list) - 1][4] response['prev_6m_price'] = prev_6m_price # 1y start_date = today.date() - dateutil.relativedelta.relativedelta( years=1, months=1) prev_year = today.date() - dateutil.relativedelta.relativedelta( years=1) y_data = si.get_data(symbol + ".NS", start_date=start_date, end_date=prev_year, interval="1d") y_price_list = y_data.values.tolist() prev_y_price = y_price_list[len(y_price_list) - 1][4] response['prev_y_price'] = prev_y_price from custom_packages.yahoo_finance import YahooFinance latest_price = YahooFinance(symbol + '.NS', result_range='1d', interval='1m', dropna='True').result count = 0 for i, j in latest_price.iterrows(): temp_price_list = [] dt_object1 = datetime.datetime.strptime(str(i), "%Y-%m-%d %H:%M:%S") my_time = dt_object1.time() my_datetime = datetime.datetime.combine(i, my_time) date = datetime.datetime.timestamp(my_datetime) temp_price_list.append(int(date) * 1000) temp_price_list.append(latest_price.values.tolist()[count][2]) # latest_price_list.append(temp_price_list) data['stock_price_list'].append(temp_price_list) count += 1 stock_price = round(si.get_live_price(symbol + ".NS"), 2) data['stockprice'] = stock_price print("PRICEEE -- ", stock_price) try: for pos_obj in Position.objects.filter(ticker=symbol): share_num = int(pos_obj.transaction_details.size) pos_obj.unrealised_gainloss = num_quantize( (float(stock_price) - float(pos_obj.transaction_details.price)) * share_num) pos_obj.save() print("GAIN LOSS --SYMBOL ", symbol, pos_obj.unrealised_gainloss) except Exception as e: print("POSITION ERROR ", e) pass except Exception as e: print("ERROR OCCUREDDDDD ", e) data = {} response = {} return data, response
def update(self): self._live = float(round(get_live_price(self.ticker), 2)) # get_live_price returns numpy.float64 self._table = get_quote_table(self.ticker) return self._live, self._table
def render_dict(lst): for item in lst: stocks_dict[item] = str(round(si.get_live_price(item), 3)) return stocks_dict
def threaded_price_stream(ticker): while True: print(stock_info.get_live_price(ticker)) sleep(1)
from yahoo_fin import stock_info from time import sleep from win10toast import ToastNotifier hr = ToastNotifier() brand = input("Enter company name: ") cp = int(input("Enter cost price: ")) lowerBound = int(input("Enter sell price: ")) upperBound = int(input("Enter notifier price: ")) while True: sleep(2) price = stock_info.get_live_price(brand) if (price < lowerBound): print("Sell now") elif (price > lowerBound and price > cp and price < upperBound): print("Profittt") elif (price >= upperBound): print("Target hit, current price is", price) hr.show_toast("Target hit, current price is", str(price))
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 current_price(ticker): dict = {"current_price": str(stock_info.get_live_price(ticker))} print(json.dumps(dict))
def silver_price(): silver_live = get_live_price('si=f') return str("Silver futures are trading at " '${:.2f}'.format(silver_live)+".")
def gold_price(): gold_live = get_live_price('gc=f') return str("Gold futures are trading at " '${:,.2f}'.format(gold_live)+".")
import yahoo_fin.stock_info as si import time import json with open('config.json', 'r') as f: config = json.load(f) sum = 0 for holding in config['portfolio']: qty = int(holding['quantity']) price = si.get_live_price(holding['ticker']) print(holding['ticker'], qty, price, qty * price) sum += qty * price timestamp = int(time.time()) print(timestamp, sum)
volatility, performance = get_volatility_and_performance(symbol) sum_inverse_volatility += 1 / volatility volatilities.append(volatility) performances.append(performance) print("Portfolio: {}, as of {} (window size is {} days)".format( str(symbols), date.today().strftime('%Y-%m-%d'), window_size)) prices_shares = [] invested = 0 for i in range(len(symbols)): print( '{} allocation ratio: {:.2f}% (anualized volatility: {:.2f}%, performance: {:.2f}%)' .format(symbols[i], float(100 * 1 / volatilities[i] / sum_inverse_volatility), float(volatilities[i] * 100), float(performances[i] * 100))) ratio = float(100 * 1 / volatilities[i] / sum_inverse_volatility) portion = ratio * (total_money) / 100 # print('{} money portion: ${:.2f}'.format(symbols[i] ,portion )) price = si.get_live_price(symbols[i]) share = int(portion / price) prices_shares.append({ "stock": symbols[i], "price": round(price, 2), "shares hold": share }) invested += share * price print(*prices_shares, sep='\n') print("invested money: ", invested)
def lastValue(stockID): return (si.get_live_price(stockID))
me = '*****@*****.**' you = '*****@*****.**' password = '******' config['session'] = True config['api_key'] = "b89559c7df932f3d1173a58e423f0c1634f61651" client = TiingoClient(config) ticker = "AAPL" start_date = datetime.datetime.now() - datetime.timedelta(days=365) end_date = datetime.date.today() # price price = si.get_live_price('{}'.format(ticker)) price = round(price, 2) # volatility, momentum, beta, alpha, r_squared df = DataReader(ticker, 'yahoo', start_date, end_date) dfb = DataReader('^GSPC', 'yahoo', start_date, end_date) 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)
def stock_index(self, stock): price = si.get_live_price(stock) self.engine.say("The current price for " + stock + " is " + str(price) + " dollars") self.engine.runAndWait()
def get_current_price(self): price = si.get_live_price(self.ticker) return price
def update_asset_stats(managed_asset: asset.Asset) -> stats.AssetStats: """Updates stats of given assets. Args: managed_asset: Asset for which to update stats. Returns: Stats of the given asset. """ tracker = managed_asset.get_tracker() price = managed_asset.current_price if not tracker: return stats.StockStats(managed_asset=managed_asset, price=price) try: fetched_price = _parse_and_format_value( stock_info.get_live_price(tracker)) except AssertionError: fetched_price = None if not fetched_price: print(f'{managed_asset.get_id()} price was not updated.') return stats.StockStats(managed_asset=managed_asset, price=price) price = fetched_price managed_asset.current_price = price try: stock_data = stock_info.get_stats(tracker) except Exception: print(f'Unable to update {managed_asset.get_id()} price.') return stats.StockStats(managed_asset=managed_asset, price=price) if stock_data.empty: return stats.StockStats(managed_asset=managed_asset, price=price) try: # TODO: handle all types of assets instead of only stocks. stock_stats = stats.StockStats( managed_asset=managed_asset, price=price, debt_to_equity=_get_stock_stat_value( stock_data, StockAttribute.DEBT_TO_EQUITY), dividend_yield=_get_stock_stat_value( stock_data, StockAttribute.DIVIDEND_YIELD), eps=_get_stock_stat_value(stock_data, StockAttribute.EPS), pe=_get_stock_stat_value(stock_data, StockAttribute.PE), profit_margin=_get_stock_stat_value(stock_data, StockAttribute.PROFIT_MARGIN), return_on_equity=_get_stock_stat_value( stock_data, StockAttribute.RETURN_ON_EQUITY), revenue_growth=_get_stock_stat_value( stock_data, StockAttribute.REVENUE_GROWTH), value_over_ebitda=_get_stock_stat_value( stock_data, StockAttribute.VALUE_OVER_EBITDA), ) managed_asset.stats = stock_stats return stock_stats except Exception: print(f'{managed_asset.get_id()} financial metrics were not updated.') return stats.StockStats(managed_asset=managed_asset, price=price)
def portfolio_Page(): msg = '' sellOrNot = 0.0 totalGain = 0.0 number = 0.0 cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute( 'SELECT * FROM transactions_Table WHERE trading_ID = %s and GameID = %s', (session['id'], session['gameID'])) if request.method == 'GET': cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute( 'SELECT * FROM transactions_Table WHERE numberOfShareSold != numberOfShareAtBuying AND trading_ID = %s and GameID = %s', (session['id'], session['gameID'])) account = cursor.fetchall() if account: # if there is data in here for i in range(0, len(account)): msg = si.get_live_price(account[i]['symbol_Of_Stock']) msg = format(msg, ".2f") account[i]['sellSharePrice'] = msg sellOrNot = float(account[i]['numberOfShareAtBuying']) - float( account[i]['numberOfShareSold']) account[i]['Gain'] = format( (sellOrNot * float(msg) - sellOrNot * float(account[i]['priceOfShareAtBuying'])), ".2f") totalGain = totalGain + float(account[i]['Gain']) totalGain = format(totalGain, ".2f") msg = account return render_template('Portfolio_page.html', account=account, len=len(account), msg=msg, totalGain=totalGain) else: return render_template('Portfolio_page.html', account=account, len=len(account), msg=msg, totalGain=totalGain) else: profitOrLoss = 0.0 post_id = request.form['Sell'] session['Transaction_ID'] = post_id cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute( 'SELECT * FROM transactions_Table WHERE transactions_ID = %s and GameID = %s', (post_id, session['gameID'])) account = cursor.fetchall() if account: for i in range(0, len(account)): number = int(account[i]['numberOfShareAtBuying']) - int( account[i]['numberOfShareSold']) stockID = account[i]['symbol_Of_Stock'] msg = si.get_live_price(account[i]['symbol_Of_Stock']) msg = format(msg, ".2f") account[i]['sellSharePrice'] = msg account[i]['Gain'] = format( (float(account[i]['numberOfShareAtBuying']) * float(msg) - float(account[i]['numberOfShareAtBuying']) * float(account[i]['priceOfShareAtBuying'])), ".2f") profitOrLoss = format(float(account[i]['Gain']), ".2f") stockid, values, time, legend, msg, company_name = getGraph(stockID) return render_template('Sell_stock.html', stockid=stockid, values=values, legend=legend, labels=time, price=msg, number=number, profitOrLoss=profitOrLoss, company_name=company_name) account, len2, msg, totalGain = getTable() return render_template('Portfolio_page.html', account=account, len=len2, msg=msg, totalGain=totalGain)
# load the stock_info module from yahoo_fin from yahoo_fin import stock_info as si # get Apple's live quote price print(si.get_live_price("AAPL")) # or Amazon's print(si.get_live_price("QQQ"))
import sys from yahoo_fin import stock_info as si stock = str(sys.argv[1]) price = si.get_live_price(stock) price_str = str(price) file_price = "E:/Users/chris/Schule/Modul_300/m300_lb/website/python/tmp/price.txt" file_stock = "E:/Users/chris/Schule/Modul_300/m300_lb/website/python/tmp/stock.txt" with open(file_price, 'w') as fileowrite: fileowrite.write(price_str + "<br>") with open(file_stock, 'w') as fileowrite: fileowrite.write(stock + "<br>")
def get_current_stock_value(ticker): warnings.simplefilter('ignore') stock_value = round(stock_info.get_live_price(ticker), 2) return (ticker, datetime.now(), stock_value)
def get_new_history(symbol): import custom_packages.yfinance as yf today = datetime.datetime.now() # define the ticker symbol tickerSymbol = symbol + ".NS" # get data on this ticker tickerData = yf.Ticker(tickerSymbol) # get the historical prices for this ticker # print(tickerData.history) # print(tickerData.quarterly_earnings) past_3_months = today.date() - dateutil.relativedelta.relativedelta( months=18) sbin = tickerData.history(period='1d', start=past_3_months.strftime('%Y-%m-%d'), end=today.date().strftime('%Y-%m-%d')) count = 0 price_list = [] print("GOT TICKER HISTORYYYY ", tickerSymbol) for i, j in sbin.iterrows(): temp_price_list = [] dt_object1 = datetime.datetime.strptime(str(i), "%Y-%m-%d %H:%M:%S") if not dt_object1 == datetime.datetime.now().date(): my_time = dt_object1.time() my_datetime = datetime.datetime.combine(i, my_time) date = datetime.datetime.timestamp(my_datetime) temp_price_list.append(int(date) * 1000) temp_price_list.append(sbin.values.tolist()[count][2]) price_list.append(temp_price_list) count += 1 # print(j,"\n") try: prev_day_price = price_list[len(price_list) - 2][1] today_price = price_list[len(price_list) - 1][1] difference = float(today_price) - float(prev_day_price) except: difference = 0 if difference < 0: color = "#ff9900" else: color = "#00ff39" from nsetools import Nse from yahoo_fin import stock_info as si nse = Nse() data = {} print("NSEEEEEEEEE ", tickerSymbol) # print("_____________ ",nse.get_quote(symbol)) try: # from func_timeout import func_timeout, FunctionTimedOut print("BEFOREEE GET QUOTE ", tickerSymbol) stock_details = tickerData.info #stock_details = nse.get_quote(symbol) # def get_quote_val(symbol): # stock_details = nse.get_quote(symbol) # return stockdata # try: # stock_details = func_timeout(30, get_quote_val, args=(symbol)) # except Exception as e: # print("TIMEOUT ERRORRRRR ",e) # try: # stock_details = nse.get_quote(symbol) # except Exception as e: # print("AGAINNnnnNNNNn TIMEOUT ERRORRRRR ",e) print("AFTERRRRR GET QUOTE ", tickerSymbol) try: base_price = stock_details.get("basePrice", "") companyName = stock_details.get("longName", "") lastPrice = si.get_live_price(symbol + ".NS") except Exception as e: print("GET QUOTE TIME OUT ERROR : ", e) # print (price_list) # symbol = "hdfc" js_resp = get_earnings(symbol) estimate_list = get_earnings_by_type(js_resp, 'epsEstimate', "earnings") print("ESTIMATEEEE LISTTTT ", estimate_list) # estimate_list = get_earnings(symbol, 'epsEstimate', "earnings") actual_list = get_earnings_by_type(js_resp, 'epsActual', "earnings") company_info = get_earnings_by_type(js_resp, "", "company_info") data = { 'stockname': companyName, 'color': color, 'base_price': base_price, 'stockprice': lastPrice, 'stocksymbol': symbol, 'stock_price_list': price_list, 'estimate_list': json.dumps(estimate_list), 'actual_list': json.dumps(actual_list), 'company_info': company_info, } except: data = { 'stockname': '', 'color': color, 'base_price': '', 'stockprice': '', 'stocksymbol': symbol, 'stock_price_list': price_list, 'estimate_list': '', 'actual_list': '', 'company_info': '', } return data
def buyShares(userCapitalVal): userCapital = float(userCapitalVal) portfolioSummary() flag = True print("Buy Shares") print() while (flag): targetStock = input("What stock would you like to buy shares of?: ") try: currPrice = si.get_live_price(targetStock) currPrice = str(currPrice).split('.') try: currPriceDisplay = currPrice[0] + '.' + currPrice[1][ 0] + currPrice[1][1] except: try: curryPriceDisplay = currPrice[0] + '.' + currPrice[1][ 0] + "0" except: currPriceDisplay = currPrice[0] + '.' + "00" print(targetStock, "$" + str(currPriceDisplay)) print() print("1 - Buy", targetStock) print("2 - Main Menu") choice = input() flag = False if choice == '1': print("How may shares of", targetStock, "would you like to purchase") order = input() validInput = order.isdigit() while (validInput == False): print("How may shares of", targetStock, "would you like to purchase") order = input() validInput = order.isdigit() if userCapital >= int(order) * float( currPriceDisplay) and validInput: userCapital = userCapital - int(order) * float( currPriceDisplay) print(userCapital) with open('portfolio.json') as file: portfolio = json.load(file) portfolio['stockNames'].append(targetStock) portfolio['stockPrices'].append( float(currPriceDisplay)) portfolio['shareQuantities'].append(order) with open('portfolio.json', 'w') as file: json.dump(portfolio, file, indent=4) elif userCapital < int(order) * float( currPriceDisplay) and validInput: print( "You do not have enough capital to purchase this amount of stock" ) return userCapital except: main(False, str(userCapital))
grade_list.append(math.nan) current_prices.append(math.nan) df["invest_grades"] = grade_list df["timestamps"] = timestamps df["past_price"] = past_price df["current_price"] = current_prices return df def market_screen(ticker_list): df = pd.DataFrame() df["tickerlist"] = ticker_list grade_list = [] for x in ticker_list: grade_list.append(recommendations(x)) df["invest_grades"] = grade_list return df #past_ticker_table = market_screen_past(tickerlist_short) #past_ticker_table.to_csv("short_ticker_table.csv") x="AACQ" mytime = pd.Timestamp(fclient.recommendation_trends(x)[22]["period"])+pd.Timedelta(days=1) print(Decimal(si.get_data(x).where(si.get_data(x).index.to_series()== mytime).dropna()["close"])) print(recommendations_past(x)) print(si.get_live_price(x)) print(mytime)
def sellShares(userCapitalVal): shareCount = 0 with open('portfolio.json') as file: portfolio = json.load(file) for entry in portfolio["stockNames"]: shareCount += 1 if shareCount == 0: print("You do not have any shares to sell") return userCapitalVal userCapital = float(userCapitalVal) portfolioSummary() tickerToBeSold = input( "Enter the ticker of the stock you would like to sell: ") found = False shareTotal = 0 for index in range(len(portfolio['stockNames'])): if portfolio['stockNames'][index] == tickerToBeSold.upper(): shareTotal += int(portfolio['shareQuantities'][index]) found = True while (not found): tickerToBeSold = input( "Enter the ticker of the stock you would like to sell: ") with open('portfolio.json') as file: portfolio = json.load(file) shareTotal = 0 for index in range(len(portfolio['stockNames'])): if portfolio['stockNames'][index] == tickerToBeSold.upper(): shareTotal += int(portfolio['shareQuantities'][index]) found = True print("You have {} shares of {}".format(shareTotal, tickerToBeSold.upper())) if (shareTotal != 0): invalidInput = True while (invalidInput): print("Would you like to sell any?") print("1 - Yes") print("2 - No") choice = input() if choice == '1' or choice == '2': invalidInput = False if choice == '1': quantityToBeSold = 0 invalidInput = True while (invalidInput): quantityToBeSold = input( "How many of your {} shares of {} would you like to sell? : ". format(shareTotal, tickerToBeSold.upper())) if quantityToBeSold.isdigit(): invalidInput = False currPrice = si.get_live_price(tickerToBeSold) userCapital += float(currPrice) * int(quantityToBeSold) foundEntryListIndex = [] for index in range(len(portfolio["stockNames"])): if portfolio["stockNames"][index] == tickerToBeSold.upper(): foundEntryListIndex.append(index) for entry in foundEntryListIndex: print(shareTotal) print(quantityToBeSold) #The case where quantity of the stock entry is greater than the quantityToBeSold if int(portfolio["shareQuantities"][int(entry)]) > int( quantityToBeSold): print("More shares in one entry") portfolio["shareQuantities"][int(entry)] = int( portfolio["shareQuantities"][int(entry)]) - int( quantityToBeSold) # Finish the loop break #The case where quantity of all stock entries combined is greater than the quantityToBeSold elif shareTotal >= int(quantityToBeSold): if int(portfolio["shareQuantities"][int(entry)]) < int( quantityToBeSold): shareTotal -= int(portfolio["shareQuantities"][int(entry)]) del portfolio["shareQuantities"][int(entry)] del portfolio["stockNames"][int(entry)] del portfolio["stockPrices"][int(entry)] #The case where quantity of the stock entry is equal to the quantityToBeSold elif shareTotal == int(quantityToBeSold): print("Equal to the quantity sold") del portfolio["shareQuantities"][index] del portfolio["stockNames"][index] del portfolio["stockPrices"][index] #Write changes to the json file with open('portfolio.json', 'w') as file: json.dump(portfolio, file, indent=4) #The case where quantity of the stock entry is less than the quantityToBeSold if shareTotal < int(quantityToBeSold): print("You do not have {} shares of {} to sell".format( quantityToBeSold, tickerToBeSold.upper())) if choice == '2': print() mainMenu(userCapital) return userCapital
def checkAlerts(): """ Continuously checks a dictionary of specified alert stocks and prices and sends an alert via cli/email/text if the price of the stock is hit. Params: alerts (Dictionary{int:[string, float, bool, bool]}: a dictionary of stock alerts """ def printAlert(ticker, price): """ Prints/sends the alert message for the specified alert. The alert will be printed on the command line, and/or sent via email and/or text message based on the choices the user has previously made for the 'mode' global Params: value ([string, float, bool, bool]: a dictionary entry value for the alert price (float): the current price of the stock """ #set up server for email/text message port = 465 password = '******' context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server: server.login("*****@*****.**", password) #send out cli alert if (mode["cli"]): #create message for alert message = """ ****************************************** * ALERT * * {0:4} ${1:<9.4f} * ****************************************** """.format(ticker, price) print(message) print(">>", end=' ') #send out email alert to each email if (mode["email"]): message = """\ From: TickerBell\nSubject: New TickerBell Alert\n\n You have 1 new TickerBell Alert! Ticker: {0} Price: ${1:.4f} """.format(ticker, price) for email in emails: server.sendmail("*****@*****.**", email, message) #send out text alert to each number if (mode["text"]): message = """ You have 1 new TickerBell Alert! Ticker: {0} Price: ${1:.4f} """.format(ticker, price) for number in phoneNumbers: server.sendmail("*****@*****.**", number, message) global alerts curtime = time() while (True): for key, value in alerts.items(): #separate input arguments ticker = value[0] alertPrice = value[1] alertIsLess = value[2] alertIsOn = value[3] if alertIsOn: price = si.get_live_price(ticker) if alertIsLess: if (float("{:.4f}".format(price)) <= alertPrice): printAlert(ticker, price) alerts[key][3] = False else: if (float("{:.4f}".format(price)) >= alertPrice): printAlert(ticker, price) alerts[key][3] = False print(">> ", end=' ') while time() <= (curtime + 2): sleep(2) curtime = time()
logging.info('Setting timezone to {}'.format(tz.zone)) count = 0 count_threshold = config.script_config.get('script_count_threshold') try: logging.info('Connecting to InfluxDB using port {}...'.format( config.influxdb_config.get('influxdb_port'))) client = InfluxDBClient(config.influxdb_config.get('influxdb_host'), config.influxdb_config.get('influxdb_port')) client.ping() client.switch_database(config.influxdb_config.get('influxdb_db')) json_body = [config.influxdb_config.get('influxdb_json_body')] logging.info('Connected!') logging.info('Reading stocks value...') while (True): if (9 <= datetime.now().hour < 18): value = stock_info.get_live_price('^mxx') json_body[0]['time'] = '{}'.format(datetime.now(tz)) json_body[0]['fields']['value'] = value client.write_points(json_body) time.sleep(1) count = count + 1 if (count == count_threshold): count = 0 logging.info('Writing without problems') else: logging.info('BMV finished operations for today.') logging.info('Closing connections.') break except Exception as e: print('Error: {}'.format(str(e))) logging.error('Service stoped')