def yahoo_finance_functions(): si.get_data("AAPL") si.get_day_gainers() si.get_day_losers() si.get_day_most_active() si.get_analysts_info("AAPL") stock = si.get_live_price("AAPL")
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()
async def perdedores(ctx): await ctx.send("espera.. OwO") temp = si.get_day_losers().head(10).drop( ["Market Cap", "Volume", "Avg Vol (3 month)"], axis=1) await ctx.send(embed=crearEmbed( ctx, temp, 'Perdedores', 'Lista de top 10 perdedores', 'https://pbs.twimg.com/media/ES9L6NIXQAAFlnO.jpg', 0xFF0000))
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 loser(): losers=get_day_losers() day_loser1=losers['Symbol'] price_day_loser1=losers['Price (Intraday)'] change_day_loser1=losers['% Change'] dl1_tick=(day_loser1[0]) dl1_price=('${:,.2f}'.format(price_day_loser1[0])) dl1_change=('{:.2%}'.format(change_day_loser1[0]/100)) day_loser2=losers['Symbol'] price_day_loser2=losers['Price (Intraday)'] change_day_loser2=losers['% Change'] dl2_tick=(day_loser2[1]) dl2_price=('${:,.2f}'.format(price_day_loser2[1])) dl2_change=('{:.2%}'.format(change_day_loser2[1]/100)) day_loser3=losers['Symbol'] price_day_loser3=losers['Price (Intraday)'] change_day_loser3=losers['% Change'] dl3_tick=(day_loser3[2]) dl3_price=('${:,.2f}'.format(price_day_loser3[2])) dl3_change=('{:.2%}'.format(change_day_loser3[2]/100)) tickers=(f"The top losers are {dl1_tick}, {dl2_tick}, and {dl3_tick}.\n") prices=(f"Their prices are currently {dl1_price}, {dl2_price}, and {dl3_price}.\n") change=(f"Their prices dropped by {dl1_change}, {dl2_change}, and {dl3_change}.") return(tickers+prices+change)
def submit(): if request.method == 'POST': if request.form.get("TopGainers"): top_gainers = si.get_day_gainers() file_name = "TopGainers-"+ str(datetime.today()).split()[0] + '.csv' return Response( top_gainers.to_csv(), mimetype="text/csv", headers={"Content-disposition": f"attachment; filename={file_name}"}) elif request.form.get("TopLosers"): top_losers = si.get_day_losers() file_name = "TopLosers-"+ str(datetime.today()).split()[0] + '.csv' return Response( top_losers.to_csv(), mimetype="text/csv", headers={"Content-disposition": f"attachment; filename={file_name}"}) elif request.form.get("MostActives"): most_active_stock = si.get_day_most_active() file_name = "MostActives-" + str(datetime.today()).split()[0] + '.csv' return Response( most_active_stock.to_csv(), mimetype="text/csv", headers={"Content-disposition": f"attachment; filename={file_name}.csv"})
def getDayMovers(): global gainers, losers, activity, gainerdata, loserdata, activedata gainerdata = pd.DataFrame(si.get_day_gainers())[['Symbol', 'Price (Intraday)', '% Change']] gainerdata['Price (Intraday)'] = "$" + gainerdata['Price (Intraday)'].astype(str) gainerdata['% Change'] = "+" + gainerdata['% Change'].astype(str) + "%" gainerdata['Combined'] = gainerdata[gainerdata.columns[0:]].apply( lambda x: ':'.join(x.dropna().astype(str)), axis=1 ) loserdata = pd.DataFrame(si.get_day_losers())[['Symbol', 'Price (Intraday)', '% Change']] loserdata['Price (Intraday)'] = "$" + loserdata['Price (Intraday)'].astype(str) loserdata['% Change'] = loserdata['% Change'].astype(str) + "%" loserdata['Combined'] = loserdata[loserdata.columns[0:]].apply( lambda x: ':'.join(x.dropna().astype(str)), axis=1 ) activedata = pd.DataFrame(si.get_day_most_active())[['Symbol', 'Price (Intraday)', '% Change']] activedata['Price (Intraday)'] = "$" + activedata['Price (Intraday)'].astype(str) activedata['% Change'] = activedata['% Change'].astype(str) + "%" activedata['Combined'] = activedata[activedata.columns[0:]].apply( lambda x: ':'.join(x.dropna().astype(str)), axis=1 ) # sets the list box data gainers.set('\n'.join(gainerdata['Combined'])) losers.set('\n'.join(loserdata['Combined'])) activity.set('\n'.join(activedata['Combined']))
def Daily_info(): win = yf.get_day_gainers() win = win.sort_values(by='% Change',ascending = False).head(5) lose = yf.get_day_losers() lose = lose.sort_values(by='% Change',ascending = True).head(5) active = yf.get_day_most_active() active = active.head(5) return win,lose,active
def biggestloser(): """Returns: stock with the the biggest losses in a given day and its stock price with format: 'TICKER': 'PRICE'.""" day_losers = si.get_day_losers() output = str(day_losers.at[0, 'Symbol']) + ': ' + str( round(si.get_live_price(day_losers.at[0, 'Symbol']), roundNumber)) return output
def get_bottom_tickers(): bottom_tickers = si.get_day_losers() bottom_array = [] for x in range(10): bottom_array.append((str(bottom_tickers['Symbol'][x]))) return jsonify(bottom_array)
def topl(self): toploss = si.get_day_losers() self.listBox.delete(*self.listBox.get_children()) for x in range(25): self.listBox.insert( "", "end", values=(toploss.loc[x, 'Symbol'], toploss.loc[x, 'Name'], '$' + str(toploss.loc[x, 'Price (Intraday)']), toploss.loc[x, 'Change'], toploss.loc[x, '% Change']))
def worst(update, context): stock_list = si.get_day_losers() output = "Stock Code \t\t\t TTM\n\n" for i in range(0, 10): if math.isnan(stock_list.iloc[i, -1]): ttm_val = "---" else: ttm_val = str(format(stock_list.iloc[i, -1], '.2f')) output += str(i + 1) + ". " + str( stock_list.iloc[i, 0]).upper() + " \t\t\t " + ttm_val + ' \n' print(output) context.bot.send_message(chat_id=update.effective_chat.id, text=output)
def get_stock_movers(number_of): gainers = get_day_gainers() gainers = gainers.head(number_of) gainers = gainers[["Name", "Symbol", "% Change"]] gainers["type"] = "gainer" losers = get_day_losers() losers = losers.head(number_of) losers = losers[["Name", "Symbol", "% Change"]] losers["type"] = "loser" losers = losers.reindex(index=losers.index[::-1]) movers = gainers.append(losers, ignore_index=True) movers = movers.rename(columns={"% Change": "Change"}) return movers
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 Download_pulse(self): self.pulse_result = {} # get most active stocks on the day if asyncio.get_event_loop().is_running( ): # Only patch if needed (i.e. running in Notebook, Spyder, etc) import nest_asyncio nest_asyncio.apply() self.pulse_result['most_active'] = si.get_day_most_active() # get biggest gainers self.pulse_result['gainer'] = si.get_day_gainers() # get worst performers self.pulse_result['loser'] = si.get_day_losers() print('_____________Market Pulse Download Done________________')
def days_loser(self): loser = get_day_losers() df = pd.DataFrame( loser, columns=['Symbol', 'Price (Intraday)', 'Change', '% Change']) df1 = df.head(5) print(df1) data = [] for ind in df1.index: dic = { 'symbol': df1['Symbol'][ind], 'price': df1['Price (Intraday)'][ind], 'change': df1['Change'][ind], 'per_change': df1['% Change'][ind] } data.append(dic) return data
def overview(request): if not Profile.objects.filter(email=request.user.email).exists(): ins = Profile(email=request.user.email) ins.save() if request.user.is_authenticated: if (Buystock.objects.filter(username=request.user.username).exists()): all = Buystock.objects.filter(username=request.user.username) for i in all: from yahoo_fin import stock_info as si r = si.get_live_price(i.ticker) s = Stockd.objects.get(ticker=i.ticker, username=request.user.username) s.lastprice = r s.change = (s.lastprice / s.price) * 100 s.save() if (s.lastprice > s.price): s.type = 'Profit' s.profit = s.quantity * (s.lastprice - s.price) s.change -= 100 elif (s.lastprice < s.price): s.type = 'Loss' s.profit = s.quantity * (s.price - s.lastprice) s.change = 100 - s.change else: s.type = 'Stable' s.profit = 0.00 s.change = 0.00 s.profit = round(s.profit, 2) print(s.profit) s.save() else: messages.warning(request, "Till Now No Stocks are bought") from yahoo_fin import stock_info as si r = si.get_day_most_active().head(5) r.rename(columns={ 'Market Cap': 'Market', 'Price (Intraday)': 'Price' }, inplace=True) json_records = r.reset_index().to_json(orient='records') data = [] data = json.loads(json_records) g = si.get_day_gainers().head(5) g.rename(columns={ 'Market Cap': 'Market', 'Price (Intraday)': 'Price', '% Change': 'change' }, inplace=True) json_records = g.reset_index().to_json(orient='records') datag = [] datag = json.loads(json_records) lost = si.get_day_losers().head(5) lost.rename(columns={ 'Market Cap': 'Market', 'Price (Intraday)': 'Price', '% Change': 'change' }, inplace=True) json_records = lost.reset_index().to_json(orient='records') datal = [] datal = json.loads(json_records) if Stockd.objects.filter(username=request.user.username).exists( ) and Buystock.objects.filter(username=request.user.username).exists(): st = Stockd.objects.filter(username=request.user.username) po = Profile.objects.get(email=request.user.email) return render(request, 'Stock/overview.html', { 'd': st, 'r': data, 'g': datag, 'l': datal, 'pho': po }) else: po = Profile.objects.get(email=request.user.email) return render(request, 'Stock/overview.html', { 'r': data, 'g': datag, 'l': datal, 'pho': po }) else: auth.logout(request) return render(request, 'login/login.html')
######################################################################################## # 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") # 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() ############################################################################################
async def day_losers(ctx): await ctx.send(si.get_day_losers())
from yahoo_fin import stock_info as si from datetime import date, datetime import pandas as pd # gainer si_day_gainer = si.get_day_gainers() si_day_gainer['day_gainer'] = 'day_gainer' si_day_gainer['modified_date'] = datetime.today().strftime('%Y-%m-%d') si_day_gainer.to_csv('data/day_gainer/day_gainer_' + datetime.today().strftime('%Y-%m-%d') + '.csv') # loser si_day_loser = si.get_day_losers() si_day_loser['day_loser'] = 'day_loser' si_day_loser['modified_date'] = datetime.today().strftime('%Y-%m-%d') si_day_loser.to_csv('data/day_loser/day_loser_' + datetime.today().strftime('%Y-%m-%d') + '.csv')
def main(): st.title("Welcome to Predict Future of Stocks.") menu = ["Home", "Stock Prediction using ML"] choice = st.sidebar.selectbox("Menu", menu) if choice == "Home": st.subheader("Recommendations") si.get_day_most_active() st.subheader("Today's Most Active Users") st.write(si.get_day_most_active()) si.get_day_gainers() st.subheader("Today's Top Gainers") st.write(si.get_day_gainers()) si.get_day_losers() st.subheader("Today's Top Losers") st.write(si.get_day_losers()) elif choice == "Stock Prediction using ML": st.subheader("Stock Prediction using ML") START = "2015-01-01" TODAY = date.today().strftime("%Y-%m-%d") selected_stock = st.text_input("Type Stocks's name...") submit = st.button('Search') if submit: si.get_live_price(selected_stock) st.write("Live Price : ", si.get_live_price(selected_stock)) si.get_market_status() st.write("Market state : ", si.get_market_status()) n_years = st.slider("Years of prediction:", 1, 10) period = n_years * 365 def load_data(ticker): data = yf.download(ticker, START, TODAY) data.reset_index(inplace=True) return data data_load_state = st.text('Loading data...') data = load_data(selected_stock) data_load_state.text('Loading data... done!') st.subheader('Raw data') st.write(data.tail()) # Plot raw data def plot_raw_data(): fig = go.Figure() fig.add_trace( go.Scatter(x=data['Date'], y=data['Open'], name="stock_open")) fig.add_trace( go.Scatter(x=data['Date'], y=data['Close'], name="stock_close")) fig.layout.update( title_text='Time Series data with Rangeslider', xaxis_rangeslider_visible=True) st.plotly_chart(fig) plot_raw_data() # Predict forecast with Prophet. df_train = data[['Date', 'Close']] df_train = df_train.rename(columns={"Date": "ds", "Close": "y"}) m = Prophet() m.fit(df_train) future = m.make_future_dataframe(periods=period) forecast = m.predict(future) # Show and plot forecast st.subheader('Forecast data') st.write(forecast.tail()) st.write(f'Forecast plot for {n_years} years') fig1 = plot_plotly(m, forecast) st.plotly_chart(fig1) st.write("Forecast components") fig2 = m.plot_components(forecast) st.write(fig2)
import yfinance as yf from yahoo_fin import stock_info as si import re # def getData(ticker): # while True: # data = yf.Ticker(ticker) # print("Current Price: " + str(data.info['regularMarketPrice'])) # print("Market Open: " + str(data.info['regularMarketOpen'])) # print("Market Close: " + str(data.info['previousClose'])) # print("50 Day Average: " + str(data.info['fiftyDayAverage'])) # print("200 Day Average: " + str(data.info['twoHundredDayAverage'])) # print(data.info) #getData('GME') print("Enter stock ticker: ") ticker = input() print("Current Price: " + str(si.get_live_price(ticker))) # get most active stocks on the day print("Most Active:\n " + str(si.get_day_most_active())) # get biggest gainers print("Biggest Gainers:\n " + str(si.get_day_gainers())) # get worst performers print("Worst performers:\n " + str(si.get_day_losers()))
def getLosers(): x = si.get_day_losers() print(x)
import matplotlib.pyplot as plt from datetime import date import yfinance as yf import pandas as pd from yahoo_fin import stock_info as si import mplcursors symbol1 = "AAPL" stockOne = yf.Ticker(symbol1) dailyData = pd.DataFrame(stockOne.history(period="1d", interval="1m"))['Open'] dailyData.index = dailyData.index.strftime("%H:%M:%S") gainers = pd.DataFrame(si.get_day_gainers())[['Price (Intraday)', '% Change']] gainers.index = pd.DataFrame(si.get_day_gainers())['Symbol'] losers = pd.DataFrame(si.get_day_losers())[['Price (Intraday)', '% Change']] losers.index = pd.DataFrame(si.get_day_losers())['Symbol'] active = pd.DataFrame( si.get_day_most_active())[['Price (Intraday)', '% Change']] active.index = pd.DataFrame(si.get_day_most_active())['Symbol'] print(pd.DataFrame(si.tickers_dow()))
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 getTopLosers(self): topLosers = si.get_day_losers()[0:10] topLosers['volume_change'] = self.yahooFinanceDataModification.getPercentigeChangeInVolume(topLosers) return self.yahooFinanceDataModification.formatTopGainersOrLoosersOrActive(topLosers)
import yahoo_fin.stock_info as si import ftplib, io, json, pandas, requests, requests_html #Top 100 winners today winners = si.get_day_gainers() #Top 100 losers today losers = si.get_day_losers()
def get_worst_performers(): return si.get_day_losers()
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")