def getquote(phenny, input): """.stock <ticker> - Check stock quote""" ticker = input.group(1) if ticker is None: phenny.say('Usage: .stock <ticker>, e.g. .stock kr') return phenny.say('Loading quote...') try: stock = stockquotes.Stock(input.group(1)) except stockquotes.StockDoesNotExistError: phenny.say('I couldn\'t find that stock.') return except Exception as e: phenny.say('An error occurred.') raise e if len(str(stock.currentPrice).split('.')[1]) < 2: price = '{}0'.format(stock.currentPrice) else: price = str(stock.currentPrice) if len(str(stock.increaseDollars).split('.')[1]) < 2: change = '{}0'.format(stock.increaseDollars) else: change = str(stock.increaseDollars) phenny.say('{} - {}'.format(stock.symbol, stock.name)) if stock.increaseDollars > 0: phenny.say('{} [+{} (+{}%)]'.format(price, change, stock.increasePercent)) else: phenny.say('{} [{} ({}%)]'.format(price, change, stock.increasePercent))
def scheduled_job(): global alreadyWarned, threshhold, stocks, prevPrice, stocks print("Updating start of day stock priceing") stocks = db.session.query(models.STOCKS).distinct(models.STOCKS.ticker) prevPrice = {} alreadyWarned = {} for stock in stocks: prevPrice[stock] = stockquotes.Stock(stock).current_price
def check_mentions(api, since_id): logger.info("Retrieving mentions") new_since_id = since_id # for all tweets that account is mentioned in for tweet in tweepy.Cursor(api.mentions_timeline, since_id=since_id).items(): new_since_id = max(tweet.id, new_since_id) if tweet.in_reply_to_status_id is not None: continue # save text of tweet as a string status = api.get_status(tweet.id) tweetString = status.text # call tweet_to_ticker and store in new variable ticker = tweet_to_ticker(tweetString) # try/except getting info from stockquotes try: stockObject = stockquotes.Stock(ticker) stockPrice = stockObject.current_price print(stockPrice) stockIncrease = stockObject.increase_percent print(stockIncrease) logger.info(f"Answering to {tweet.user.name}") #reply with info and image if stockIncrease > 0: message = ticker + " is STONKS today! It's currently trading at $" + str( stockPrice) + ", up " + str( stockIncrease) + "% on the day!" api.update_status( status=message, in_reply_to_status_id=tweet.id ) # for some reason the 'reply feature isn't working, it just prints a normal tweet # still trying to get the image upload to work, using just the text for now #api.media_upload(media='stonks.png', status=message, in_reply_to_status_id=tweet.id) print('4') else: message = ticker + " is NOT STONKS today. It's currently trading at $" + str( stockPrice) + ", down " + str( stockIncrease) + "% on the day." api.update_status(status=message, in_reply_to_status_id=tweet.id) # still trying to get the image upload to work, using just the text for now #api.media_upload(media='notstonks.jpg', status=message, in_reply_to_status_id=tweet.id) except: logger.info(f"Answering to {tweet.user.name}") api.update_status( status= "Uh oh! I didn't recognize that ticker symbol. Please tweet the ticker in ALL CAPS with no other capital letters in the tweet.", in_reply_to_status_id=tweet.id) return new_since_id
def getStockPrices(self, tickers): prices = {} for ticker in tickers: try: info = stockquotes.Stock(ticker) prices[ticker] = info.current_price except: return [False, "Uh oh! Couldn't find " + ticker + ", did you type that correctly?"] return [True, prices]
def buy_stock(self, ticker, shares=1): ticker = ticker.upper() stock = stockquotes.Stock(ticker) if shares * Decimal(stock.current_price) > self.balance: raise NotEnoughError(shares * Decimal(stock.current_price), self.balance) elif stock.current_price <= 0: raise stockquotes.StockDoesNotExistError else: self.stocks[ticker] += shares self.balance -= shares * Decimal(stock.current_price) return shares * Decimal(stock.current_price)
def sell_stock(self, ticker, shares=1): ticker = ticker.upper() stock = stockquotes.Stock(ticker) if shares > self.stocks[ticker]: raise NotEnoughError(shares, self.stocks[ticker]) else: self.stocks[ticker] -= shares self.balance += shares * Decimal(stock.current_price) if self.stocks[ticker] == 0: del self.stocks[ticker] return shares * Decimal(stock.current_price)
def __call__(self): collection = self.db['quotes'] for symbol in self.symbols: print(symbol) if not self._symbol_in_quotes_collection(symbol): self._add_base_object(symbol) for quote in stockquotes.Stock(symbol).historical: collection.update({"symbol": symbol}, {"$addToSet": { "quotes": quote }})
def add_stock_for_user(db: Session, stock: StockCreate, email: str): stock.ticker = stock.ticker.upper() stock_obj = stockquotes.Stock(stock.ticker) current_price = stock_obj.current_price user_id = get_user_by_email(db, email).id db_stock = Stock(**stock.dict(), user_id=user_id, current_price=current_price) db.add(db_stock) db.commit() db.refresh(db_stock) return db_stock
def home(): american = stockquotes.Stock('AAL') americanPrice = american.current_price if request.form: comment = Comment(comment=request.form.get("comment"), name=request.form.get("name")) db.session.add(comment) db.session.commit() comments = Comment.query.all() return render_template('home.html', comments=comments, americanPrice=americanPrice)
def manage(): if request.form: comment = request.form.get("comment") comment = Comment.query.filter_by(comment=comment).first() db.session.delete(comment) db.session.commit() comments = Comment.query.all() american = stockquotes.Stock('AAL') americanPrice = american.current_price return render_template('manage.html', comments=comments, americanPrice=americanPrice)
def bad_break_sell_rule(symbol, price_tolerance=0.05, volume_tolerance=1.0): stock = stockquotes.Stock(symbol) curr_price = stock.current_price prev_price = stock.historical[1]['close'] curr_vol = stock.historical[0]['volume'] prev_vol = stock.historical[1]['volume'] percent_gain_price = (curr_price - prev_price) / prev_price percent_gain_vol = (curr_vol - prev_vol) / prev_vol if percent_gain_price <= price_tolerance and percent_gain_vol >= volume_tolerance: print("Sell Based on Bad Break Sell Rule") return True else: print("Do Not Sell Based on Bad Break Sell Rule") return False
def request_ticker_history(data): print(data["ticker"]) ticker = data["ticker"] try: stock = stockquotes.Stock(ticker) except stockquotes.StockDoesNotExistError: return None history = stock.historical final = {} volume = {} for i in history: date = i["date"].strftime("%Y-%m-%d") data = [i["open"], i["high"], i["low"], i["close"]] final[date] = data volume[date] = i["volume"] response = {"final": final, "volume": volume} return response
def get_money(stock_list, list_of_prices, money): #divides money evenly among stocks stock_money = money / len(stock_list) dict = {} list = [] count = 0 # today = datetime.datetime.now() # today = today.strftime("%Y-%m-%d") for stock in stock_list: # share = Share(stock) #stock_price = yf.download(stock, start=today, end=today) stock_obj = stockquotes.Stock(stock) stock_price = stock_obj.current_price # stock_price = stock_price['Open'].values[0] #print(stock_price) num_of_shares = stock_money / float(stock_price) list_of_stock = list_of_prices[count] #print(list_of_stock) # i = 1 for date, price in list_of_stock.items(): uprice = num_of_shares * price # s = str(i) if (date in dict.keys()): dict[date] = dict[date] + uprice else: dict[date] = uprice #i+=1 count += 1 for key, value in dict.items(): new_dict = {} new_dict[key] = value list.append(new_dict) return list #num_of_months = 5 # low_risk_stock_list = ['TDTF', 'BIV', 'PZA'] #medium_risk_stock_list = ['GOOGL', 'URI', 'MSFT'] #high_risk_stock_list = ['TSLA', 'AMZN', 'NVDA', 'AAPL'] #list_of_prices = get_list_of_prices(high_risk_stock_list, num_of_months) #print(list_of_prices) #temp_list = [{'2020-11-01': 444.58105600107984, '2020-12-01': 476.3930626472659, '2021-01-01': 513.7873154199672, '2021-02-01': 551.9584350369109, '2021-03-01': 576.6159015623272}, {'2020-11-01': 3314.3813289361915, '2020-12-01': 3403.458750136123, '2021-01-01': 3471.237244499922, '2021-02-01': 3643.584211818914, '2021-03-01': 3689.151627413864}, {'2020-11-01': 549.3280722258825, '2020-12-01': 562.9468660336015, '2021-01-01': 587.3330001816589, '2021-02-01': 609.6957059514913, '2021-03-01': 621.3325014357209}, {'2020-11-01': 123.39610206550843, '2020-12-01': 124.17790857381368, '2021-01-01': 127.15492871073009, '2021-02-01': 131.13093697525866, '2021-03-01': 131.60752995602556}] #money = get_money(high_risk_stock_list, temp_list, 50) #print(money)
def timed_job(): print(f"\nStarting Stock Price Checks {datetime.datetime.now()}") global alreadyWarned, threshhold, stocks, prevPrice, stocks for stock in stocks: curr = stockquotes.Stock(stock).current_price prev = prevPrice[stock] print( f"Starting Day {stock} Price: {prev} Current {stock} Price : {curr} Top Threashold {prev*(1+threshhold)} Bot Threshold {prev*(1-threshhold)}" ) if (curr > prev * (1 + threshhold)) or (curr < prev * (1 - threshhold)): warnUsers = (db.session.query(models.STOCKS.username_id).filter( models.STOCKS.ticker == stock).all()) warnNumbers = [] for userID in warnUsers: if userID in alreadyWarned.keys(): if stock in alreadyWarned[userID]: pass else: alreadyWarned[userID].append(stock) userCell = (db.session.query( models.USERS.username).filter( models.USERS.username_id == userID).all()) userCell = userCell[0][0] warnNumbers.append(userCell) else: alreadyWarned[userID] = [stock] userCell = (db.session.query(models.USERS.username).filter( models.USERS.username_id == userID).all()[0]) userCell = userCell[0] warnNumbers.append(userCell) print("sent a message about", stock, "to", warnNumbers) SendText.massText( warnNumbers, "PaperBull Notification", f"{stock} has had a significant change, you should look into it! https://paperbull.herokuapp.com/", )
import models db.create_all() threshhold = 0.03 stocks = db.session.query(models.STOCKS.ticker).distinct( models.STOCKS.ticker).all() prevPrice = {} tmp = [] for i in stocks: tmp.append(i[0]) stocks = tmp for stock in stocks: try: prevPrice[stock] = stockquotes.Stock(stock).current_price except: pass alreadyWarned = {} sched = BlockingScheduler() print(f"Starting Clock {datetime.datetime.now()}") @sched.scheduled_job("interval", minutes=1) def timed_job(): print(f"\nStarting Stock Price Checks {datetime.datetime.now()}") global alreadyWarned, threshhold, stocks, prevPrice, stocks for stock in stocks: curr = stockquotes.Stock(stock).current_price prev = prevPrice[stock]
for language in all_languages: disp_info = f"{language[0]}, {language[1]}, \t {language[2]}" print(disp_info) # Checks if the user provided stock argument if stock: print("-----------------------------------------") try: stock = str(stock) stock = stock.upper() except Exception as e: print(e) else: try: # Obtains the curent stock price for the provided stock symbol stock_price = stockquotes.Stock(stock).current_price except stockquotes.StockDoesNotExistError as sde: print(f"Stock {stock} does not exist.") except stockquotes.NetworkError as sn: print("Could not establish a network connection") except Exception as ex: print("Could not obtain the stock. Please check your internet connection") else: print("Stock price in USD", stock_price) default_text = f"The current price for {stock} is " # A boolean flag for determining whether the user's preferred currency should be diplayed currency_flag = False # Checks if the user provided the preferred currency if preferred_currency: preferred_currency = preferred_currency.upper()
engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) db = SessionLocal() smtpObj = smtplib.SMTP_SSL("smtp.gmail.com", 465) email = os.getenv("EMAIL_ADDRESS", "your-email-address") password = os.getenv("EMAIL_PASSWORD", "your-email-password") smtpObj.login(email, password) for ticker in db.query(Stock.ticker).distinct(): symbol = ticker[0] current_price = stockquotes.Stock(symbol).current_price symbol_stocks = db.query(Stock).filter(Stock.ticker == symbol) for stock in symbol_stocks: if stock.mode == "buy" and stock.price > current_price: subject = f"Buy {stock.ticker} Now!" text = ( f"Hello,\n\nThe price for {stock.ticker} is now below your requested price" + f" of ${stock.price:.2f}. It is currently at ${current_price:.2f}.\n\n" + "Love you,\nAang") message = "Subject: {}\n\n{}".format(subject, text) try: smtpObj.sendmail(email, stock.user.email, message)
return '{}0'.format(amount) else: return amount with open('portfolio.json') as f: portfolio = json.load(f) portfolio_data = [] for stock in portfolio.keys(): if portfolio[stock] == 0: continue elif stock == 'CASH': cash = portfolio[stock] else: stock_data = stockquotes.Stock(stock) portfolio_data.append( [stock, portfolio[stock], stock_data.currentPrice]) total = sum([i[1] * i[2] for i in portfolio_data]) + cash longest_qty = 3 for stock in portfolio_data: length = len(money(stock[1])) longest_qty = length if length > longest_qty else longest_qty longest_stock = 5 for stock in portfolio_data: length = len(stock[0]) longest_stock = length if length > longest_stock else longest_stock
def getStocks(): # start timer startTime = datetime.now() importlib.reload(sap) from tickerList import tickers # create dateString to get the date for the sheet dateString = datetime.strftime(datetime.now(), '%Y_%m_%d') # sort tickers, not sure why, but I did tickers = sorted(tickers) # ticker.info is used from yf to create a json that I can pull from # called for each ticker in the list # store that json as its own variable and pull the data # stockquotes module is used to get the current price of the ticker object stock_df = pd.DataFrame() index = 1 for ticker in tickers: try: ticker_df = sap.pullStocks(ticker) stockObj = stockquotes.Stock(ticker) currentPrice = stockObj.current_price ticker_df['Price'] = currentPrice # current price is not being added here stock_df = stock_df = stock_df.append(ticker_df, ignore_index=True) print(index, ticker) index += 1 except Exception: pass stock_df = stock_df.dropna(axis=1, how='all') stock_df.fillna('', inplace=True) stock_df = stock_df.applymap(str) # need to change 52WeekChange column name because BigQuery does not like # columns that start with numbers stock_df = stock_df.rename(columns={'52WeekChange': 'WeekChange52'}) tickerCount = len(stock_df.index) tickerCount = '{:,}'.format(tickerCount) print(f'Pulled {tickerCount} stocks on {dateString}'.format(tickerCount)) # gc authorizes and lets us access the spreadsheets gc = gspread.oauth() # create the workbook where the day's data will go # add in folder_id to place it in the folder we want sh = gc.create(f'Stock sheet as of {dateString}', folder_id=valueStockFolderId) # access the first sheet of that newly created workbook worksheet = sh.get_worksheet(0) # edit the worksheet with the created dataframe for the day's data worksheet.update([stock_df.columns.values.tolist()] + stock_df.values.tolist()) range_of_cells = worksheet.range('A1:CZ10000') worksheet.update_cells(range_of_cells, value_input_option='USER_ENTERED') # open the main workbook with that workbook's url db = gc.open_by_url(dashboardURL) # changed this over to the second sheet so the dashboard can be the first sheet # dbws is the database worksheet, as in the main workbook that is updated and # used to analyze and pick from dbws = db.get_worksheet(1) # below clears the stock sheet so it can be overwritten with updates # z1000 is probably overkill but would rather over kill than underkill range_of_cells = dbws.range('A1:CU10000') for cell in range_of_cells: cell.value = '' dbws.update_cells(range_of_cells) # update the stock spreadsheet in the database workbook with the stock_df # need to specify this as user entered to keep the data type dbws.update([stock_df.columns.values.tolist()] + stock_df.values.tolist()) # unstringify the strung data for SQL purposes spreadsheetId = dbId # Please set the Spreadsheet ID. sheetName = "Data" # Please set the sheet name. spreadsheet = gc.open_by_key(spreadsheetId) sheetId = spreadsheet.worksheet(sheetName)._properties['sheetId'] requests = { "requests": [{ "findReplace": { "sheetId": sheetId, "find": "^'", "searchByRegex": True, "includeFormulas": True, "replacement": "" } }] } spreadsheet.batch_update(requests) # output total time to run this script print(datetime.now() - startTime)
from pprint import pprint # Using Alpha Vantage API to get current price stock: ts = TimeSeries(key=' WDT25OH0Y4H4S4Y9', output_format='pandas') data, meta_data = ts.get_intraday(symbol='MSFT', interval='1min', outputsize='full') # Get the most recent price: dynatraceCurrentStockPrice = data['4. close'][0] #Get stock price every minute: while (1): # For the sake of speed and simplicity, just pull from stockquotes: dynatrace = stockquotes.Stock('DY') dynaPrice = str(dynatrace.current_price) timeNow = str( math.floor(datetime.datetime.utcnow().timestamp() * 1000) - 14300000) print("Current Price: $" + dynaPrice) print("Time in milliseconds: " + timeNow) #CURL and POST metrics to the custom device "DynatraceStock" headers = { 'Authorization': 'Api-Token --', 'Content-Type': 'application/json', } data = '{ "tags": [ "tag2" ], "type": "Stock-Price", "properties" : { "Dynatrace Stock Price": "USD" }, "series" : [ { "timeseriesId" : "custom:dynatrace.stock.price","dimensions" : { "nic" : "finance"},"dataPoints" : [ [ ' + timeNow + ',' + dynaPrice + ' ] ] } ] }' response = requests.post(
def stockrate(name): stockname = stockquotes.Stock(name) print(stockname) stockprice = stockname.current_price print(stockprice) return (stockprice)
def get_stock_info(stock_syml): return stockquotes.Stock(stock_syml)
import stockquotes kroger = stockquotes.Stock('SLB') krogerPrice = kroger.current_price print(krogerPrice) bitcoin = stockquotes.Stock('BTC-USD') bitcoinPrice = bitcoin.current_price print(bitcoinPrice)
def _options_data_parser(self, ticker): # Options_data is a dictionary with all the necessary data now = dt.datetime.now() thirty_forward_date = now + dt.timedelta(30) # Obtaining data from the yahoo finance API ticker_api = yf.Ticker(ticker) try: ticker_info = ticker_api.info try: price = ticker_info['regularMarketPrice'] except KeyError: price = ticker_info except: ticker_api_backup = stockquotes.Stock(ticker) price = ticker_api_backup.current_price # Obtaining the options expiration dates from the yahoo finance API options_expirations = ticker_api.options # Searching for optimal near term date near_term_date = [] for d in options_expirations: d = dt.datetime.strptime(d, '%Y-%m-%d') if d <= thirty_forward_date: near_term_date.append(d) near_term_date = near_term_date[-1] # Searching for optimal next term date next_term_date = [] for d in options_expirations: d = dt.datetime.strptime(d, '%Y-%m-%d') if d > thirty_forward_date: next_term_date.append(d) next_term_date = next_term_date[0] # Using the yfinance api near_term_options = ticker_api.option_chain(str(near_term_date.date())) next_term_options = ticker_api.option_chain(str(next_term_date.date())) # Generating contract name based on options naming conventions (UNFINISHED) ''' near_term_options_contract = f"{ticker}" + next_term_options_contract ''' # Using eodoptionsdata api (UNFINISHED) ''' near_term_options_request_url = https://eodhistoricaldata.com/api/options/AAPL.US?api_token={your_api_key} next_term_options_request_url = https://eodhistoricaldata.com/api/options/AAPL.US?api_token={your_api_key} ''' options_data = { 'now': now, 'thirty_forward_date': thirty_forward_date, 'near_term_date': near_term_date, 'next_term_date': next_term_date, 'price': price, 'options_expirations': options_expirations, 'near_term_options': near_term_options, 'next_term_options': next_term_options, } return options_data
def get_stock(stock, portfolio_data): stock_data = stockquotes.Stock(stock) portfolio_data.append([stock, portfolio[stock], stock_data.currentPrice])
dateString = datetime.strftime(datetime.now(), '%Y_%m_%d') # sort tickers, not sure why, but I did tickers = sorted(tickers) # ticker.info is used from yf to create a json that I can pull from # called for each ticker in the list # store that json as its own variable and pull the data # stockquotes module is used to get the current price of the ticker object stock_df = pd.DataFrame() index = 1 for ticker in tickers: try: ticker_df = sap.pullStocks(ticker) stockObj = stockquotes.Stock(ticker) currentPrice = stockObj.current_price ticker_df['Price'] = currentPrice # current price is not being added here stock_df = stock_df = stock_df.append(ticker_df, ignore_index=True) print(index, ticker) index += 1 except Exception: pass stock_df = stock_df.dropna(axis=1, how='all') stock_df.fillna('', inplace=True) stock_df = stock_df.applymap(str) # need to change 52WeekChange column name because BigQuery does not like # columns that start with numbers stock_df = stock_df.rename(columns={'52WeekChange': 'WeekChange52'})
def get_stock_history(self, stock): try: return stockquotes.Stock(stock).historical except stockquotes.StockDoesNotExistError: return None
def helper_get_stock_price(stock): """This method is depreciated use StockDataAccess""" try: return stockquotes.Stock(stock).current_price except stockquotes.StockDoesNotExistError: return None
def helper_get_stock_price(stock): try: return stockquotes.Stock(stock).current_price except stockquotes.StockDoesNotExistError: return None
async def price(ctx, ticker: str): ticker = ticker.upper() stock = stockquotes.Stock(ticker) await ctx.send("{}, the price of {} is {} KhalilCoin™ per share".format( ctx.author.mention, ticker, stock.current_price))