def GetCompanieslist(): print("@" * 20 + " Pls Hang on getting data from YahooEarningsCalendar API " + "@" * 20) yec = YahooEarningsCalendar() date_from = pd.to_datetime( cfg.defaults["startdate"]) ##convert str to date format date_to = pd.to_datetime(cfg.defaults["enddate"]) data = yec.earnings_between(date_from, date_to) ### Pull the data print('\n' * 2) print("Successfully Fetched the data for time range", date_from, date_to) print('\n' * 2) df = pd.DataFrame(data) ### Convert into DataFrame df = df.sort_values(by=['epsestimate'], ascending=False) ## Sort in Asc order by epsestimate #df=df[df.epsestimate>cfg.defaults["epsestimate_threshold"]] ## Filter the records df.startdatetime = df.startdatetime.apply( lambda a: pd.to_datetime(a).strftime("%Y-%m-%d %H:%M:%S")) df.fillna(0, inplace=True) for idx, data in df.iterrows(): status = db.EarningCalender(data) #print(status,idx) companies = df.ticker.tolist() ### Get the companies list #print(df.head()) if companies: output = {"companies": companies, "status": True} else: output = {"companies": companies, "status": False} return output
def generate_dfs(num_gl): start_date = datetime.now().date() end_date = datetime.now().date() gainers=get_day_gainers() topg=gainers.nlargest(num_gl,"% Change") topg=topg.drop(columns=["Price (Intraday)","Change","Volume","Avg Vol (3 month)"]) losers=get_day_losers() topl=losers.nsmallest(num_gl,"% Change") topl=topl.drop(columns=["Price (Intraday)","Change","Volume","Avg Vol (3 month)"]) #try: yec = YahooEarningsCalendar() earnings_list = yec.earnings_between(start_date, end_date) earnings_df = pd.DataFrame(earnings_list) earnings_df["% Change"]="" earnings_df["Current Price"]="" earnings_df["Previous Close"]="" earnings_df=earnings_df.drop(columns=["epsestimate","epsactual","epssurprisepct","startdatetime","timeZoneShortName","gmtOffsetMilliSeconds","quoteType"]) for index, x in enumerate(earnings_df["ticker"]): try: earnings_df["Previous Close"][index]=get_quote_table(x , dict_result = True)["Previous Close"] earnings_df["Current Price"][index]=get_live_price(x) earnings_df["% Change"][index]=100*((earnings_df["Current Price"][index]-earnings_df["Previous Close"][index])/earnings_df["Previous Close"][index]) except: pass earnings_df=earnings_df.dropna().sort_values(by="% Change",ascending=False) #except: # earnings_df=pd.DataFrame return earnings_df , topg,topl
def Calendar(Ticker): for i in Ticker: # Setting the dates start_date = datetime.now().date() end_date = date(datetime.now().year, 12, 31) # Downloading the earnings calendar yec = YahooEarningsCalendar() earnings_list = yec.get_earnings_of(i) earnings_df = pd.DataFrame(earnings_list) # Extracting the date from the string and filtering for the period of interest earnings_df['report_date'] = earnings_df['startdatetime'].apply( lambda x: dateutil.parser.isoparse(x).date()) earnings_df = earnings_df.loc[earnings_df['report_date'].between(start_date, end_date)] \ .sort_values('report_date') # Creating initial date list earning_dates = earnings_df['report_date'].to_list() # Converting datetime objects to strings for j in earning_dates: d = date(year=j.year, month=j.month, day=j.day) dates.append(d.strftime("%d-%m-%Y")) # Export Dates with open(f'earning_dates/{i}.txt', 'w', encoding='utf-8') as f: for k in dates: f.write(f"{k}\n") print(f"{i}'s earning report dates exported.") # Reset lists so no overlap occurs del dates[:]
def sp500_constituents(): resp = requests.get( 'http://en.wikipedia.org/wiki/List_of_S%26P_500_companies') soup = bs.BeautifulSoup(resp.text, 'lxml') table = soup.find('table', {'class': 'wikitable sortable'}) tickers = [] companies = [] sectors = [] subindustries = [] next_earnings = [] for row in table.findAll('tr')[1:]: ticker = row.findAll('td')[0].text tickers.append(ticker.rstrip()) company = row.findAll('td')[1].text companies.append(company.rstrip()) sector = row.findAll('td')[3].text sectors.append(sector.rstrip()) subindustry = row.findAll('td')[4].text subindustries.append(subindustry.rstrip()) with open("sp500tickers.pickle", "wb") as f: pickle.dump(tickers, f) yec = YahooEarningsCalendar() for i in range(len(tickers)): try: next_earnings.append( datetime.fromtimestamp(yec.get_next_earnings_date(tickers[i]))) except: print("Problem with: {t}".format(t=tickers[i])) next_earnings.append(0) return tickers, companies, sectors, subindustries, next_earnings
def get_earnings_for_days(date_from, date_to): try: calender_manager = YahooEarningsCalendar() data = calender_manager.earnings_between(date_from, date_to) return [EarningsData(i) for i in data] except KeyError: return []
def DL_earningsdates(argv=None): today = datetime.datetime.today() oneweeks = datetime.timedelta(days=21) threeweeks = datetime.timedelta(days=21) yec = YahooEarningsCalendar() earningsDF = None frames = [] for i in xrange(1, 26, 1): if i > 1: today = today - (threeweeks) threeweeksago = today - threeweeks inthreeweeks = today + threeweeks earnings = yec.earnings_between(threeweeksago, inthreeweeks) df = pd.DataFrame(earnings) print 'Found ' + str(len(df)) + ' results for between ' + str( threeweeksago) + ' and ' + str(inthreeweeks) if ('startdatetime' not in df.columns) or len(df) == 0: print "no startdatetime detected/no data" continue df['startdatetime'] = pd.to_datetime( df['startdatetime']) # TODO make timezone aware and convert to UTC pdtoday = pd.to_datetime(today) df['today'] = pdtoday df['temp'] = df['startdatetime'].view('int64') - df['today'].view( 'int64') df['days'] = df['temp'].apply(lambda x: np.timedelta64(x, 'ns').astype( 'timedelta64[D]') / np.timedelta64(1, 'D')) frames.append(df) df.to_csv('/root/data/temp/earningsdata-' + str(threeweeksago) + '-' + str(inthreeweeks) + '.csv') earningsDF = pd.concat(frames) earningsDF.to_csv('/root/data/temp/earningsdata.csv')
def get_earnings_calendar(start_date, end_date): yec = YahooEarningsCalendar() print('Getting earnings calendar between {} - {}'.format( start_date, end_date)) all_earnings_data = yec.earnings_between(start_date, end_date) all_earnings_df = pd.DataFrame(all_earnings_data) all_earnings_df = all_earnings_df.set_index('ticker') return all_earnings_df
def get_todays_earnings(): today = datetime.date.today() date_from = datetime.datetime.combine(today, datetime.datetime.min.time()) date_to = datetime.datetime.combine(today, datetime.datetime.max.time()) yec = YahooEarningsCalendar() earnings_list = yec.earnings_between(date_from, date_to) ticker_list = [] for stock in earnings_list: ticker_list.append(stock['ticker']) return np.unique(ticker_list)
def update_data(): latest_date = get_latest_data() on_date = latest_date + timedelta(days=1) on_date = datetime(on_date.year, on_date.month, on_date.day) yec = YahooEarningsCalendar(delay=1) while on_date <= datetime.utcnow() - timedelta(days=1): logger.info(f"[Earnings] Add data on {on_date}") data = yec.earnings_on(on_date) df = pd.DataFrame(data) df.to_csv(CRUDE_EARNINGS_DATA_PATH, mode='a', header=False) on_date += timedelta(days=1) time.sleep(1)
def get_next_earning_release() -> list: date_from = datetime.datetime.today() date_to = get_next_working_day() yec = YahooEarningsCalendar() all_ticker = list() today_earnings = yec.earnings_on(date_from) tomorrow_earnings = yec.earnings_on(date_to) for stock1, stock2 in zip(today_earnings, tomorrow_earnings): if stock1['startdatetimetype'] == 'AMC': all_ticker.append(stock1['ticker']) if stock2['startdatetimetype'] == 'BMO': all_ticker.append(stock2['ticker']) return all_ticker
def get_earnings(self, days_before = 0, days_after = 30): from yahoo_earnings_calendar import YahooEarningsCalendar dfdb = pd.read_sql(self.earnings_db, con=self.engine) yec = YahooEarningsCalendar() dfd = pd.DataFrame(yec.earnings_between( datetime.now() - timedelta(days=days_before), datetime.now() + timedelta(days=days_after))) df_new = dfd.append(dfdb, ignore_index=True) df_new.drop_duplicates(subset=["ticker","startdatetime","startdatetimetype"], inplace=True, keep="first") #save DATAFRAME to database df_new.to_sql(self.earnings_db, con=self.engine, if_exists='replace', index=False) print(df_new) return df_new
def OneTimeUpdate(num_days): count = 1 print('OneTimeUpdate') yec = YahooEarningsCalendar() date_from = datetime.date.today() date_to = date_from + dateutil.relativedelta.relativedelta( days=num_days) ERs = yec.earnings_between(date_from, date_to) ERs = [{k: item[k] for k in ('ticker', 'startdatetime')} for item in ERs] num_itr = len(ERs) for er in ERs: screener.objects.update_or_create( symbol=er['ticker'], defaults={'nextER': er['startdatetime']}) print("itr %3d of %3d" % (count, num_itr)) count = count + 1
def get_earnings(): ''' get earnings date and ticker from yahoo calendar library save as format: [ { ticker: 'string', date: 'string', }, ... ] ''' print('earnings date script started.......') def get_front_date(date_delta): dates_list = [] for i in range(0, date_delta): d = datetime.date.today() d += datetime.timedelta(i) if d.weekday() == 4: dates_list.append(str(d)) #print(dates_list[-2]) return dates_list[-1] front_date = get_front_date(15) print(front_date) # ========= check earnings calendar ========== date_from = datetime.datetime.strptime(date.today().strftime('%Y-%m-%d') + " 05:00:00", '%Y-%m-%d %X') date_to = datetime.datetime.strptime(front_date + " " + "18:00:00", '%Y-%m-%d %X') yec = YahooEarningsCalendar() earnings_list= [] earnings_calendar = yec.earnings_between(date_from, date_to) if earnings_calendar: for company in earnings_calendar: earnings_dict = {} earnings_dict['ticker'] = company['ticker'] earnings_dict['date'] = re.findall('\d\d\d\d-\d\d-\d\d',company['startdatetime'])[0] earnings_list.append(earnings_dict) with open('/tmp/json/companies_earnings.json', 'w') as f: json.dump(earnings_list, f) print('earnings date script finished !') print('check /tmp/json/ for earnings_date')
def upcoming_earnings(self, days: int = 2) -> str: result = '' date_from = date.today() date_to = date_from + timedelta(days=days) yec = YahooEarningsCalendar() ue = yec.earnings_between(date_from, date_to) pd_ue = pd.DataFrame(ue) pd_ue = pd_ue.drop_duplicates(subset=['ticker']) columns = ['startdatetime', 'companyshortname', 'ticker'] result = pd_ue[columns].to_string(header=False, index=False, formatters={ columns[0]: formatter_date, columns[1]: '{:.15}'.format }) return result
def email(): ezgmail.init() DAYS_AHEAD=1 start_date = datetime.now().date() + timedelta(days=DAYS_AHEAD) end_date = (datetime.now().date() + timedelta(days=DAYS_AHEAD)) # downloading the earnings calendar yec = YahooEarningsCalendar() earnings_list = yec.earnings_between(start_date, end_date) print(earnings_list) # saving the data in a pandas DataFrame earnings_df = pd.DataFrame(earnings_list) print(earnings_df["startdatetime"]) earnings_df["startdatetime"]= earnings_df['startdatetime'].astype(str).str[:-14] earnings_df["Link"]="https://finance.yahoo.com/quote/{}".format(earnings_df["ticker"]) for index, x in enumerate(earnings_df["ticker"]): earnings_df["Link"][index]="https://finance.yahoo.com/quote/{}".format(x) print(earnings_df["startdatetime"]) print(earnings_df) earnings_df.to_csv( r"C:\Users\MIKEB\Desktop\Python\Fuhnance\Earnings_For_{}.csv".format(start_date)) e,g,l=generate_dfs(10) msg="Top Gainers Today:\n\n" for index,x in enumerate(g["Symbol"]): try: line=f"{x} | {g['Name'][index]} | {g['% Change'][index]}% | https://finance.yahoo.com/quote/{x}\n\n" msg=msg+line except: pass print(msg) msg=msg+"\n\nTop Losers Today:\n\n" for index,x in enumerate(l["Symbol"]): try: line=f"{x} | {l['Name'][index]} | {l['% Change'][index]}% | https://finance.yahoo.com/quote/{x}\n\n" msg=msg+line except: pass msg=msg+"\n\nEarnings Action Today:\n\n" for index,x in enumerate(e["ticker"]): line=f"{x} | {e['companyshortname'][index]} | {e['startdatetimetype'][index]} | {round(e['% Change'][index],2)}% | https://finance.yahoo.com/quote/{x}\n\n" msg=msg+line print(msg) #for x in ["*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**"]: for x in ["*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**"]: ezgmail.send(x,"Gainers, Losers, and Earnings {}".format(start_date),msg,r"C:\Users\MIKEB\Desktop\Python\Fuhnance\Earnings_For_{}.csv".format(start_date))
def scrap_yahoo_appointments(appointments: dict, stock: Stock, stock_storage: StockStorage): if stock.symbol: try: if appointments is None or len(appointments) == 0: earnings = YahooEarningsCalendar().get_earnings_of( stock.symbol) else: last_appointment = max(appointments.keys()) last_appointment = (datetime.strptime(last_appointment, "%Y-%m-%d")) if last_appointment > stock_storage.indexStorage.date: earnings = YahooEarningsCalendar().get_earnings_of( stock.symbol) except Exception as e: logging.error( "Unable to get yahoo earnings for symbol '{}' for stock {} {}". format(stock.symbol, stock.stock_id, stock.name)) if 'earnings' not in locals(): logging.warning("No earning data for stock {} {}".format( stock.stock_id, stock.name)) else: appointments = {} oldest_date = toRevertStr(stock_storage.indexStorage.date - relativedelta(months=3)) for earning in earnings: date_str = earning["startdatetime"].split("T")[0] if date_str > oldest_date: appointments[date_str] = "Yahoo Earning" else: break else: logging.warning("No symbol for stock {} {}".format( stock.stock_id, stock.name)) return appointments
def PopulateEarningDate(num_days): yec = YahooEarningsCalendar() date_to = datetime.date.today() date_from = date_to - dateutil.relativedelta.relativedelta( days=num_days) ERs = yec.earnings_between(date_from, date_to) ERs = [{ k: item[k] for k in ('ticker', 'startdatetime', 'epsestimate', 'epsactual', 'epssurprisepct') } for item in ERs] for er in ERs: screener.objects.update_or_create(symbol=er['ticker'], defaults={ 'epsActual': er['epsactual'], 'epsEstimate': er['epsestimate'], 'mostRecentER': er['startdatetime'], 'epsSurprisePC': er['epssurprisepct'] })
def get_future_earnings(self): date_from = datetime.strptime(self.start_date, '%b %d %Y') date_to = datetime.strptime(self.end_date, '%b %d %Y') yec = YahooEarningsCalendar() el = yec.earnings_between(date_from, date_to) df_list = [] for elem in el: if elem['ticker'] in self.name_list: str1 = elem['startdatetime'] l1 = str1.split("T") date = l1[0] str2 = elem['startdatetimetype'] type = "" if str2 == "BMO" or str2 == "AMC": type = str2 else: l2 = l1[1].split(":") if int(l2[0]) <= 16: type = "BMO" else: type = "AMC" l2 = date.split("-") day = day_dict[calendar.weekday(int(l2[0]), int(l2[1]), int(l2[2]))] #print("|",elem['ticker'].ljust(10),elem['companyshortname'].ljust(40),day.ljust(4),date.ljust(15),type.ljust(8),"|") t = (elem['ticker'], elem['companyshortname'], day, date, type) df_list.append(t) arr = np.array(df_list) df = pd.DataFrame(arr, columns=['Ticker', 'Company', 'Day', 'Date', 'When']) model = pandasModel(df) #print(tabulate(df, headers='keys', tablefmt='psql')) return model
class EarningCalendar(abc.ABC): def __init__(self): super().__init__() self.yec = YahooEarningsCalendar() constituents_df = pd.read_csv("../data/constituents.csv") self.constituents = set(constituents_df.Symbol.values) def earning_events_on(self, date): ''' :param date: date of interest :return: tuple (number of earnings reported after the market closes, number of all other earning events) ''' earnings = self.yec.earnings_on(date) # filter only S&P tickers earnings = list( filter(lambda x: x['ticker'] in self.constituents, earnings)) # after market close earnings - will be added to the next market day after_market_close = len( list(filter(lambda x: x['startdatetimetype'] == 'AMC', earnings))) others = len(earnings) - after_market_close s_and_p_matches = (after_market_close, others) return s_and_p_matches
from datetime import datetime from pytz import timezone from yahoo_earnings_calendar import YahooEarningsCalendar import json newYorkTz = timezone('America/New_York') symbol = 'AAPL' fromDate = datetime(2010, 1, 1, tzinfo=newYorkTz) toDate = datetime(2020, 6, 9, tzinfo=newYorkTz) fromDateFormat = fromDate.strftime('%Y-%m-%d') toDateFormat = toDate.strftime('%Y-%m-%d') yec = YahooEarningsCalendar() data = yec.get_earnings_of(symbol) with open(f'./data/data3/earnings/{symbol}.json', 'w') as f: json.dump(data, f)
import pandas as pd from datetime import datetime from datetime import timedelta from yahoo_earnings_calendar import YahooEarningsCalendar import dateutil.parser pd.set_option('display.max_columns', None) # Downloading the earnings for a specific date report_date = datetime.now().date() yec = YahooEarningsCalendar() earnings_list = yec.earnings_on(report_date) earnings_df = pd.DataFrame(earnings_list) earnings_df = earnings_df.drop(columns = ['gmtOffsetMilliSeconds', 'quoteType', 'timeZoneShortName']) earnings_df.columns = ['Ticker', 'Company Name', 'DateTime', 'Type', 'EPS Estimate', 'EPS Actual', 'EPS Surprise PCT'] earnings_df = earnings_df[['Ticker', 'Company Name', 'DateTime', 'Type', 'EPS Estimate', 'EPS Actual', 'EPS Surprise PCT']] earnings_df['DateTime'] = pd.to_datetime(earnings_df['DateTime']).dt.tz_localize(None) print(earnings_df) # Downloading the earnings for a range of dates DAYS_AHEAD = 7 start_date = datetime.now().date() end_date = (datetime.now().date() + timedelta(days=DAYS_AHEAD)) yec = YahooEarningsCalendar() earnings_list = yec.earnings_between(start_date, end_date) earnings_df = pd.DataFrame(earnings_list) earnings_df = earnings_df.drop(columns = ['gmtOffsetMilliSeconds', 'quoteType', 'timeZoneShortName']) earnings_df.columns = ['Ticker', 'Company Name', 'DateTime', 'Type', 'EPS Estimate', 'EPS Actual', 'EPS Surprise PCT']
import datetime from yahoo_earnings_calendar import YahooEarningsCalendar date_from = datetime.datetime.strptime('May 5 2017 10:00AM', '%b %d %Y %I:%M%p') date_to = datetime.datetime.strptime('May 8 2017 1:00PM', '%b %d %Y %I:%M%p') yec = YahooEarningsCalendar() print(yec.earnings_on(date_from)) print(yec.earnings_between(date_from, date_to))
from yahoo_earnings_calendar import YahooEarningsCalendar from yahooquery import Ticker import pandas as pd from datetime import datetime, timedelta # Create instance of yec yec = YahooEarningsCalendar() # Define Start/End Dates and Pull list of stocks with upcoming earnings start = datetime.today() + timedelta(days=15) end = datetime.today() + timedelta(days=25) earnings = yec.earnings_between(start, end) # Extract symbols from results screener_symbols = [dic['ticker'] for dic in earnings] # Pull current prices screener = Ticker(screener_symbols) today_price = screener.price # Prices DataFrame prices_df = pd.DataFrame(today_price).T.reset_index() prices_df.rename({'regularMarketPrice': 'stock_price'}, inplace=True, axis=1) # Create empty list to store filtered stocks filtered_stocks = [] # Go through stocks and check if price is between 5/100 for stock in today_price.keys(): # Dealing with stocks with no results
import csv import pandas import datetime from yahoo_earnings_calendar import YahooEarningsCalendar yec = YahooEarningsCalendar() #current non queried:APC ARNC BBT BF-B BHGE CBS CELG DOW DWDP FOX FOXA HCP HRS JEC LEN LLL NWS RHT SYMC TMK TSS WCG #current empty fields: (try with different hour): CMI GNP KHC MLM MOS SNA XEL date_from = datetime.datetime.strptime('Jan 1 2017 01:00AM', '%b %d %Y %I:%M%p') date_to = datetime.datetime.strptime('Dec 31 2018 11:00PM', '%b %d %Y %I:%M%p') data = pandas.read_csv('data/companiesNew.csv', names=None) symList = data.Symbols.tolist() with open('data/earnings.csv', 'w', newline='') as file: fieldnames = [ 'Stock', 'Q1 2017 date', 'Q1 2017 Est', 'Q1 2017 Act', 'Q2 2017 date', 'Q2 2017 Est', 'Q2 2017 Act', 'Q3 2017 date', 'Q3 2017 Est', 'Q3 2017 Act', 'Q4 2017 date', 'Q4 2017 Est', 'Q4 2017 Act', 'Q1 2018 date', 'Q1 2018 Est', 'Q1 2018 Act', 'Q2 2018 date', 'Q2 2018 Est', 'Q2 2018 Act', 'Q3 2018 date', 'Q3 2018 Est', 'Q3 2018 Act', 'Q4 2018 date', 'Q4 2018 Est', 'Q4 2018 Act' ] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() for sym in symList: listEarning = []
connection.close() """ date_from = datetime.datetime.strptime( 'August 22 2020 10:00AM', '%B %d %Y %I:%M%p') date_to = datetime.datetime.strptime( 'September 10 2020 5:00PM', '%B %d %Y %I:%M%p') """ date_to = datetime.datetime.today().replace(year=datetime.datetime.today().year+1) print("date_to: " + str(date_to)) print("today: " + str(datetime.datetime.today())) yec = YahooEarningsCalendar() earning_info_list = [] fetched_earnings = yec.earnings_between(datetime.datetime.today(), date_to) for each in fetched_earnings: earning_info_list.append(EarningInfo(each['ticker'], each['companyshortname'], each['startdatetime'], each['startdatetimetype'], each['epsestimate'])) ticker_set = set() for each in earning_info_list: ticker_set.add(each.ticker) tickers_string = ""
def finding_fun(sec): from yahoo_earnings_calendar import YahooEarningsCalendar yec = YahooEarningsCalendar() data = yec.get_earnings_of(sec) fdf = pd.DataFrame(data) return fdf
import datetime from collections import defaultdict from yahoo_earnings_calendar import YahooEarningsCalendar import pandas as pd from datetime import date, time, datetime, timedelta import sqlalchemy from sqlalchemy import * from sqlalchemy.orm import sessionmaker from datetime import datetime mydict = dict() alldict = defaultdict(list) my_custom_delay_s = 0.1 yec = YahooEarningsCalendar(my_custom_delay_s) tickers = ['EBAY', 'EA', 'ECL'] #tickers = ['A', 'AAL', 'AAPL', 'ABBV', 'ABT', 'ACN', 'ADBE', 'ADI', 'ADP', 'ADSK', 'AEP', 'AFL', 'AGG', 'AGN', 'ALGN', 'ALL', 'ALXN', 'AMAT', 'AMGN', 'AMT', 'AMZN', 'ANTM', 'AON', 'APD', 'APH', 'ASML', 'ATVI', 'AVGO', 'AWK', 'AXP', 'AZO', 'BA', 'BABA', 'BAC', 'BAX', 'BDX', 'BIDU', 'BIIB', 'BK', 'BKNG', 'BLK', 'BMRN', 'BMY', 'BSX', 'C', 'CAT', 'CB', 'CCI', 'CDNS', 'CERN', 'CHKP', 'CHTR', 'CI', 'CL', 'CLX', 'CMCSA', 'CME', 'CNC', 'COF', 'COP'] #tickers = ['A', 'AAL', 'AAPL', 'ABBV', 'ABT', 'ACN', 'ADBE', 'ADI', 'ADP', 'ADSK', 'AEP', 'AFL', 'AGG', 'AGN', 'ALGN', 'ALL', 'ALXN', 'AMAT', 'AMGN', 'AMT', 'AMZN', 'ANTM', 'AON', 'APD', 'APH', 'ASML', 'ATVI', 'AVGO', 'AWK', 'AXP', 'AZO', 'BA', 'BABA', 'BAC', 'BAX', 'BDX', 'BIDU', 'BIIB', 'BK', 'BKNG', 'BLK', 'BMRN', 'BMY', 'BSX', 'C', 'CAT', 'CB', 'CCI', 'CDNS', 'CERN', 'CHKP', 'CHTR', 'CI', 'CL', 'CLX', 'CMCSA', 'CME', 'CNC', 'COF', 'COP', 'COST', 'CRM', 'CSCO', 'CSX', 'CTAS', 'CTSH', 'CTXS', 'CVS', 'CVX', 'D', 'DBA', 'DD', 'DE', 'DG', 'DHR', 'DIS', 'DLR', 'DLTR', 'DUK', 'EA', 'EBAY', 'ECL', 'ED', 'EL', 'EMB', 'EMR', 'EQIX', 'EQR', 'ES', 'ETN', 'EW', 'EWH', 'EWW', 'EXC', 'EXPE', 'FAST', 'FB', 'FDX', 'FE', 'FIS', 'FISV', 'GD', 'GE', 'GILD', 'GIS', 'GM', 'GOOG', 'GPN', 'GS', 'HAS', 'HCA', 'HD', 'HON', 'HPQ', 'HSIC', 'HUM', 'HYG', 'IAU', 'IBM', 'ICE', 'IDXX', 'ILMN', 'INCY', 'INFO', 'INTC', 'INTU', 'ISRG', 'ITW', 'JBHT', 'JD', 'JNJ', 'JPM', 'KHC', 'KLAC', 'KMB', 'KMI', 'KO', 'KR', 'LBTYA', 'LBTYK', 'LHX', 'LLY', 'LMT', 'LOW', 'LQD', 'LRCX', 'LULU', 'MA', 'MAR', 'MCD', 'MCHP', 'MCO', 'MDLZ', 'MDT', 'MELI', 'MET', 'MMC', 'MMM', 'MNST', 'MO', 'MRK', 'MS', 'MSCI', 'MSFT', 'MSI', 'MU', 'MXIM', 'MYL', 'NEE', 'NEM', 'NFLX', 'NKE', 'NLOK', 'NOC', 'NOW', 'NSC', 'NTAP', 'NTES', 'NVDA', 'NXPI', 'ORCL', 'ORLY', 'PAYX', 'PCAR', 'PEG', 'PEP', 'PFE', 'PG', 'PGR', 'PLD', 'PM', 'PNC', 'PSA', 'PSX', 'PYPL', 'QCOM', 'REGN', 'RMD', 'ROKU', 'ROP', 'ROST', 'RTX', 'SBAC', 'SBUX', 'SCHW', 'SHOP', 'SHW', 'SHY', 'SIRI', 'SNPS', 'SO', 'SPGI', 'SPY', 'SRE', 'STZ', 'SWKS', 'SYK', 'SYY', 'T', 'TCOM', 'TFC', 'TGT', 'TIP', 'TJX', 'TMO', 'TMUS', 'TROW', 'TRV', 'TSLA', 'TTWO', 'TWLO', 'TXN', 'ULTA', 'UNH', 'UNP', 'UPS', 'USB', 'V', 'VNQ', 'VRSK', 'VRSN', 'VRTX', 'VZ', 'WBA', 'WDAY', 'WDC', 'WEC', 'WFC', 'WLTW', 'WM', 'WMT', 'WYNN', 'XHB', 'XLK', 'XLNX', 'XLU', 'XLV', 'XOM', 'XRT', 'YUM', 'ZTS'] # Returns a list of all available earnings of BOX for i in tickers: mydict[i] = yec.get_earnings_of(i) print(i) if mydict.get(i): print("found") for k in mydict.get(i): tset = k.get( 'startdatetime' )[: -5] #remove last 5 digits in time stamp returned (weird '.000Z' value) tnew = tset.replace(
def main(argv): list_file = "" name_list = set() start_date = "" end_date = "" future_flag = False db_name = "" update_flag = False method_flag = False try: opts, args = getopt.getopt(argv, "hd:l:s:e:uafm", [ "db_name=", "list_file=", "start_date=", "end_date=", "update", "add", "future", "method" ]) except getopt.GetoptError: print("""driver2.py -l <file containing list of stocks> -d <name of the database> -s <start_date in YYYY-MM-DD format> -e <end_date in YYYY-MM-DD format> -u (update, do not replace) -a (add additional instruments) -f (this is for coming earnings) -m (use laternative method for future earnings) """) sys.exit(2) for opt, arg in opts: if opt == '-h': print("""driver2.py -l <file containing list of stocks> -s <start_date in YYYY-MM-DD format> -e <end_date in YYYY-MM-DD format> -d <name of the database> -u (update, do not replace) -a (add additional instruments) -f (this is for coming earnings) -m (use laternative method for future earnings) """) sys.exit() elif opt in ("-l", "--list_file"): list_file = arg elif opt in ("-s", "--start_date"): start_date = arg elif opt in ("-e", "--end_date"): end_date = arg elif opt in ("-f", "--future"): future_flag = True elif opt in ("-u", "--update"): update_flag = True elif opt in ("-m", "--method"): method_flag = True elif opt in ("-d", "--db_name"): db_name = arg process_file(list_file, name_list) date_from = datetime.strptime(start_date, '%b %d %Y') date_to = datetime.strptime(end_date, '%b %d %Y') if future_flag == True: if method_flag == False: yec = YahooEarningsCalendar() el = yec.earnings_between(date_from, date_to) print_future_earnings(el, name_list) else: future_earnings_method2(start_date, end_date, name_list) else: l1 = start_date.split() l2 = end_date.split() obtain_historical_earnings_data(l1, l2, name_list, db_name, update_flag)
from pandas_datareader._utils import RemoteDataError import pandas as pd import numpy as np from datetime import datetime import yfinance_ez as yf from yahoo_fin.stock_info import get_live_price import flask from flask import Flask, request, jsonify from yahoo_earnings_calendar import YahooEarningsCalendar import time app = flask.Flask(__name__) app.config["DEBUG"] = True yec = YahooEarningsCalendar() START_DATE = '1980-01-01' END_DATE = str(datetime.now().strftime('%Y-%m-%d')) def get_stats(stock_data): adj_close = clean_data(stock_data, 'Adj Close') return { 'last(1 Day Mean)': np.mean(adj_close.tail(1)), 'short_mean(20 day mean)': np.mean(adj_close.tail(20)), 'medium_mean (90 day mean)': np.mean(adj_close.tail(90)), 'long_mean(200 day mean)': np.mean(adj_close.tail(200)) #'short_rolling':stock_data.rolling(window=20).mean(), #'long_rolling':stock_data.rolling(window=200).mean() }
# The first time to run the program, you need to install yfinance module and # yahoo_earings_calendar by running the folloiwng command once. # After that, you can comment them out by prefixing a # sign. !pip install yfinance !pip install yahoo_earnings_calendar # Import required library modules import yfinance as yf from yahoo_earnings_calendar import YahooEarningsCalendar import pandas as pd import numpy as np # Try to get tickers from earnings report # You may enter your prefered stock ticker manually. yec= YahooEarningsCalendar() from datetime import datetime day1 = datetime.strptime('10/30/2020', '%m/%d/%Y') er = yec.earnings_on(day1) # Use this dropdown widget to select a ticker for retrieving the stock data. from ipywidgets import Dropdown option_list =[] for i in range(len(er)): option_list.append([er[i]['companyshortname']+'-'+er[i]['ticker'], er[i]['ticker']]) dropdown = Dropdown(description = 'Select one company', options = option_list) display(dropdown) ticker = dropdown.value # Get the stock data from Yahoo finance.