Пример #1
0
def get_earnings_history_(tick):
    ern_hist = yf.get_earnings_history(tick)
    epsactual = [eh['epsactual'] for eh in ern_hist][::-1]
    epsestimate = [eh['epsestimate'] for eh in ern_hist][::-1]
    date = [eh['startdatetime'][0:10] for eh in ern_hist][::-1]

    return {'epsactual': epsactual, 'epsestimate': epsestimate, 'date': date}
def get_data_on_symbols(symbols, type_="info"):
    data = []
    symbols_with_data = []
    for symbol in symbols:
        if type_ == "info":
            try:
                data.append(yf_info.Ticker(symbol).info)
                symbols_with_data.append(symbol)
            except:
                continue
        elif type_ == "earnings":
            try:
                data.append(
                    pd.DataFrame.from_dict(
                        yf_earn.get_earnings_history(symbol)))
                symbols_with_data.append(symbol)
            except:
                continue
        else:
            raise Exception("ERROR", "Unrecognised type_ value.")

    return dict(zip(symbols_with_data, data))
Пример #3
0
pred_high = reg_high.predict(time)

reg_low = LinearRegression().fit(time, sklow)
pred_low = reg_low.predict(time)

plt.plot(time, pred_high)
plt.plot(time, pred_low)
plt.plot(time, skclose)
plt.legend(['High', 'Low', 'Close'])
plt.show()

##################### historical PE ratio #####################
## eps
ticker = 'adbe'
stock = yf.Ticker(ticker)
earning_tmp1 = si.get_earnings_history(ticker)
earning_tmp2 = pd.DataFrame(earning_tmp1)
earning = earning_tmp2[earning_tmp2['startdatetimetype'] != 'TAS']

# actual earning
earn_act = earning.dropna()

# actual eps date
earntime = list(earn_act['startdatetime'].str[:10])

# price on actual earning date
price_cls = []
for i in range(len(earntime)):
    skprice = stock.history(start=dt.date.fromisoformat(earntime[i]) -
                            dt.timedelta(days=30),
                            end=earntime[i])
Пример #4
0
    def plot_earning(self, **kwargs):

        plt.figure(figsize=(12, 9))
        fig, axes = plt.subplots(2)

        # add earning history
        earnings_history = si.get_earnings_history(self.name)
        earnings_history = pd.DataFrame(earnings_history)
        earnings_history.dropna(inplace=True)
        earnings_history = earnings_history.set_index("startdatetime")
        earnings_history = earnings_history.sort_index()
        earnings_history.index = pd.to_datetime(earnings_history.index)
        if len(earnings_history) > 10:
            earnings_history = earnings_history.iloc[-10:]
        result_dict = {}
        result_dict["epsactual"] = list(earnings_history["epsactual"])
        result_dict["epsestimate"] = list(earnings_history["epsestimate"])

        earnings = si.get_earnings(self.name)
        info = si.get_analysts_info(self.name)
        result_dict["epsactual"].extend([None, None])
        result_dict["epsestimate"].append(
            info["Earnings Estimate"].T.iloc[1].loc[1])
        result_dict["epsestimate"].append(
            info["Earnings Estimate"].T.iloc[2].loc[1])
        result_df = pd.DataFrame(result_dict)
        this_year = dt.datetime.now().year
        next_year = this_year + 1
        new_row = {
            "date":
            this_year,
            "revenue":
            _convert_to_numeric(info["Revenue Estimate"].T.iloc[3].loc[1]),
            #"earnings": _convert_to_numeric(info["Earnings Estimate"].T.iloc[3].loc[1])
        }
        earnings["yearly_revenue_earnings"] = earnings[
            "yearly_revenue_earnings"].append(new_row, ignore_index=True)
        new_row = {
            "date":
            next_year,
            "revenue":
            _convert_to_numeric(info["Revenue Estimate"].T.iloc[4].loc[1]),
            #"earnings": _convert_to_numeric(info["Earnings Estimate"].T.iloc[4].loc[1])
        }
        earnings["yearly_revenue_earnings"] = earnings[
            "yearly_revenue_earnings"].append(new_row, ignore_index=True)
        earnings["yearly_revenue_earnings"]["revenue"] = earnings[
            "yearly_revenue_earnings"]["revenue"] / 1000000000
        #earnings["yearly_revenue_earnings"] = earnings["yearly_revenue_earnings"]/1000000000
        earnings["yearly_revenue_earnings"].set_index('date', inplace=True)
        earnings["yearly_revenue_earnings"]["revenue"].plot(
            ax=axes[0], marker='o', legend=["revenue(B)"])
        #print(result_df)
        result_df.plot(ax=axes[1], marker='o')

        # save to file if possible
        #fig = plt.gcf()
        image_name = self.name
        if "image_name" in kwargs:
            image_name = kwargs['image_name']
        result_dir = kwargs['result_dir'] if 'result_dir' in kwargs else None
        if result_dir is not None:
            file_name = image_name + "_earnings.png"
            fig.savefig(os.path.join(result_dir, file_name), dpi=300)
            plt.close(fig)
            self.markdown_notes += "\n\n \pagebreak\n\n"
            self.markdown_notes += f"![{image_name}]({file_name})\n\n\n"
            return file_name
        else:
            return fig, axes
Пример #5
0
import yahoo_fin.stock_info as si
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates
from datetime import datetime as dt
import datetime

codelist = ['msft']

for i in range(len(codelist)):
   
   ticker=codelist[i]
   ticker_earnings_hist = si.get_earnings_history(ticker)
   df =pd.DataFrame.from_dict(ticker_earnings_hist).loc[:,["startdatetime","epsestimate","epsactual"]]
   df.rename(columns={'epsestimate':'EPS Estimate','epsactual':'EPS Actual'},inplace=True)
   df['day'] = pd.to_datetime(df["startdatetime"], format='%Y-%m-%d')
   df['startdatetime'] = df['day'].dt.strftime('%Y-%m-%d')
       
   df = df.sort_index(axis='index',ascending=False)[["startdatetime","EPS Estimate", "EPS Actual"]]
   df[(df['startdatetime'] > '2006-01-01')].plot.bar(title=ticker , x="startdatetime",color=['lightgray', 'red'], figsize=(14,6),fontsize=10)
   plt.title(ticker, fontsize=50)
   plt.xlabel(xlabel="", fontsize=20)
   plt.ylabel(ylabel="EPS", fontsize=20)
   plt.legend(fontsize=25)
   plt.show()
Пример #6
0
import pandas as pd
from yahoo_fin import options
from yahoo_fin import stock_info as si
"""
nflx_dates = options.get_expiration_dates('nflx')

chain = options.get_options_chain("nflx")

calls = chain["calls"]

puts = chain["puts"]

nflx_dates= options.get_expiration_dates("nflx")
 
info = {}
for date in nflx_dates:
    info[date] = options.get_options_chain("nflx")
    
"""
# dow_tickers = si.tickers_dow()

# nasdaq = si.tickers_nasdaq()

# sp = si.tickers_sp500()

aapl_earnings = si.get_next_earnings_date("aapl")

aapl_earnings_hist = si.get_earnings_history("aapl")

data = pd.DataFrame.from_dict(aapl_earnings_hist)
Пример #7
0
def getEarningsHistory(ticker):
    return si.get_earnings_history(ticker)