def calculate_ps_metrics(stock):
        yahoo_stock = YahooFinancials(stock.symbol)
        market_cup = yahoo_stock.get_market_cap()
        if stock.target_avg_sales:
            multiplier = FilteredStocks.get_multiplier(
                stock.target_avg_sales[-1])
            target_avg_sales = float(stock.target_avg_sales[:-1]) * multiplier
            try:
                stock.price_to_sell_ratio = round(
                    market_cup / target_avg_sales, 2)
                stock.ps_to_growth_ratio = round(
                    stock.price_to_sell_ratio /
                    float(stock.target_sales_growth[:-1]), 2)
                ev = (yahoo_stock.get_key_statistics_data()[stock.symbol]
                      ["enterpriseValue"])
                profit_margins = (yahoo_stock.get_key_statistics_data()[
                    stock.symbol]["profitMargins"])
                stock.ev_to_sell_ratio = round(ev / target_avg_sales, 2)
                stock.gross_margins = round(
                    yahoo_stock.get_gross_profit() /
                    yahoo_stock.get_total_revenue() * 100, 2)
                ev_to_profit_ratio = round(
                    stock.ev_to_sell_ratio / profit_margins, 2)
                print("gross_margins : " + str(stock.gross_margins))
                print("ev sells : " + str(stock.ev_to_sell_ratio))
                print("ev / earnings : " + str(ev_to_profit_ratio))
                print("ps_to_growth : " + str(stock.ps_to_growth_ratio))
                print("sales targets:" + str(stock.target_sales_growth[:-1]))
                print("growth adujsted ev / sells: " + str(
                    round(
                        stock.ev_to_sell_ratio /
                        float(stock.target_sales_growth[:-1]), 2)))

            except Exception as e:
                print(str(e))
Esempio n. 2
0
def fundamentals(tickers, begin="2020-05-26", end="2020-06-26",):
    format_header = '{:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>10} {:>10}'
    format_numbers = '{:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6}  {:>6} {:>10.2e} {:>10.2E}'
    print(format_header.format('ticker', 'P/E', 'EARNSH', 'BK/PR', 'DY', 'DR', 'VAR', 'PEG', 'PS', 'PCI', 'VOLPR', 'CM',))

    for ticker in tickers:
        yf = YF(ticker)

        try:
            pe = get_number_for_None(get_number_for_None(yf.get_pe_ratio()))
            prices = yf.get_historical_price_data(begin, end, "daily")[ticker]['prices']
            stat_pr = calc_statistics(prices)
            var_pr = get_number_for_None(100 * stat_pr[1] / stat_pr[0])
            volume = get_number_for_None(stat_pr[4])
            es = get_number_for_None(yf.get_earnings_per_share())
            sh = get_number_for_None(yf.get_num_shares_outstanding(price_type='current'))
        
            ''' "pegRatio" "priceToBook" "heldPercentInstitutions" '''
            
            statistics = yf.get_key_statistics_data()[ticker]
            summary = yf.get_summary_data()[ticker]
            peg = get_number_for_None(statistics["pegRatio"])
            PCI = get_number_for_None(statistics["heldPercentInstitutions"])
            bv = yf.get_key_statistics_data()[ticker]['bookValue']
            pr = yf.get_current_price()

            if pr is not None and bv is not None:
                pr_bv = get_number_for_None(pr/bv)
            else:
                pr_bv = '-99.99'

            f_s = yf.get_financial_stmts('annual', 'income')['incomeStatementHistory'][ticker][0]
            f_s_key = list(f_s.keys())[0]
            totalRevenue = f_s[f_s_key]['totalRevenue']
            outstanding = statistics["sharesOutstanding"]
            rev_per_share = totalRevenue / outstanding
            
            if pr is not None and es is not None:
                p_s = get_number_for_None(rev_per_share/float(es))
            else:
                p_s = '99'

              
            dy = get_number_for_None(yf.get_dividend_yield())
            dr = get_number_for_None(yf.get_dividend_rate())
        
            volume10days = summary['averageVolume10days']
            marketCap = summary['marketCap']
        
            # float(volume)*pr
            # float(sh)*pr)
            print(format_numbers.format(ticker, pe, es, pr_bv, dy, dr, var_pr, peg, p_s, PCI, volume10days, marketCap))
        except Exception as e:
            print(ticker, e)
Esempio n. 3
0
def get_df_1(ticker):
    yahoo_financials = YahooFinancials(ticker)
    stats_1 = yahoo_financials.get_key_statistics_data()
    df_1 = pd.DataFrame(stats_1).loc[['enterpriseValue'], :].transpose()
    df_1['marketCap'] = [yahoo_financials.get_market_cap()]

    return df_1
    def __init__(self, ticker, name, risk_free_return):
        yf_stock = YF(ticker)
        yf_stats = si.get_stats(ticker)
        key_statistics = yf_stock.get_key_statistics_data()

        self.ticker = ticker

        self.name = name

        self.risk_free_return = risk_free_return

        self.beta = self.get_beta(yf_stock, yf_stats)

        self.wacc = self.get_wacc(yf_stock)

        self.growth_estimate_per_annum = self.get_growth_estimate_per_annum()

        self.conservative_growth_rate = self.get_conservative_growth_rate()

        self.recommendation_rating = self.get_recommendation_rating()

        self.free_cash_flow = self.get_free_cash_flow()

        self.price = round(si.get_live_price(ticker), 2)

        self.shares_outstanding = float(
            round(key_statistics[self.ticker]['sharesOutstanding'] / 1000000,
                  2))

        self.profit_margin = yf_stats["Value"][30]

        self.operating_margin = yf_stats["Value"][31]

        self.return_on_assets = yf_stats["Value"][32]

        self.return_on_equity = yf_stats["Value"][33]

        self.book_value = yf_stats["Value"][47]

        self.quarterly_revenue_growth_yoy = yf_stats["Value"][36]

        self.cash = yf_stats["Value"][42]

        self.trailing_pe = self.get_trailing_pe(yf_stock)

        self.price_per_book = round(self.price / float(self.book_value), 2)

        self.cash_and_cash_equivalents = float(
            re.sub("[^\d\.\-]", "", self.cash)) * 1000

        self.total_liabilities = self.get_total_liabilities(yf_stock)

        self.intrinsic_value = self.get_intrinsic_value()

        self.potential_upside = self.get_potential_upside()

        self.trailing_pe_pb_multiple = round(
            self.trailing_pe * self.price_per_book, 2)
Esempio n. 5
0
def getMarketData():
    tickers = 'AAPL'
    financials = YahooFinancials(tickers)

    #	company_stock_price = financials.get_stock_price_data() #gets stock price information

    historical_stock_prices_data = financials.get_historical_price_data(
        '2015-11-21', '2020-11-21',
        'daily')  #gets historical daily stock price of company
    #	get_Div_data(historical_stock_prices_data[tickers])
    get_stock_price_data(historical_stock_prices_data[tickers])

    #	company_balance_sheet_data_qt = financials.get_financial_stmts('quarterly', 'balance') #get balance sheet
    #	company_income_statement_data_qt = financials.get_financial_stmts('quarterly', 'income') #get income statement

    company_key_statistics_data = financials.get_key_statistics_data(
    )  #includes profit margins, forward eps, yearly change etc.
    #	get_forward_pe(company_key_statistics_data[tickers])
    #	get_trailing_eps(company_key_statistics_data[tickers])
    #	get_foward_eps(company_key_statistics_data[tickers])
    #	get_ytdReturn(company_key_statistics_data[tickers])

    company_earnings_data = financials.get_stock_earnings_data(
    )  #historical eps only for 1 year span
    #	get_earnings_data(company_earnings_data[tickers])

    company_dividend_yield = financials.get_dividend_yield(
    )  #current dividends yield
    company_dividend = financials.get_dividend_rate()  #current dividends rate
    company_avg_div_yield_1year = financials.get_annual_avg_div_yield(
    )  #average 1 year div yield
    company_avg_div_yield_5year = financials.get_five_yr_avg_div_yield(
    )  #average 5 year div yield
    company_eps = financials.get_earnings_per_share()  #current eps
    company_pe = financials.get_pe_ratio()  #current pe ratio
    company_beta = financials.get_beta()  #current beta
    company_current_stock_price = financials.get_current_price(
    )  #current stock price

    company_revenue = financials.get_total_revenue()  #current company revenue
    company_operating_income = financials.get_operating_income(
    )  #current company operating income
    company_net_income = financials.get_net_income()  #current net income

    company_yearly_high = financials.get_yearly_high()  #get yearly high
    company_yearly_low = financials.get_yearly_low()  #get yearly low
    company_moving_50 = financials.get_50day_moving_avg(
    )  #50 day moving average of stock
    company_moving_200 = financials.get_200day_moving_avg(
    )  #200 day moving average of stock
Esempio n. 6
0
 def get(self, ticker: str) -> asset_returns:
     try:
         ticker = ticker.upper()
         yf = YahooFinancials(ticker)
         quote_type_data = yf.get_stock_quote_type_data()
         # This one seems very slow
         key_stats = yf.get_key_statistics_data()
         return json.dumps({
             'ticker': ticker,
             'quote_type_data': quote_type_data[ticker],
             'key_stats': key_stats[ticker]
         })
     except Exception as e:
         return {'message': 'Unable to retrive prices'}, 500
Esempio n. 7
0
def get_stock_data(stock_data):
    symbol = stock_data['symbol']
    start = time.time()
    print('start: {}'.format(symbol))
    Stock = YahooFinancials(symbol)
    stock_data['pe_ratio'] = Stock.get_pe_ratio()
    if stock_data['pe_ratio'] != None and stock_data['pe_ratio'] < 15:
        key_stock_data = Stock.get_key_statistics_data()
        stock_data['pb_ratio'] = key_stock_data[symbol]['priceToBook']
        if stock_data['pb_ratio'] != None and stock_data['pb_ratio'] < 1.5:
            balance_sheet_data = Stock.get_financial_stmts('annual', 'balance')
            income_sheet_data = Stock.get_financial_stmts('annual', 'income')
            bal1 = balance_sheet_data['balanceSheetHistory'][symbol][0]
            bal2 = balance_sheet_data['balanceSheetHistory'][symbol][1]
            bal3 = balance_sheet_data['balanceSheetHistory'][symbol][2]
            bal4 = balance_sheet_data['balanceSheetHistory'][symbol][3]
            bal1_key1 = next(iter(bal1))
            bal2_key1 = next(iter(bal2))
            bal3_key1 = next(iter(bal3))
            bal4_key1 = next(iter(bal4))
            inc1 = income_sheet_data['incomeStatementHistory'][symbol][0]
            inc2 = income_sheet_data['incomeStatementHistory'][symbol][1]
            inc3 = income_sheet_data['incomeStatementHistory'][symbol][2]
            inc4 = income_sheet_data['incomeStatementHistory'][symbol][3]
            inc1_key1 = next(iter(inc1))
            inc2_key1 = next(iter(inc2))
            inc3_key1 = next(iter(inc3))
            inc4_key1 = next(iter(inc4))

            stock_data['liabilities'] = bal1[bal1_key1][
                'totalCurrentLiabilities']
            stock_data['assets'] = bal1[bal1_key1]['totalCurrentAssets']
            stock_data['equity1'] = bal1[bal1_key1]['totalStockholderEquity']
            stock_data['equity2'] = bal2[bal2_key1]['totalStockholderEquity']
            stock_data['equity3'] = bal3[bal3_key1]['totalStockholderEquity']
            stock_data['equity4'] = bal4[bal4_key1]['totalStockholderEquity']
            stock_data['net_income1'] = inc1[inc1_key1]['netIncome']
            stock_data['net_income2'] = inc2[inc2_key1]['netIncome']
            stock_data['net_income3'] = inc3[inc3_key1]['netIncome']
            stock_data['net_income4'] = inc4[inc4_key1]['netIncome']

            db = sqlite3.connect('stocks.db')
            c = db.cursor()
            c.execute(
                '''INSERT INTO stocks (
                    symbol,
                    company_name,
                    pb_ratio,
                    pe_ratio,
                    assets,
                    liabilities,
                    net_income1,
                    net_income2,
                    net_income3,
                    net_income4,
                    equity1,
                    equity2,
                    equity3,
                    equity4
                    )
                VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
                (stock_data['symbol'], stock_data['company_name'],
                 stock_data['pb_ratio'], stock_data['pe_ratio'],
                 stock_data['assets'], stock_data['liabilities'],
                 stock_data['net_income1'], stock_data['net_income2'],
                 stock_data['net_income3'], stock_data['net_income4'],
                 stock_data['equity1'], stock_data['equity2'],
                 stock_data['equity3'], stock_data['equity4']))
            db.commit()
    del stock_data
    end = time.time()
    print('got: {} - {}'.format(symbol, round(end - start)))
    return None
Esempio n. 8
0
import pandas as pd
import yfinance as yf
from yahoofinancials import YahooFinancials

yahoo_financials = YahooFinancials('MMM')
print(yahoo_financials.get_key_statistics_data())

#assets = ['TSLA', 'MSFT', 'FB']
#
#yahoo_financials = YahooFinancials('BTC-USD')
#
##data = yahoo_financials.get_summary_data()
#data = yahoo_financials.get_key_statistics_data()
##get_historical_price_data(start_date='2019-01-01',
##                                                  end_date='2019-12-31',
##                                                  time_interval='weekly')
##
##prices_df = pd.DataFrame({
##    a: {x['formatted_date']: x['adjclose'] for x in data[a]['prices']} for a in assets
##})
#print(data)
Esempio n. 9
0
class Company(object):
    def __init__(self, ticker):
        self.ticker = ticker.upper()
        self.financials = YahooFinancials(ticker)
        self.timeframe = 'annual'
        self.balance_sheet = None
        self.income_statement = None
        self.cash_flow_statement = None
        self.key_statistics = None
        self.historical_eps = None
        self.price_data = None
        self.new_corporate_tax_rate = 0.21
        self.old_corporate_tax_rate = 0.35
        self.risk_free_ror = 0.025
        self.market_ror = 0.098

    def __set_balance_sheet(self):
        if str(type(self.balance_sheet)) == "<class 'NoneType'>":
            try:
                self.balance_sheet = self.financials.get_financial_stmts(
                    self.timeframe,
                    'balance')['balanceSheetHistory'][self.ticker]
                self.balance_sheet = self.__clean_statement_timestamp(
                    self.balance_sheet)
            except:
                return None

    def __set_income_statement(self):
        if str(type(self.income_statement)) == "<class 'NoneType'>":
            try:
                self.income_statement = self.financials.get_financial_stmts(
                    self.timeframe,
                    'income')['incomeStatementHistory'][self.ticker]
                self.income_statement = self.__clean_statement_timestamp(
                    self.income_statement)
            except:
                return None

    def __set_cash_flow_statement(self):
        if str(type(self.cash_flow_statement)) == "<class 'NoneType'>":
            try:
                self.cash_flow_statement = self.financials.get_financial_stmts(
                    self.timeframe,
                    'cash')['cashflowStatementHistory'][self.ticker]
                self.cash_flow_statement = self.__clean_statement_timestamp(
                    self.cash_flow_statement)
            except:
                return None

    def __set_key_statistics(self):
        if str(type(self.key_statistics)) == "<class 'NoneType'>":
            try:
                self.key_statistics = self.financials.get_key_statistics_data()
            except:
                return None

    def __set_historical_eps(self):
        if str(type(self.historical_eps)) == "<class 'NoneType'>":
            url = 'https://www.nasdaq.com/earnings/report/{}'.format(
                self.ticker)
            page = requests.get(url)
            if page.status_code == 200:
                soup = BeautifulSoup(page.text, 'html.parser')
                eps_list = []
                td = soup.find_all('td')
                counter = 0
                for i in td[2::5]:
                    try:
                        test = float(i.get_text())
                        counter += 1
                    except:
                        break
                for i in range(counter * 5):
                    eps_list.append(list(soup.find_all('td'))[i].get_text())
                self.historical_eps = pd.DataFrame({
                    'textdate':
                    eps_list[0::5],
                    'timestamp':
                    eps_list[1::5],
                    'eps':
                    eps_list[2::5],
                    'consensus_eps':
                    eps_list[3::5],
                    'surprise':
                    eps_list[4::5]
                })
                self.historical_eps = self.historical_eps.iloc[::-1]
                self.historical_eps.reset_index(inplace=True, drop=True)
            else:
                return None

    def __set_price_data(self):
        if str(type(self.price_data)) == "<class 'NoneType'>":
            try:
                self.price_data = pd.DataFrame(
                    self.financials.get_historical_price_data(
                        '1800-01-01',
                        str(datetime.now())[:10],
                        'daily')[self.ticker]['prices'])
            except:
                pass

    def __clean_statement_timestamp(self, statement):
        for i in statement:
            for j in i.keys():
                i[j[:4]] = i.pop(j)
        return statement

    def __get_specific_year(self, statement, year):
        for i in statement:
            if str(list(i.keys())[0]) == str(year):
                return i['{}'.format(year)]

    def __json_to_dataframe(self, data):
        columns = []
        for i in data:
            for j in i.keys():
                columns.append(j)
        df = pd.DataFrame(data[0])
        for i in range(len(columns)):
            df[columns[i]] = pd.DataFrame(data[i])
        df = df[df.columns[::-1]]
        return df

    def set_risk_free_ror(self, risk_free_ror):
        self.risk_free_ror = risk_free_ror

    def set_market_ror(self, market_ror):
        self.market_ror = market_ror

    def check_risk_free_ror(self):
        return self.risk_free_ror

    def check_market_ror(self):
        return self.market_ror

    def check_old_corporate_tax_rate(self):
        return self.old_corporate_tax_rate

    def check_new_corporate_tax_rate(self):
        return self.new_corporate_tax_rate

    def get_balance_sheet(self):
        self.__set_balance_sheet()
        df = self.__json_to_dataframe(self.balance_sheet)
        return df

    def get_income_statement(self):
        self.__set_income_statement()
        df = self.__json_to_dataframe(self.income_statement)
        return df

    def get_cash_flow_statement(self):
        self.__set_cash_flow_statement()
        df = self.__json_to_dataframe(self.cash_flow_statement)
        return df

    def get_key_statistics(self):
        self.__set_key_statistics()
        ser = pd.Series(self.key_statistics[self.ticker])
        return ser

    def get_historical_eps(self):
        self.__set_historical_eps()
        return self.historical_eps

    def get_price_data(self):
        self.__set_price_data()
        return self.price_data

    def check_ticker(self):
        return self.ticker

    def revenue(self, year):
        self.__set_income_statement()
        try:
            return self.__get_specific_year(self.income_statement,
                                            year)['totalRevenue']
        except:
            return None

    def total_expenses(self, year):
        self.__set_income_statement()
        self.__set_cash_flow_statement()
        try:
            operating_expenses = self.__get_specific_year(
                self.income_statement, year)['totalOperatingExpenses']
            interest = self.__get_specific_year(self.income_statement,
                                                year)['interestExpense']
            tax = self.__get_specific_year(self.income_statement,
                                           year)['incomeTaxExpense']
            depreciation = self.__get_specific_year(self.cash_flow_statement,
                                                    year)['depreciation']
            return abs(operating_expenses) + abs(interest) + abs(tax) + abs(
                depreciation)
        except:
            return None

    def operating_expenses(self, year):
        self.__set_income_statement()
        try:
            return self.__get_specific_year(self.income_statement,
                                            year)['totalOperatingExpenses']
        except:
            return None

    def outstanding_shares(self):
        self.__set_key_statistics()
        try:
            return self.get_key_statistics()['sharesOutstanding']
        except:
            return None

    def share_price(self):
        self.__set_price_data()
        try:
            return float(self.price_data[-1:]['close'])
        except:
            return None

    def market_value(self):
        try:
            return self.share_price() * self.outstanding_shares()
        except:
            return None

    def liquid_assets(self, year):
        self.__set_balance_sheet()
        try:
            return self.__get_specific_year(
                self.balance_sheet, year)['cash'] + self.__get_specific_year(
                    self.balance_sheet, year)['shortTermInvestments']
        except:
            return None

    def total_debt(self, year):
        self.__set_balance_sheet()
        try:
            return self.__get_specific_year(
                self.balance_sheet,
                year)['shortLongTermDebt'] + self.__get_specific_year(
                    self.balance_sheet, year)['longTermDebt']
        except:
            return None

    def tax(self, year):
        self.__set_income_statement()
        try:
            return abs(
                self.__get_specific_year(self.income_statement,
                                         year)['incomeTaxExpense'])
        except:
            return None

    def interest(self, year):
        self.__set_income_statement()
        try:
            return self.__get_specific_year(self.income_statement,
                                            year)['interestExpense']
        except:
            return None

    def depreciation(self, year):
        self.__set_cash_flow_statement()
        try:
            return self.__get_specific_year(self.cash_flow_statement,
                                            year)['depreciation']
        except:
            return None

    def cost_of_revenue(self, year):
        self.__set_income_statement()
        try:
            return self.__get_specific_year(self.income_statement,
                                            year)['costOfRevenue']
        except:
            return None

    def total_receivables(self, year):
        self.__set_balance_sheet()
        try:
            return self.__get_specific_year(self.balance_sheet,
                                            year)['netReceivables']
        except:
            return None

    def total_liabilities(self, year):
        self.__set_balance_sheet()
        try:
            return self.__get_specific_year(self.balance_sheet,
                                            year)['totalLiab']
        except:
            return None

    def total_assets(self, year):
        self.__set_balance_sheet()
        try:
            return self.__get_specific_year(self.balance_sheet,
                                            year)['totalAssets']
        except:
            return None

    def total_capital(self, year):
        self.__set_balance_sheet()
        try:
            return self.__get_specific_year(
                self.balance_sheet,
                year)['totalStockholderEquity'] + self.total_debt(year)
        except:
            return None

    def total_equity(self, year):
        try:
            return self.total_assets(year) - self.total_liabilities(year)
        except:
            return None

    def capital_expenditures(self, year):
        self.__set_cash_flow_statement()
        try:
            return self.__get_specific_year(self.cash_flow_statement,
                                            year)['capitalExpenditures']
        except:
            return None

    def net_income(self, year):
        self.__set_income_statement()
        try:
            return self.__get_specific_year(self.income_statement,
                                            year)['netIncome']
        except:
            return None

    def gross_profit(self, year):
        self.__set_income_statement()
        try:
            return self.__get_specific_year(self.income_statement,
                                            year)['grossProfit']
        except:
            return None

    def earnings_per_share(self):
        try:
            return self.financials.get_earnings_per_share()
        except:
            return None

    def pe_ratio(self):
        try:
            return self.financials.get_pe_ratio()
        except:
            return None

    def enterprise_value(self):
        try:
            return self.get_key_statistics()['enterpriseValue']
        except:
            return None

    def ebit(self, year):
        self.__set_income_statement()
        try:
            return self.__get_specific_year(self.income_statement,
                                            year)['ebit']
        except:
            return None

    def ebitda(self, year):
        try:
            temp_net_income = abs(self.net_income(year))
            temp_tax = abs(self.tax(year))
            temp_interest = abs(self.interest(year))
            temp_depreciation = abs(self.depreciation(year))
            return temp_net_income + temp_tax + temp_interest + temp_depreciation
        except:
            return None

    def quick_ratio(self, year):
        try:
            temp_liquid_assets = abs(self.liquid_assets(year))
            temp_receivables = abs(self.total_receivables(year))
            temp_liabilities = abs(self.total_liabilities(year))
            return (temp_liquid_assets + temp_receivables) / temp_liabilities
        except:
            return None

    def income_continuing_operations_margin(self, year):
        try:
            temp_ebit = self.ebit(year)
            temp_revenue = abs(self.revenue(year))
            return temp_ebit / temp_revenue
        except:
            return None

    def net_margin(self, year):
        try:
            temp_net_income = self.net_income(year)
            temp_revenue = self.revenue(year)
            return temp_net_income / temp_revenue
        except:
            return None

    def return_on_assets(self, year):
        try:
            ending_year = year
            beginning_year = year - 1
            temp_net_income = self.net_income(year)
            beginning_total_assets = abs(self.total_assets(beginning_year))
            ending_total_assets = abs(self.total_assets(ending_year))
            return temp_net_income / (
                (beginning_total_assets + ending_total_assets) / 2)
        except:
            return None

    def return_on_capital(self, year):
        try:
            ending_year = year
            beginning_year = year - 1
            if ending_year >= 2018:
                temp_ebit = self.ebit(year)
                temp_tax_rate = self.new_corporate_tax_rate
                beginning_total_capital = abs(
                    self.total_capital(beginning_year))
                ending_total_capital = abs(self.total_capital(ending_year))
                return (temp_ebit * (1 - temp_tax_rate)) / (
                    (beginning_total_capital + ending_total_capital) / 2)
            elif ending_year < 2018:
                temp_ebit = self.ebit(year)
                temp_tax_rate = self.old_corporate_tax_rate
                beginning_total_capital = abs(
                    self.total_capital(beginning_year))
                ending_total_capital = abs(self.total_capital(ending_year))
                return (temp_ebit * (1 - temp_tax_rate)) / (
                    (beginning_total_capital + ending_total_capital) / 2)
        except:
            return None

    def return_on_equity(self, year):
        try:
            temp_ebit = self.ebit(year)
            temp_total_equity = abs(self.total_equity(year))
            return temp_ebit / temp_total_equity
        except:
            return None

    def cash_flow_operations(self, year):
        try:
            temp_revenue = abs(self.revenue(year))
            temp_operating_expenses = abs(self.operating_expenses(year))
            return temp_revenue - temp_operating_expenses
        except:
            return None

    def free_cash_flow(self, year):
        try:
            if year >= 2018:
                temp_cfo = self.cash_flow_operations(year)
                temp_interest = self.interest(year)
                temp_tax_rate = self.new_corporate_tax_rate
                temp_capex = self.capital_expenditures(year)
                return temp_cfo + (temp_interest *
                                   (1 - temp_tax_rate)) - temp_capex
            elif year < 2018:
                temp_cfo = self.cash_flow_operations(year)
                temp_interest = self.interest(year)
                temp_tax_rate = self.old_corporate_tax_rate
                temp_capex = self.capital_expenditures(year)
                return temp_cfo + (temp_interest *
                                   (1 - temp_tax_rate)) - temp_capex
        except:
            return None

    def beta(self):
        try:
            return self.financials.get_beta()
        except:
            return None

    def cost_of_equity(self):
        try:
            return self.risk_free_ror + (
                self.beta() * (self.market_ror - self.risk_free_ror))
        except:
            return None

    def gross_profit_margin(self, year):
        try:
            return (self.revenue(year) -
                    self.cost_of_revenue(year)) / self.revenue(year)
        except:
            return None

    def operating_profit_margin(self, year):
        try:
            return self.ebit(year) / self.revenue(year)
        except:
            return None

    def net_profit_margin(self, year):
        try:
            return self.net_income(year) / self.revenue(year)
        except:
            return None

    def short_ratio(self):
        try:
            return self.get_key_statistics()['shortRatio']
        except:
            return None
Esempio n. 10
0
def get_data():
    COMPANIES = ['FMC', 'GME', 'PTON', 'U']
    portforlio_cmp = {
        "GME": {
            "num_shares": 2,
            "value": 0.0,
            "weight": 0.0,
            "beta": 0.0,
            "weighted_beta": 0.0
        },
        "FMC": {
            "num_shares": 8,
            "value": 0.0,
            "weight": 0.0,
            "beta": 0.0,
            "weighted_beta": 0.0
        },
        "U": {
            "num_shares": 4,
            "value": 0.0,
            "weight": 0.0,
            "beta": 1.16,
            "weighted_beta": 0.0
        },
        "PTON": {
            "num_shares": 8,
            "value": 0.0,
            "weight": 0.0,
            "beta": 0.31,
            "weighted_beta": 0.0
        }
    }
    # COMPANIES = ['AAPL', 'AMZN', 'NVDA', 'TSLA']
    # portforlio_cmp = {
    #             "AAPL":{"num_shares":100, "value":0.0, "weight":0.0, "beta":0.0, "weighted_beta":0.0},
    #             "AMZN":{"num_shares":100, "value":0.0, "weight":0.0, "beta":0.0, "weighted_beta":0.0},
    #             "NVDA":{"num_shares":40, "value":0.0, "weight":0.0, "beta":0.0, "weighted_beta":0.0},
    #             "TSLA":{"num_shares":30, "value":0.0, "weight":0.0, "beta":0.0, "weighted_beta":0.0}
    #                 }

    # Set Object
    yfs = YahooFinancials(COMPANIES)

    # Set date range
    # today = date.today()
    # dta = timedelta(days=3)
    # prev = today - dta
    # d1 = today.strftime("%Y-%m-%d")
    # d2 = prev.strftime("%Y-%m-%d")

    # # maket the call
    print("pull stock data...")
    # data = yfs.get_historical_price_data(start_date=d2,
    #                                      end_date=d1,
    #                                      time_interval='monthly')
    stats_data = yfs.get_key_statistics_data()

    total_asset_price = 0.0
    print("updating weight...")
    print(
        "------------------------------------------------------------------------------------------------------------"
    )
    for stock in portforlio_cmp:
        print(stock)

        print("number of shares: " + str(portforlio_cmp[stock]["num_shares"]))
        ticker = yf.Ticker(stock)
        todays_data = ticker.history(period='1d')
        print("price: " + str(todays_data['Close'][0]))
        print("----------------------------------------")
        portforlio_cmp[stock]["value"] = todays_data['Close'][
            0] * portforlio_cmp[stock]["num_shares"]
        # portforlio_cmp[stock]["value"] = float(data[stock]['prices'][-1]['close']) * portforlio_cmp[stock]["num_shares"]
        total_asset_price += portforlio_cmp[stock]["value"]
    print(
        "------------------------------------------------------------------------------------------------------------"
    )
    # Calculate R_f
    ticker = yf.Ticker('^TNX')
    todays_data = ticker.history(period='1d')
    expected_return_risk_free = todays_data['Close'][0] / 100

    # update the weight
    portforlio_beta = 0.0
    for stock in portforlio_cmp:
        portforlio_cmp[stock][
            "weight"] = portforlio_cmp[stock]["value"] / total_asset_price
        print(stock + " beta: " + str(portforlio_cmp[stock]["beta"]))
        if stats_data[stock]['beta'] is None:
            portforlio_cmp[stock]["weighted_beta"] = portforlio_cmp[stock][
                "weight"] * portforlio_cmp[stock]["beta"]
        else:
            portforlio_cmp[stock]["weighted_beta"] = portforlio_cmp[stock][
                "weight"] * float(stats_data[stock]['beta'])
        portforlio_beta += portforlio_cmp[stock]["weighted_beta"]

    print(
        "------------------------------------------------------------------------------------------------------------"
    )
    print("Portfolio Beta: " + str(portforlio_beta))

    portfolio_expected_return = expected_return_risk_free + portforlio_beta * (
        0.1 - expected_return_risk_free)
    print("Expected Return: " + str(portfolio_expected_return))
def yahoo_data():
    #ticker needs to be in ["nvda","yahoo"] format
    # #date needs to be in (YYYY,M,D) format
    start = datetime.datetime(2005, 1, 1)

    # We define the end date as the date from today.
    end = datetime.datetime.now().date()

    # The input for the code follows. With the while and try function the code will ask the user to enter the tickers again in case if there was an error.
    # The variable var is first set on 1 an changed to 0 as soon as entering the input was successful.
    var = 1
    while (var == 1):
        try:
            # The input is converted to upperletters in case it isn't to avoid identification problems with yahoo. The string is splitted in to single elements and stored in a list.
            inputone = input(
                "Enter the tickers of four stocks, you'd like to analyze, like 'GOOG AAPL NFLX TSLA': "
            )
            inputonesplitted = inputone.upper()
            tickers = inputonesplitted.split()
            var = 0

            # If the user enters less than for tickers, he is asked to enter four of them, until he does so.
            while (len(tickers) < 4):
                inputone = input(
                    "You entered less than four tickers. Please enter four of them: "
                )
                inputonesplitted = inputone.upper()
                tickers = inputonesplitted.split()
            var = 0

            # If the user enters more than for tickers, he is asked to enter four of them, until he does so.
            while (len(tickers) > 4):
                inputone = input(
                    "You entered more than four tickers. Please enter four of them: "
                )
                inputonesplitted = inputone.upper()
                tickers = inputonesplitted.split()
            var = 0

        except:
            print("Something went wrong. Try it again!")
            var = 1
    #Takes only the adjusted closing prices from yahoo
    prices = web.DataReader(tickers, "yahoo", start, end)['Adj Close']
    #standardize to compare the time series

    #build returns. Takes all information from yahoo
    returns = web.DataReader(tickers, "yahoo", start, end)
    #daily_returns = returns['Adj Close'].pct_change()
    monthly_returns = returns['Adj Close'].resample('M').ffill().pct_change()

    #create a summary list for the stocks
    summary = monthly_returns.describe()
    summary = summary.round(3)
    #mean_daily_returns = daily_returns.mean()

    #We take from yahoo_financials all the summary data about the ticker like beta P/E ratio etc
    #Output is in json datastring
    YF = YahooFinancials(tickers)
    rate = YF.get_key_statistics_data()
    #We transform the json string to a pandas dataframe
    rate = pd.DataFrame(rate)

    #We only take certain ratios with names like beta bookValue etc from column 0 (axis=0)
    facts = rate.filter(
        {
            'beta', 'bookValue', 'priceToBook', 'forwardPE', 'profitMargins',
            'enterpriseToRevenue', 'enterpriseToEbitda',
            'earningsQuarterlyGrowth'
        },
        axis=0)
    #We make a separate variable with the enterprise values (ev)
    ev = rate.filter({'enterpriseValue'}, axis=0)

    #inc=pd.DataFrame(YF.get_financial_stmts('annual', 'balance',reformat=True))

    ####################                   create the csv files                %%%%%%%%%%%%%%%%
    # get relative data folder
    PATH = pathlib.Path(__file__).parent
    DATA_PATH = PATH.joinpath("./data").resolve()

    #Save the collected data to data folder
    prices.to_csv(DATA_PATH.joinpath("prices.csv"))
    monthly_returns.to_csv(DATA_PATH.joinpath("monthly_returns.csv"))
    summary.to_csv(DATA_PATH.joinpath("summary.csv"))
    facts.to_csv(DATA_PATH.joinpath("facts.csv"))
    ev.to_csv(DATA_PATH.joinpath("ev.csv"))