def import_yahoofinance2(): # import stock_info module from yahoo_fin from yahoo_fin import stock_info as si # get live price of Apple si.get_live_price("aapl") # or Amazon si.get_live_price("amzn") # or any other ticker si.get_live_price(ticker) # get quote table back as a data frame si.get_quote_table("aapl", dict_result = False) # or get it back as a dictionary (default) si.get_quote_table("aapl") si.get_top_crypto() # get most active stocks on the day si.get_day_most_active() # get biggest gainers si.get_day_gainers() # get worst performers si.get_day_losers()
def post_market(self): root = {} root["market"] = {} """ Market Node """ day_gainers = si.get_day_gainers().to_dict(orient="dict") day_losers = si.get_day_losers().to_dict(orient="dict") top_crypto = si.get_top_crypto().to_dict(orient="dict") most_active = si.get_day_most_active().to_dict(orient="dict") new_node = {"Day_Gainers" : day_gainers, "Day_Losers" : day_losers, "Top_Crypto" : top_crypto, "Most_Active" : most_active} for node_key in new_node.keys(): now = str(datetime.date(datetime.now())) key_var = now self.post(key_var, new_node[node_key], "Market", node_key) time.sleep(.5) print('Sucess\n')
def topcrypto(): """Returns: cryptocurrency with the highest price in a given day and its name with format: 'CRYPTO': 'PRICE'.""" top_crypto = si.get_top_crypto() output = str(top_crypto.at[0, 'Symbol']) + ': ' + str( round(si.get_live_price(top_crypto.at[0, 'Symbol']), roundNumber)) return output
def tab_crypto(): new_tab = [] tab = si.get_top_crypto() tab = np.array(tab) for i in tab: array = np.array(i) new_tab.append([array[0], array[1]]) return new_tab
def ethereum_change(): crypt=get_top_crypto() ethereum=crypt['Name'] ethereum_price=crypt['Price (Intraday)'] ethereum_change=crypt['% Change'] if ethereum_change[0] >=0: result='up' else: result='down' return(f"{ethereum[1]} is trading at {'${:,.2f}'.format(ethereum_price[1])}, {result} {'{:.2%}'.format(ethereum_change[1]/100)}.")
def bitcoin_change(): crypt=get_top_crypto() bitcoin=crypt['Name'] bitcoin_price=crypt['Price (Intraday)'] bitcoin_change=crypt['% Change'] if bitcoin_change[0] >=0: result='up' else: result='down' return(f"{bitcoin[0]} is trading at {'${:,.2f}'.format(bitcoin_price[0])}, {result} {'{:.2%}'.format(bitcoin_change[0]/100)}.")
def functions_type(): #VERIF TAILLE DU TABLEAU if var_text.get() > 0 and var_text.get() < 101: if type_ == "stock_gainers": tab = si.get_day_gainers() elif type_ == "stock_losers": tab = si.get_day_losers() elif type_ == "crypto": tab = si.get_top_crypto() else: print("error1") #convert in table tab = np.array(tab) affichage_tab(tab)
def main(): # creating object of TwitterClient Class q_word = "BTC" api = TwitterClient() output = [] i = 0 #Section to run in a loop # calling function to get tweets while (i < 480): #print("Mining Tweets") tweets = api.get_tweets(query=q_word, count=100) #print("Example of a tweet") #print(tweets[0]) #print(len(tweets)) BTC = si.get_top_crypto() btcp = BTC["Price (Intraday)"].tolist() btcp = btcp[0] #print(btcp) # picking positive tweets from tweets ptweets = [ tweet for tweet in tweets if tweet['sentiment'] == 'positive' ] # percentage of positive tweets #print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets))) # picking negative tweets from tweets ntweets = [ tweet for tweet in tweets if tweet['sentiment'] == 'negative' ] # percentage of negative tweets #print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets))) # percentage of neutral tweets #print("Neutral tweets percentage: {} % \ # ".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets))) #Calculate Summary Stats to Save ptweetp = 100 * len(ptweets) / len(tweets) ntweetp = 100 * len(ntweets) / len(tweets) dtg = datetime.now() myTup = (btcp, ptweetp, ntweetp, dtg) print(myTup) output.append(myTup) time.sleep(60) i = i + 1 print("Loop Complete") print(output) # printing first 5 positive tweets print("\n\nPositive tweets:") for tweet in ntweets[:10]: print(tweet['text']) # printing first 5 negative tweets print("\n\nNegative tweets:") for tweet in ntweets[:10]: print(tweet['text']) #Save to a pickle with open('outputBTC.txt', 'wb') as fp: pickle.dump(output, fp)
def btc_price(self): top = si.get_top_crypto() btc = top['Symbol'][0] price = top['Price (Intraday)'][0] self.engine.say("The current price of Bitcoin is " + str(price)) self.engine.runAndWait()
async def on_message(message): print(message.content) if message.content.find("!") != -1: content = message.content.strip('!').lower().split() print(content) print(content[0]) if content[0] == "day": if content[1] == "gain": await message.channel.send( si.get_day_gainers().head(10).iloc[:, :3]) await message.channel.send( "-------------------------------------------") await message.channel.send( si.get_day_gainers().head(10).iloc[:, 4:7]) elif content[1] == "lose": await message.channel.send( si.get_day_losers().head(10).iloc[:, :3]) await message.channel.send( "-------------------------------------------") await message.channel.send( si.get_day_losers().head(10).iloc[:, 4:7]) elif content[1] == "active": await message.channel.send( si.get_day_most_active().head(10).iloc[:, :3]) await message.channel.send( "-------------------------------------------") await message.channel.send( si.get_day_most_active().head(10).iloc[:, 4:7]) elif content[0] == "crypto": await message.channel.send(si.get_top_crypto().head(10).iloc[:, :3] ) await message.channel.send( "-------------------------------------------") await message.channel.send(si.get_top_crypto().head(10).iloc[:, 4:5]) elif content[0] == "help": embedVar = discord.Embed(title="List of functioning commands", description="", colour=0x00ff00) embedVar.add_field(name="\u200b", value="!tsla\n!day gain\n!day loss", inline=True) embedVar.add_field( name="\u200b", value="!calls tlsa 03/19/2021\n!puts tlsa 03/19/2021", inline=True) await message.channel.send(embed=embedVar) elif content[0] == "calls": await message.channel.send( op.get_calls(content[1], content[2]).iloc[:, 2:8]) elif content[0] == "puts": await message.channel.send( op.get_puts(content[1], content[2]).iloc[:, 2:8]) else: temp = si.get_quote_table(content[0]) change = round(temp["Quote Price"] - temp["Previous Close"], 2) percentage = round(change / temp["Previous Close"] * 100, 2) displayQuote = str(round(temp["Quote Price"], 2)) displayChange = str(change) displayPercentage = str(percentage) displayTicker = content[0].upper() displayClose = str(round(temp["Previous Close"], 2)) dayRange = temp["Day's Range"].replace('-', '').split() dayLow = dayRange[0] dayHigh = dayRange[1] open = temp["Open"] close = temp["Previous Close"] volume = str(round(temp["Volume"] / 1000000, 2)) volume = volume + "M" avgVolume = str(round(temp["Avg. Volume"] / 1000000, 2)) avgVolume = avgVolume + "M" bid = temp["Bid"] ask = temp["Ask"] if change >= 0: rgb = 0x00ff00 displayChange = "+" + displayChange displayPercentage = "+" + displayPercentage else: rgb = 0xff0000 embedVar = discord.Embed( title= f"${displayTicker}\n${displayQuote} {displayChange} ({displayPercentage}%)", description="", colour=rgb) embedVar.add_field( name="\u200b", value= f"High: {dayHigh}\nLow: {dayLow}\n\nAsk: {ask}\nBid: {bid}", inline=True) embedVar.add_field(name="\u200b", value=f"Open: {open}\nPrev.: {close}", inline=True) embedVar.add_field( name="\u200b", value=f"Volume: {volume}\nAvg. Vol.: {avgVolume}", inline=True) await message.channel.send(embed=embedVar)
def getTopCrypto(self): #TODO topCrypto = si.get_top_crypto()[0:10] return topCrypto
def main(): #Initialize userInput = '' #Program will run until 5 is entered while userInput != "5": userInput = mainMenu() #Look up Stock if userInput == "1": #Initialize subSelect = '' #Get symbol, validate, print current price, opening price, previous close symbol = getStock() if symbol != 'Q': quoteTable = si.get_quote_table(symbol) print("Current price: $", round(si.get_live_price(symbol), 3), " as of", currentTime()) print("Opening price: $", quoteTable['Open'], \ "\nPrevious closing price: $", quoteTable['Previous Close']) #Stay on submenu until 5 is entered while subSelect != '5': subSelect = subMenu() #Get date range and plot historical price if subSelect == '1': selection = 'Y' while selection == 'Y': plot(getStockData(symbol), "index", "close", "Price ($)") selection = input( "Would you like to enter a new set of dates? (Y/N) " ) #Get date range and plot historical volume if subSelect == '2': selection = 'Y' while selection == 'Y': plot(getStockData(), "index", "volume", "Volume ") selection = input( "Would you like to enter a new set of dates? (Y/N) " ) #Add stock to a watchlist if subSelect == '3': columns = ['Name'] #Try to open existing watchlist and add stock to it try: watchlist = pd.read_csv("watchlist.csv", header=0, delim_whitespace=True) add = pd.DataFrame([symbol], index=None, columns=columns) watchlist = watchlist.append(add, True) watchlist.to_csv('watchlist.csv', index=False) #Create new watchlist file and add stock to it except: add = pd.DataFrame([symbol], index=None, columns=columns) add.to_csv('watchlist.csv', index=False) print("This stock has been added to your watchlist\n") #Update the live price if subSelect == '4': print("Current price: $", round(si.get_live_price(symbol), 3), " as of", currentTime()) #Print Watchlist if userInput == "2": #Try to open watchlist. Look up live price for each stock on the list. print the resulting Dataframe try: watchlist = pd.read_csv("watchlist.csv", header=0, delim_whitespace=True) npWatchlist = watchlist.to_numpy() price = [] for i in range(0, len(npWatchlist)): price.append(round(si.get_live_price(npWatchlist[i][0]), 3)) watchlist['price'] = price watchlist = watchlist.set_index('Name') print(watchlist) #Error message if watchlist does not exist except: print( "Watchlist is currently empty. Feel free to add stocks to your watchlist under the Look up Stock option in the main menu" ) #Prints top 10 gainers and losers if userInput == "3": #Gainers Losers gainers = si.get_day_gainers() deleteData = [ 'Change', 'Volume', 'Avg Vol (3 month)', 'Market Cap', 'PE Ratio (TTM)' ] print("Top Gainers\n") dfTrimmer(gainers, deleteData) losers = si.get_day_losers() print("\nTop Losers\n") dfTrimmer(losers, deleteData) #Prints top 10 crypto by market cap if userInput == "4": crypto = si.get_top_crypto() delete = [ "Market Cap", "Volume in Currency (Since 0:00 UTC)", 'Volume in Currency (24Hr)', 'Total Volume All Currencies (24Hr)', 'Circulating Supply' ] print("The top 10 Cryptocurrencies by Market Cap:") dfTrimmer(crypto, delete) #If user enters invalid input elif userInput != '5' and userInput != '1' and userInput != '2' and userInput != '3' and userInput != '4': print("Selection not recognized try again")