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()
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 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 get_stocks(): arr = [] gainers = si.get_day_gainers().head(5) tickers = gainers.Symbol for i in tickers: arr.append(i) return arr
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 gainer(): gainers=get_day_gainers() day_gainer1=gainers['Symbol'] price_day_gainer1=gainers['Price (Intraday)'] change_day_gainer1=gainers['% Change'] dg1_tick=(day_gainer1[0]) dg1_price=('${:,.2f}'.format((price_day_gainer1[0]))) dg1_change=('{:.2%}'.format(change_day_gainer1[0])) day_gainer2=gainers['Symbol'] price_day_gainer2=gainers['Price (Intraday)'] change_day_gainer2=gainers['% Change'] dg2_tick=(day_gainer2[1]) dg2_price=('${:,.2f}'.format(price_day_gainer2[1])) dg2_change=('{:.2%}'.format(change_day_gainer2[1])) day_gainer3=gainers['Symbol'] price_day_gainer3=gainers['Price (Intraday)'] change_day_gainer3=gainers['% Change'] dg3_tick=(day_gainer3[2]) dg3_price=('${:,.2f}'.format(price_day_gainer3[2])) dg3_change=('{:.2%}'.format(change_day_gainer3[2])) tickers=(f"The top gainers are {dg1_tick}, {dg2_tick}, and {dg3_tick}.\n") prices=(f"Their prices are currently {dg1_price}, {dg2_price}, and {dg3_price}.\n") change=(f"Their prices rose by {dg1_change}, {dg2_change}, and {dg3_change}.") print(tickers+prices+change)
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
async def ganadores(ctx): await ctx.send("espera.. OwO") temp = si.get_day_gainers().head(10).drop( ["Market Cap", "Volume", "Avg Vol (3 month)"], axis=1) await ctx.send(embed=crearEmbed( ctx, temp, 'Ganadores', 'Lista de top 10 Ganadores', 'https://wompampsupport.azureedge.net/fetchimage?siteId=7575&v=2&jpgQuality=100&width=700&url=https%3A%2F%2Fi.kym-cdn.com%2Fentries%2Ficons%2Ffacebook%2F000%2F029%2F959%2FScreen_Shot_2019-06-05_at_1.26.32_PM.jpg', 0x00FF00))
def biggestgainer(): """Returns: stock with the biggest gains in a given day and its stock price with format: 'TICKER': 'PRICE'.""" day_gainer = si.get_day_gainers() output = str(day_gainer.at[0, 'Symbol']) + ': ' + str( round(si.get_live_price(day_gainer.at[0, 'Symbol']), roundNumber)) return output
def get_top_tickers(): top_tickers = si.get_day_gainers() top_array = [] for x in range(10): top_array.append((str(top_tickers['Symbol'][x]))) return jsonify(top_array)
def get_top_gainers(): top_gainers = si.get_day_gainers() for x in range(10): print( str(x + 1) + '.\n' + str(top_gainers['Symbol'][x]) + '\nName: ' + str(top_gainers['Name'][x]) + '\nPrice (Intraday): $' + str(top_gainers['Price (Intraday)'][x]) + '\nChange ($): +$' + str(top_gainers['Change'][x]) + '\nPercent Change: +' + str(top_gainers["% Change"][x]) + "%\n")
def best(update, context): stock_list = si.get_day_gainers() 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 topg(self): topgain = si.get_day_gainers() self.listBox.delete(*self.listBox.get_children()) for x in range(25): self.listBox.insert( "", "end", values=(topgain.loc[x, 'Symbol'], topgain.loc[x, 'Name'], '$' + str(topgain.loc[x, 'Price (Intraday)']), '+' + str(topgain.loc[x, 'Change']), topgain.loc[x, '% Change']))
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 __init__(self): self.alpaca = tradeapi.REST(API_KEY, API_SECRET, APCA_API_BASE_URL, 'v2') gainers = si.get_day_gainers() gainers.columns = [ 'SYM', 'Company', 'Current Price', 'Price Change', 'Percentage Change', 'Volume', 'Avg Vol', 'Market Cap', '52 Week Range' ] gainers.sort_values("Price Change", axis=0, ascending=False, inplace=True) end = datetime.date.today() start = end - datetime.timedelta(days=200) stock_watchlist = [] for stock in gainers['SYM']: s_hist_data = si.get_data(stock, start_date=str(start), end_date=str(end)) var = s_hist_data.mean(axis=0, skipna=True) avg = (float(var[0]) + float(var[1])) / 2 curr_price = si.get_live_price(stock) if (avg < curr_price): stock_watchlist.append(stock) stockUniverse = stock_watchlist print("Stock Universe for the day:", stockUniverse) # Format the allStocks variable for use in the class. self.allStocks = [] for stock in stockUniverse: self.allStocks.append([stock, 0]) self.long = [] self.short = [] self.qShort = None self.qLong = None self.adjustedQLong = None self.adjustedQShort = None self.blacklist = set() self.longAmount = 0 self.shortAmount = 0 self.timeToClose = None
def main(): print("hey") names = [] prices = [] changes = [] percentChanges = [] marketCaps = [] totalVolumes = [] circulatingSupplys = [] result = requests.get(url) soup = Bsoup(result.content, 'html.parser') print("Haefd") for listing in soup.find_all( 'tr', attrs= { 'class': 'simpTblRow Bgc($extraLightBlue):h BdB Bdbc($finLightGrayAlt) Bdbc($tableBorderBlue):h H(32px) Bgc(white)' }): for name in listing.find_all('td', attrs={'aria-label': 'Name'}): names.append(name.text) for price in listing.find_all('td', attrs={'aria-label': 'Price (intraday)'}): prices.append(price.find('span').text) for change in listing.find_all('td', attrs={'aria-label': 'Change'}): changes.append(change.text) for percentChange in listing.find_all('td', attrs={'aria-label': '% change'}): percentChanges.append(percentChange.text) for marketCap in listing.find_all('td', attrs={'aria-label': 'Market cap'}): marketCaps.append(marketCap.text) for totalVolume in listing.find_all( 'td', attrs={'aria-label': 'Avg vol (3-month)'}): totalVolumes.append(totalVolume.text) for circulatingSupply in listing.find_all( 'td', attrs={'aria-label': 'Volume'}): circulatingSupplys.append(circulatingSupply.text) print(len(names)) #for i in range(0, len(names)): # print(float(changes[i][0:len(percentChanges[i]) - 1])) # print(float(percentChanges[i][0:len(percentChanges[i])-1])) print(si.get_day_gainers().columns) #is a pandas data frame
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_gainer(self): gainer = get_day_gainers() df = pd.DataFrame( gainer, 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 morning_checkout(): gainers = si.get_day_gainers() num_stocks_bought = 0 for stock in gainers[0:20]['Symbol']: if (num_stocks_bought == 10): break stock_price = si.get_live_price(stock) moving_avg = si.get_data( stock, interval='1d')['close'][-2:].mean() # check 2 day moving avg print(stock, stock_price) qty_d = int(100 / stock_price) if qty_d > 0 and moving_avg > 0: try: buy(stock, qty_d) num_stocks_bought += 1 except: print("Couldn't Buy: ", stock) continue
def get_bigger_gainers(): return si.get_day_gainers()
import requests from yahoo_fin.stock_info import get_day_gainers # Top Gainers of the day data = get_day_gainers() # Get the 5 first and transform the pandas dataframe into a list topFive = data.iloc[0:5, 0].values.tolist() print(topFive) for i in range(len(topFive)): # On récupère les données sur le site API_URL = "https://www.alphavantage.co/query" data = { "function": "TIME_SERIES_INTRADAY", "symbol": topFive[i], "interval": "1min", "outputsize": "compact", "datatype": "json", "apikey": "20M98U0442RX494K" } response = requests.get(API_URL, data) data = response.json() # Globalement les actions suivantes réduisent de plus en plus le dictionnaire pour ne donner qu'une liste de liste # Convertit le dictionnaire en list data = list(data.values()) # On convertit la dict globale des dates en list en gardant les dates (les keys) (intérieur est toujours dict comme ca on peut supprimer plus facilement) data = list(data[1].items()) print(topFive[i]) print(data[0][1]['1. open']) print(data[1][1]['1. open']) print(0 + i, 0 + i, 0 + i, 0 + i, 0 + i, 0 + i, 0 + i, 0 + i, 0 + i, 0 + i,
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()
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()))
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders import yahoo_fin.stock_info as si import time import datetime #from config import * import os df = si.get_day_gainers() df_filtered = df[df['% Change'] >= 5] today = datetime.date.today() #file_name = '/Users/shashank/Documents/Code/Python/Outputs/movers/' + "Top Gainers " + str(today) +".csv" file_name = '/home/mmyers/Documents/GitHub/Finance/Find_Stocks/data/send_top_movers/' + "Top Gainers " + str( today) + ".csv" print(df) df_filtered.to_csv(file_name) """ def send_email(): email_sender = junk_email_username() email_recipient = good_email_username() msg = MIMEMultipart() email_message = "Attached are today's market movers" attachment_location= file_name msg['From'] = email_sender msg['To'] = email_recipient
async def day_gainers(ctx): await ctx.send(si.get_day_gainers())
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')
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)
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()))