Ejemplo n.º 1
0
def bar_chart_input(search_btn,search):
    if search_btn:
        cashflow = si.get_cash_flow(search)
        cf = cashflow.T
    else:
        cashflow = si.get_cash_flow("aapl")
        cf = cashflow.T

    cf["date"] = cf.index
    date= cf["date"].dt.year
    op = (cf["totalCashFromOperatingActivities"]/1000000000).astype(float).round(2)
    invest = (cf["totalCashflowsFromInvestingActivities"]/1000000000).astype(float).round(2)
    fin = (cf["totalCashFromFinancingActivities"]/1000000000).astype(float).round(2)

    color, color2, color3 = np.array(['rgb(255,255,255)']*op.shape[0]), np.array(['rgb(255,255,255)']*invest.shape[0]), np.array(['rgb(255,255,255)']*fin.shape[0])
    color[op<0],  color2[invest<0],  color3[fin<0]='crimson','crimson','crimson'
    color[op>=0], color2[invest>=0],  color3[fin>=0]='green','green','green'

    fig4 = go.Figure(data=[
        go.Bar(name='Operating', x=date, y=cf["totalCashFromOperatingActivities"],marker=dict(color=color.tolist()), text = op,textfont_size=8, textposition='outside',),
        go.Bar(name='Investing', x=date, y=cf["totalCashflowsFromInvestingActivities"],marker=dict(color=color2.tolist()),  text = invest,textfont_size=8, textposition='outside',),
        go.Bar(name='Financing', x=date, y=cf["totalCashFromFinancingActivities"],marker=dict(color=color3.tolist()),  text = fin,textfont_size=8, textposition='outside',),
    ])
    # Change the bar mode
    fig4.update_layout(barmode='group',title_text='Cash Flow',title_x=0.5,width = 444,margin=dict(t=70,b=20,l=55,r=40),paper_bgcolor='rgba(0,0,0,0)',plot_bgcolor='rgba(0,0,0,0)')
    fig4.update_layout(legend=dict(orientation="h",yanchor="bottom",y=1,xanchor="right",x=0.85,font=dict(size=9,),))
    #fig4.update_xaxes(showline=False,zeroline=True,linewidth=1, linecolor='Black',tickfont=dict(size=10))
    return fig4
Ejemplo n.º 2
0
def is_available(stock_nm):
    try:
        income_statement = si.get_income_statement(stock_nm)
        balance_sheet = si.get_balance_sheet(stock_nm)
        cash_flow_statement = si.get_cash_flow(stock_nm)
        my_stock_price(stock_nm)
    except (IOError, KeyError):
        None
Ejemplo n.º 3
0
def cash(request):
    ticker = json.loads(request.body)['ticker']

    if not ticker:
        return HttpResponse('ticker not received')
    else:
        info = si.get_cash_flow(ticker)
        # print info to a text buffer
        with io.StringIO() as buf, redirect_stdout(buf):
            print(info)
            output = buf.getvalue()

        return HttpResponse(output)
Ejemplo n.º 4
0
def my_stock_rank(stock_nm):
    #print(stock_nm)
    stock_nm = "NESTLEIND.NS"
    stock_stats = si.get_stats(stock_nm)
    low_52 = float(
        stock_stats[stock_stats.Attribute == '52 Week Low 3'].Value.item())
    dma_200 = float(stock_stats[stock_stats.Attribute ==
                                '200-Day Moving Average 3'].Value.item())
    avg_price = (low_52 + dma_200) / 2
    cmp = si.get_live_price(stock_nm)
    buy_price_gap = ((cmp - avg_price) / avg_price) * 100
    #print (buy_price_gap)
    curr_row = stock_nm + ',' + str(round(buy_price_gap, 2))
    print(curr_row)
    #df = df.append(curr_row)

    income_statement = si.get_income_statement(stock_nm)
    balance_sheet = si.get_balance_sheet(stock_nm)
    cash_flow_statement = si.get_cash_flow(stock_nm)

    income_statement.fillna(0, inplace=True)
    income_statement = income_statement.div(10000000).astype(int)

    balance_sheet.fillna(0, inplace=True)
    balance_sheet = balance_sheet.div(10000000).astype(int)

    cash_flow_statement.fillna(0, inplace=True)
    cash_flow_statement = cash_flow_statement.div(10000000).astype(int)

    income_statement_df = income_statement.transpose()
    balance_sheet_df = balance_sheet.transpose()
    cash_flow_statement_df = cash_flow_statement.transpose()

    revenue = income_statement_df['totalRevenue']
    revenue.sort_index()
    end_value = float(revenue.iloc[0])
    mcap = stock_stats[stock_stats.Attribute ==
                       'Market Cap (intraday) 5'].Value.item()

    if mcap.find("T") == -1:
        print("No 'is' here!")
    else:
        print("Found 'is' in the string.")
Ejemplo n.º 5
0
def getAcctgInfo(ticker):
    global balance_sheet
    global income_statement
    global cfs
    global periods
    balance_sheet = yf.get_balance_sheet(ticker, yearly=False)
    income_statement = yf.get_income_statement(ticker, yearly=False)
    cfs = yf.get_cash_flow(ticker, yearly=False)
    periods = balance_sheet.columns
    cq = periods[0]
    pq = periods[1]
    cq_rev = income_statement[periods[0]]['totalRevenue']
    pq_rev = income_statement[periods[1]]['totalRevenue']
    cq_ni = income_statement[periods[0]]['netIncome']
    pq_ni = income_statement[periods[1]]['netIncome']
    cq_cash = balance_sheet[periods[0]]['cash']
    pq_cash = balance_sheet[periods[1]]['cash']
    cq_ocf = cfs[periods[0]]['totalCashFromOperatingActivities']
    pq_ocf = cfs[periods[1]]['totalCashFromOperatingActivities']
    acctginfo.append((ticker, cq, pq, cq_rev, pq_rev, cq_ni, pq_ni, cq_cash,
                      pq_cash, cq_ocf, pq_ocf))
Ejemplo n.º 6
0
 def oif_cash(self, tck):
     cf = []
     oc = int(
         get_cash_flow(tck).loc[
             get_cash_flow(tck)['Breakdown'] ==
             "Net cash provided by operating activites"].iloc[:, 1])
     ic = int(
         get_cash_flow(
             tck).loc[get_cash_flow(tck)['Breakdown'] ==
                      "Net cash used for investing activites"].iloc[:, 1])
     fc = int(
         get_cash_flow(tck).loc[
             get_cash_flow(tck)['Breakdown'] ==
             "Net cash used privided by (used for) financing activities"].
         iloc[:, 1])
     cf.append(oc, ic, fc)
     return cf
Ejemplo n.º 7
0
def Statement():
    page_bg_img = '''
    <style>
    body {
    background-image: url("https://images.pexels.com/photos/2748757/pexels-photo-2748757.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=1000");
    background-size: cover;
    }
    </style>
    '''
    st.markdown(page_bg_img, unsafe_allow_html=True)
    symbols = 'https://raw.githubusercontent.com/Moly-malibu/Stocks/main/bxo_lmmS1.csv'
    df = pd.read_csv(symbols)
    ticker = st.sidebar.selectbox('Stocks by Company', (df['Symbol']))
    tickerData = YahooFinancials(ticker)

    def get_symbol(symbol):
        url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}&region=1&lang=en".format(
            symbol)
        result = requests.get(url).json()
        for x in result['ResultSet']['Result']:
            if x['symbol'] == symbol:
                return x['name']

    company_name = get_symbol(ticker.upper())
    st.write("""# Analysis of """, company_name)
    company = yf.Ticker(ticker)
    # st.write(company.info)
    company_general = st.sidebar.checkbox("Financial Ratio")
    if company_general:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Financial Ratios</h1>",
            unsafe_allow_html=True)
        st.write('***Payout Ratio:*** ', company.info["payoutRatio"])
        st.write('***Trailing Annual Dividend Yield:*** ',
                 company.info["trailingAnnualDividendYield"])
        st.write('***Dividend Rate:*** ', company.info["dividendRate"])
        st.write('***Profit Margins: ***', company.info["profitMargins"])
        st.write('***Peg Ratio: ***', company.info["pegRatio"])
        yahoo_financials = YahooFinancials(ticker)
        marketcap = yahoo_financials.get_market_cap()
        price_to_sales = yahoo_financials.get_current_price()
        dividend_yield = yahoo_financials.get_dividend_yield()
        income_balance = si.get_income_statement(ticker)
        transpose_income = income_balance.transpose()
        balance_income = si.get_balance_sheet(ticker)
        transpose_balance = balance_income.transpose()
        st.write("""**Dividends**""", company.dividends)
        income = si.get_income_statement(ticker)
        transpose = income.transpose()
        interest_coverage1 = transpose['operatingIncome']
        interest_coverage2 = transpose['interestExpense']
        st.write(
            '***Interest Coverage:*** Operating Income / interest Expenses',
            interest_coverage1 / interest_coverage2)
        gross_profit_margin1 = transpose['totalRevenue']
        gross_profit_margin2 = transpose['costOfRevenue']
        st.write(
            '***Gross Profit Margin:*** Total Revenue / Gross Profit Margin',
            (gross_profit_margin1 - gross_profit_margin2) /
            gross_profit_margin1)
        balance = si.get_balance_sheet(ticker)
        transpose = balance.transpose()
        current_ratio1 = transpose['totalCurrentAssets']
        current_ratio2 = transpose['totalCurrentLiabilities']
        debt_to_assets1 = transpose['otherCurrentAssets']
        debt_to_assets2 = transpose['totalAssets']
        st.write('***Debit Assets:*** Total Debit / Total Assets',
                 (debt_to_assets1 / debt_to_assets2))
        debt_to_equity1 = transpose['otherCurrentAssets']
        debt_to_equity2 = transpose['totalStockholderEquity']
        st.write(
            '***Debit to Equity:*** Total Debit / Total Stock Holders Equity',
            (debt_to_equity1 / debt_to_equity2))
        ROE1 = transpose_income['netIncome']
        ROE2 = transpose_balance['totalStockholderEquity']
        st.write(
            '***Return On Equity ROE:*** Net Income / (Total Stock Holder Equity + Total Stock Holder Equity)/2',
            (ROE1 / ((ROE2 + ROE2) / 2)))
        ROA1 = transpose_income['netIncome']
        ROA2 = transpose_balance['totalAssets']
        st.write('***Return On Assets:*** Net Income / Total Assets',
                 (ROA1 / ROA2))

    company_simulation = st.sidebar.checkbox("Monte Carlo Simulation")
    if company_simulation:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Monte Carlo Simulation Price</h1>",
            unsafe_allow_html=True)
        st.write(
            """Monte Carlo Simulation project future price for the stocks. """)
        yahoo_financials = YahooFinancials(ticker)
        price = yahoo_financials.get_current_price()
        st.write('***Current Price:***', price)
        marketcap = yahoo_financials.get_market_cap()
        st.write('***Market Capital***', marketcap)
        income_balance = si.get_income_statement(ticker)
        transpose_income = income_balance.transpose()
        revenue = transpose_income['totalRevenue']
        st.write('***Price to sales:*** (Market Capital / Revenue',
                 marketcap / revenue)
        price_to_earnings = transpose_income['netIncome']
        st.write('***Price to Earnings:*** (Market Capital/ Net Income',
                 marketcap / price_to_earnings)
        balance_income = si.get_balance_sheet(ticker)
        transpose_balance = balance_income.transpose()
        price_to_book = transpose_balance['totalStockholderEquity']
        st.write('***Price to book:*** (marketcap/Total Stock Holders Equity',
                 marketcap / price_to_book)
        start = st.date_input("Please enter date begin Analysis: ")
        price = yf.download(ticker, start=start, end=None)['Close']
        returns = price.pct_change()
        last_price = price[-1]
        num_simulations = 1000
        num_days = 252
        num_simulations_df = pd.DataFrame()
        for x in range(num_simulations):
            count = 0
            daily_vol = returns.std()
            price_series = []
            price = last_price * (1 + np.random.normal(0, daily_vol))
            price_series.append(price)
            for y in range(num_days):
                if count == 251:
                    break
                price = price_series[count] * (1 +
                                               np.random.normal(0, daily_vol))
                price_series.append(price)
                count += 1
            num_simulations_df[x] = price_series
        fig = plt.figure()
        plt.title('Monte Carlo Simulation')
        plt.plot(num_simulations_df)
        plt.axhline(y=last_price, color='r', linestyle='-')
        plt.xlabel('Day')
        plt.ylabel('Price')
        st.set_option('deprecation.showPyplotGlobalUse', False)
        st.pyplot()
        st.write('Price Series Predict: ', num_simulations_df)
    # company_general = st.sidebar.checkbox("Quick_Ratio")
    # if company_general:
    #     st.subheader("""**Quick Ratio**""")
    #     balance=si.get_balance_sheet(ticker)
    #     transpose=balance.transpose()
    #     quick_ratio1 = transpose['otherCurrentAssets']
    #     quick_ratio2 = transpose['inventory']
    #     quick_ratio3 = transpose['otherCurrentLiab']
    #     quick_ratio = ((quick_ratio1-quick_ratio2)/quick_ratio3)
    #     if not quick_ratio2:
    #         st.write("No data available")
    #     else:
    #         st.write('(***Quick Ratio:*** CurrentAssets - Inventory)/Current Liabilities)', (quick_ratio1-quick_ratio2)/quick_ratio3)
    company_hist = st.sidebar.checkbox("Cash Flow")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Cash Flow</h1>",
            unsafe_allow_html=True)
        display_cash = si.get_cash_flow(ticker)
        if display_cash.empty == True:
            st.write("No data available")
        else:
            st.write(display_cash)
    company_hist = st.sidebar.checkbox("Income Statement")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Income Statement</h1>",
            unsafe_allow_html=True)
        display_income_stat = si.get_income_statement(ticker)
        if display_income_stat.empty == True:
            st.write("No data available")
        else:
            st.write(display_income_stat)
    company_hist = st.sidebar.checkbox("Balance Sheet")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Balance Sheet</h1>",
            unsafe_allow_html=True)
        display_balance = si.get_balance_sheet(ticker)
        if display_balance.empty == True:
            st.write("No data available")
        else:
            st.write(display_balance)
    company_hist = st.sidebar.checkbox("Quote Table")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Quote Table</h1>",
            unsafe_allow_html=True)
        display_table = si.get_quote_table(ticker, dict_result=False)
        if display_table.empty == True:
            st.write("No data available")
        else:
            st.write(display_table)
        quote_table = si.get_quote_table(ticker)
        t = quote_table["Forward Dividend & Yield"]
        st.write('Forward Dividend & Yield:', t)
        display_capital = si.get_quote_table(ticker)["Market Cap"]
        st.write('Market Capital', display_capital)
    company_hist = st.sidebar.checkbox("Call Option")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Call Option</h1>",
            unsafe_allow_html=True)
        c = ops.get_calls(ticker)
        transpose = c.transpose()
        st.write(transpose)
Ejemplo n.º 8
0
def stage_one_check(stock_nm, opm, avg_price_to_consider, cmp):

    #stock_nm="DMART.NS"

    income_statement = si.get_income_statement(stock_nm)
    balance_sheet = si.get_balance_sheet(stock_nm)
    cash_flow_statement = si.get_cash_flow(stock_nm)

    income_statement.fillna(0, inplace=True)
    income_statement = income_statement.div(10000000).astype(int)

    balance_sheet.fillna(0, inplace=True)
    balance_sheet = balance_sheet.div(10000000).astype(int)

    cash_flow_statement.fillna(0, inplace=True)
    cash_flow_statement = cash_flow_statement.div(10000000).astype(int)

    income_statement_df = income_statement.transpose()
    balance_sheet_df = balance_sheet.transpose()
    cash_flow_statement_df = cash_flow_statement.transpose()

    revenue = income_statement_df['totalRevenue']
    pat = income_statement_df['incomeBeforeTax']
    nprof = income_statement_df['netIncomeFromContinuingOps']

    if "netReceivables" in balance_sheet_df:
        avg_recei = balance_sheet_df['netReceivables'].mean()
        avg_recei_latest = balance_sheet_df['netReceivables']
    else:
        #print ("notfound")
        avg_recei_df = revenue
        avg_recei_df = avg_recei_df.replace(avg_recei_df, 0)
        avg_recei = avg_recei_df.mean()
        avg_recei_latest = avg_recei_df

    #avg_recei=balance_sheet_df['netReceivables'].mean()
    avg_rev_20_pct = (income_statement_df['totalRevenue'].mean() * (20 / 100))
    #avg_recei_latest=balance_sheet_df['netReceivables']

    tot_share_hold = balance_sheet_df['totalStockholderEquity'].sort_index()
    net_income = income_statement_df['netIncome'].sort_index()

    roe = (net_income / tot_share_hold) * 100
    roe_mean = roe.mean()

    np_share_hold = income_statement_df[
        'netIncomeApplicableToCommonShares'].sort_index()
    prof_cap_emp = (np_share_hold / tot_share_hold) * 100
    avg_prof_cap_emp = prof_cap_emp.mean()

    cfo = cash_flow_statement_df['totalCashFromOperatingActivities']
    CCFO = cfo.sum()
    CNPAT = income_statement_df['netIncomeApplicableToCommonShares'].sum()
    CCFO_to_CNPAT = round(CCFO / CNPAT, 2)

    if "shortLongTermDebt" in balance_sheet_df:
        short_debt = balance_sheet_df['shortLongTermDebt']
    else:
        print("notfound")
        short_debt = revenue
        short_debt = short_debt.replace(short_debt, 0)

    if "longTermDebt" in balance_sheet_df:
        long_debt = balance_sheet_df['longTermDebt']
    else:
        long_debt = revenue
        long_debt = long_debt.replace(long_debt, 0)

    total_debt = short_debt + long_debt
    # sorting.......................

    revenue.sort_index()
    pat.sort_index()
    nprof.sort_index()
    avg_recei_latest.sort_index()
    cfo.sort_index()
    total_debt.sort_index()
    """ Values updates"""

    end_value = float(revenue.iloc[0])
    start_value = float(revenue.iloc[-1])
    num_periods = len(revenue)

    if end_value < 0:
        end_value = 0.001
    else:
        end_value = end_value

    if start_value <= 0:
        start_value = 0.001
    else:
        start_value = start_value

    if start_value == end_value:
        rev_grw = 0
    else:
        rev_grw = ((end_value / start_value)**(1 / (num_periods)) - 1) * 100

    end_value = float(pat.iloc[0])
    start_value = float(pat.iloc[-1])
    num_periods = len(pat)

    if end_value < 0:
        end_value = 0.001
    else:
        end_value = end_value

    if start_value <= 0:
        start_value = 0.001
    else:
        start_value = start_value

    if start_value == end_value:
        pat_grw = 0
    else:
        pat_grw = ((end_value / start_value)**(1 / (num_periods)) - 1) * 100

    end_value = float(nprof.iloc[0])
    start_value = float(nprof.iloc[-1])
    num_periods = len(nprof)

    if end_value < 0:
        end_value = 0.001
    else:
        end_value = end_value

    if start_value <= 0:
        start_value = 0.001
    else:
        start_value = start_value
    if start_value == end_value:
        nprof_grw = 0
    else:
        nprof_grw = ((end_value / start_value)**(1 / (num_periods)) - 1) * 100

    end_value = float(nprof.iloc[0])
    start_value = float(nprof.iloc[-1])
    num_periods = len(nprof)

    if end_value < 0:
        end_value = 0.001
    else:
        end_value = end_value

    if start_value <= 0:
        start_value = 0.001
    else:
        start_value = start_value

    if start_value == end_value:
        nprof_grw = 0
    else:
        nprof_grw = ((end_value / start_value)**(1 / (num_periods)) - 1) * 100

    end_value = float(avg_recei_latest.iloc[0])
    start_value = float(avg_recei_latest.iloc[-1])
    num_periods = len(avg_recei_latest)

    if end_value < 0:
        end_value = 0.001
    else:
        end_value = end_value

    if start_value <= 0:
        start_value = 0.001
    else:
        start_value = start_value

    if start_value == end_value:
        avg_recei_grw = 0
    else:
        avg_recei_grw = ((end_value / start_value)**(1 /
                                                     (num_periods)) - 1) * 100

    latest_roe = float(roe.iloc[-1])

    end_value = float(cfo.iloc[0])
    start_value = float(cfo.iloc[-1])
    num_periods = len(cfo)

    if end_value < 0:
        end_value = 0.001
    else:
        end_value = end_value

    if start_value <= 0:
        start_value = 0.001
    else:
        start_value = start_value
    if start_value == end_value:
        cfo_grw = 0
    else:
        cfo_grw = ((end_value / start_value)**(1 / (num_periods)) - 1) * 100

    end_value = float(total_debt.iloc[0])
    start_value = float(total_debt.iloc[-1])
    num_periods = len(total_debt)

    if start_value == 0:
        start_value = 0.01
    else:
        start_value = start_value

    if start_value == end_value:
        total_debt_grw = 0
    else:
        total_debt_grw = ((end_value / start_value)**(1 /
                                                      (num_periods)) - 1) * 100

    total_debt_mean = total_debt.mean()
    total_rev_mean = revenue.mean()
    total_rev_mean_20_pct = total_rev_mean * (20 / 100)
    """ Values updates"""

    rev_simple = rev_grw - (rev_grw * (5 / 100))

    if rev_simple > 8:
        rev_score = 1
    else:
        rev_score = 0

    if pat_grw > (rev_simple - (rev_simple * (10 / 100))):
        pat_score = 1
    else:
        pat_score = 0

    if nprof_grw > (rev_simple - (rev_simple * (10 / 100))):
        nprof_score = 1
    else:
        nprof_score = 0

    if avg_recei < avg_rev_20_pct or avg_recei_grw <= (rev_simple -
                                                       (rev_simple *
                                                        (9 / 100))):
        avg_rec_score = 1
    else:
        avg_rec_score = 0

    if latest_roe > (roe_mean - (roe_mean * (10 / 100))):
        roe_score = 1
    else:
        roe_score = 0

    if avg_prof_cap_emp > 15:
        avg_prof_cap_emp_score = 1
    else:
        avg_prof_cap_emp_score = 0

    if cfo_grw > (rev_simple - (rev_simple * (10 / 100))):
        cfo_score = 1
    else:
        cfo_score = 0

    if cfo_grw > 10:
        cfo_gt_10_score = 1
    else:
        cfo_gt_10_score = 0

    if CCFO_to_CNPAT > 0.8:
        ccflo_to_cnpat_score = 1
    else:
        ccflo_to_cnpat_score = 0

    if total_debt_mean < total_rev_mean_20_pct or total_debt_grw <= (
            rev_simple - (rev_simple * (10 / 100))) or total_debt_grw < 0:
        debt_score = 1
    else:
        debt_score = 0

    final_score = (rev_score + pat_score + nprof_score + avg_rec_score +
                   roe_score + avg_prof_cap_emp_score + cfo_score +
                   cfo_gt_10_score + ccflo_to_cnpat_score + debt_score)

    print("stock_nm", "opm", "avg_price_to_consider", "cmp", "rev_grw",
          "pat_grw", "nprof_grw", "avg_recei", "latest_roe",
          "avg_prof_cap_emp", "cfo_grw", "CCFO_to_CNPAT", "total_debt_grw",
          "final_score")
    if final_score >= 8:
        print(stock_nm, opm, round(avg_price_to_consider, 2), cmp,
              round(rev_grw, 2), round(pat_grw, 2), round(nprof_grw, 2),
              round(avg_recei, 2), round(latest_roe, 2),
              round(avg_prof_cap_emp, 2), round(cfo_grw, 2),
              round(CCFO_to_CNPAT, 2), round(total_debt_grw, 2), final_score)
 def update_cashflow(self, symbol):
     cashflow = si.get_cash_flow(symbol).to_dict(orient="dict")
     self.update(symbol, cashflow, 'Stocks', 'Cashflow')
Ejemplo n.º 10
0
 def __init__(self, ticker):
     self.income_statement = si.get_income_statement(ticker)
     self.balance_sheet = si.get_balance_sheet(ticker)
     self.cash_flow_statement = si.get_cash_flow(ticker)
     self.inputs = self.get_inputs_df()
Ejemplo n.º 11
0
async def cash_flow(ctx, *, ticker):
    await ctx.send(si.get_cash_flow(ticker))
Ejemplo n.º 12
0
     gear.append("n.a.")
     print(i + " gearing is N/A.")
     count += 1
 try:
     per.append(qt.per(i))
     print(i + " PER is successfully appended")
     count += 1
 except:
     per.append("n.a.")
     print(i + " PER is N/A.")
     count += 1
 try:
     ocash.append(
         int(
             get_cash_flow(i).loc[
                 get_cash_flow(i)['Breakdown'] ==
                 "Net cash provided by operating activites"].iloc[:,
                                                                  1]))
     print(i + " operating cash flow is successfully appended")
     count += 1
 except:
     ocash.append("n.a.")
     print(i + " operating cash flow is N/A.")
     count += 1
 try:
     icash.append(
         int(
             get_cash_flow(i).loc[
                 get_cash_flow(i)['Breakdown'] ==
                 "Net cash used for investing activites"].iloc[:, 1]))
     print(i + " investing cash flow is successfully appended")
     count += 1
Ejemplo n.º 13
0
 def get_cash_flow(self):
     if self.storage == None:
         return self.format1D(stock_info.get_cash_flow(self.stock))
     else:
         self.storage['cash_flow'] = self.format1D(stock_info.get_cash_flow(self.stock))
    if symbol == 'Q':
        break

    if Company_name(symbol) == None:
        print('Company not found')
        print('')
        col += 1
        continue

    print('Company: ' + Company_name(symbol))

    print('Collecting Data: ', end = '')
    start_time = time.time()
    Balance_Sheet = si.get_balance_sheet(symbol)
    Income_Statement = si.get_income_statement(symbol)
    Cash_Flow = si.get_cash_flow(symbol)
    Quote = si.get_quote_table(symbol)
    Valuation_Stats = si.get_stats_valuation(symbol)
    print(round(time.time() - start_time,2), 'seconds')
    
    ##column 2
    print('Insert Data: ', end = '')
    start_time = time.time()
    total_assets = int(Balance_Sheet.loc[list(Balance_Sheet.iloc[:,0]).index('Total Assets')][1])
    total_debt = int(Balance_Sheet.loc[list(Balance_Sheet.iloc[:,0]).index('Total Debt')][1])
    
    try: ebitda_anual = int(Income_Statement.loc[list(Income_Statement.iloc[:,0]).index('Normalized EBITDA')][2])
    except: ebitda_anual = 'Fail'

    if ebitda_anual == 'Fail': Debt_Ebitda = 'Fail'
    else: Debt_Ebitda = total_debt / ebitda_anual
Ejemplo n.º 15
0
from yahoo_fin import stock_info as si
import pprint as pp

symbol = 'HDFCBANK.NS'

print(si.get_live_price(symbol))

print(si.get_data(symbol))

pp.pprint(si.get_quote_table(symbol))

pp.pprint(si.get_stats(symbol))

pp.pprint(si.get_holders(symbol))

pp.pprint(si.get_analysts_info(symbol))

pp.pprint(si.get_income_statement(symbol))

pp.pprint(si.get_balance_sheet(symbol))

pp.pprint(si.get_cash_flow(symbol))
        pp.pprint(si.get_stats(input_arguments.symbol))

    elif input_arguments.information == 'holders':
        pp.pprint(si.get_holders(input_arguments.symbol))
        
    elif input_arguments.information == 'analysis':
        pp.pprint(si.get_analysts_info(input_arguments.symbol))

    elif input_arguments.information == 'income':
        pp.pprint(si.get_income_statement(input_arguments.symbol))

    elif input_arguments.information == 'balance':
        pp.pprint(si.get_balance_sheet(input_arguments.symbol))
        
    elif input_arguments.information == 'cashflow':
        pp.pprint(si.get_cash_flow(input_arguments.symbol))
        
    sys.exit()
    
    
    
previous_price = 0
profit = 0
current_price = 0

while True:  
    
    while (True):
        try:
            current_price  = around(si.get_live_price(input_arguments.symbol),2) 
            break
Ejemplo n.º 17
0
def financial_stmt_checks(stock_nm):
    stock_nm="VSTIND.NS"
    income_statement = si.get_income_statement(stock_nm)
    balance_sheet = si.get_balance_sheet(stock_nm)
    cash_flow_statement = si.get_cash_flow(stock_nm)
    
    
    
    income_statement.fillna(0, inplace=True)
    income_statement=income_statement.div(10000000).astype(int)
    
    balance_sheet.fillna(0, inplace=True)
    balance_sheet=balance_sheet.div(10000000).astype(int)
    
    cash_flow_statement.fillna(0, inplace=True)
    cash_flow_statement=cash_flow_statement.div(10000000).astype(int)
    
    income_statement_df=income_statement.transpose()
    balance_sheet_df=balance_sheet.transpose()
    cash_flow_statement_df=cash_flow_statement.transpose()
    
    revenue=income_statement_df['totalRevenue']
    pat=income_statement_df['incomeBeforeTax']
    nprof=income_statement_df['netIncomeFromContinuingOps']
    net_prof=income_statement_df['netIncomeApplicableToCommonShares']
    #op_exp=income_statement_df['totalOperatingExpenses']
    
    #########Aggregation##########
    tot_revenue=income_statement_df['totalRevenue'].sum()
    tot_exp=income_statement_df['totalOperatingExpenses'].sum()
    tot_np=income_statement_df['netIncomeFromContinuingOps'].sum()
    avg_revenue=income_statement_df['totalRevenue'].mean()
    
    cfo=cash_flow_statement_df['totalCashFromOperatingActivities']
    CCFO=cfo.sum()
    CNPAT=income_statement_df['netIncomeApplicableToCommonShares'].sum()
    CCFO_to_CNPAT=round(CCFO/CNPAT,2)
    
    
    ebit=income_statement_df['ebit'].sort_index()
    net_prof_sort=income_statement_df['netIncomeApplicableToCommonShares'].sort_index()
    
    ebit_to_net_prof=(ebit/net_prof_sort)
    avg_ebit_to_net_prof=ebit_to_net_prof.mean()
    
    #tot_int=income_statement_df['interestExpense'].sum()
    
    #############################
    
    if "netReceivables" in balance_sheet_df:
        avg_recei=balance_sheet_df['netReceivables'].mean()
        avg_recei_latest=balance_sheet_df['netReceivables']
    else:
        #print ("notfound")
        avg_recei_df = revenue
        avg_recei_df = avg_recei_df.replace(avg_recei_df, 0)
        avg_recei=avg_recei_df.mean()
        avg_recei_latest=avg_recei_df
        
    revenue.sort_index()
    pat.sort_index()
    nprof.sort_index()
    net_prof.sort_index()
    
    def int_to_net_prof_lt():
        tot_int=income_statement_df['interestExpense'].sum()
        if tot_int ==0:
            tot_int=0.001
            
        if (tot_int/CNPAT) <= 0.5:
            print ("All checks passed", stock_nm)
    
    def ebit_to_net_prof_check():
        latest_ebit_to_net_prof = float(ebit_to_net_prof.iloc[-1])
        if latest_ebit_to_net_prof >= (avg_ebit_to_net_prof - (avg_ebit_to_net_prof*10/100)):
            #print ("All checks passed")
            int_to_net_prof_lt()
            
        
        
    def Ccfo_to_Cpat():
        if CCFO_to_CNPAT > 0.8:
            #print ("All checks passed")
            ebit_to_net_prof_check()
        
    def receivables_sales():
        if avg_recei <= ((avg_revenue*30)/100):
            #print ("All checks passed")
            Ccfo_to_Cpat()
        
        
    def net_prof_sales_gt_8pct():
        if tot_np >= ((tot_revenue*8)/100):
            receivables_sales()
        
    def expense_less_sales():
        if tot_revenue>=tot_exp:
            net_prof_sales_gt_8pct()

    
    def net_prof_growth():
        print ("inside net_prof_growth" )
        end_value = float(net_prof.iloc[0])
        start_value = float(net_prof.iloc[-1])
        num_periods = len(net_prof)

        if end_value < 0:
            end_value=0.001
        else:
            end_value=end_value

        if start_value <= 0:
            start_value=0.001
        else:
            start_value=start_value

        if start_value == end_value:
            net_prof_grw=0
        else:
            net_prof_grw=((end_value / start_value) ** (1 / (num_periods )) - 1)*100
            print ("Net profit growth", net_prof_grw)
        if int(net_prof_grw) > 7:
            expense_less_sales()
            #net_prof_growth()
    def income_stmt():
        print ("income",avg_recei)
        net_prof_growth()
        balance_sheet()
    def balance_sheet():
        print ("balance",avg_recei)
        cashflow_stmt()
    def cashflow_stmt():
        print ("cashflow",avg_recei)
    def dummy():
        net_prof_growth()
        
    dummy()
Ejemplo n.º 18
0
def getCashFlow(ticker):
    return si.get_cash_flow(ticker)
        TE1 = float(company_income_data.iloc[company_income_data[
            company_income_data['Breakdown'] == 'Tax Provision'].index[0], 2])
        TE2 = float(company_income_data.iloc[company_income_data[
            company_income_data['Breakdown'] == 'Tax Provision'].index[0], 3])
        TE3 = float(company_income_data.iloc[company_income_data[
            company_income_data['Breakdown'] == 'Tax Provision'].index[0], 4])
        TE4 = float(company_income_data.iloc[company_income_data[
            company_income_data['Breakdown'] == 'Tax Provision'].index[0], 5])

    ##################################################
    ##################################################
    ##################################################

    #this is the information from the statement of cash flows
    Loaded = 0
    StatementOfCashFlows = get_cash_flow(companies)

    Loaded += sum(StatementOfCashFlows['Breakdown'].str.count(
        'Net cash provided by operating activites'))
    while Loaded == 0.0:
        StatementOfCashFlows = get_cash_flow(companies)
        Loaded += sum(StatementOfCashFlows['Breakdown'].str.count(
            'Net cash provided by operating activites'))

    WC1 = float(StatementOfCashFlows.iloc[StatementOfCashFlows[
        StatementOfCashFlows['Breakdown'] ==
        'Net cash provided by operating activites'].index[0], 2])
    WC2 = float(StatementOfCashFlows.iloc[StatementOfCashFlows[
        StatementOfCashFlows['Breakdown'] ==
        'Net cash provided by operating activites'].index[0], 3])
    WC3 = float(StatementOfCashFlows.iloc[StatementOfCashFlows[
Ejemplo n.º 20
0
def get_yahoo_fin(prod, outdir):
    """
    Query exhaustive information of a stock on Yahoo finance and output to a worksheet
    Args:
        prod    Product object, containing basic info about the stock such as symbol, name, currency etc.
        start_date  start date string such as '1/1/2018' or '2018-1-1T00:00:00'
        end_date    end date string such as '30/12/2018' ...
        outdir  output dir to save the plot
    Return:
        no return
    """
    ticker = prod._symbol
    out_path = os.path.join(outdir, f'{prod._name}.xlsx')
    print(f'Retrieving data for {prod._name} ...')
    writer = pd.ExcelWriter(out_path,engine='xlsxwriter')  # Creating Excel Writer Object from Pandas  

    # summary, quote table, stats
    print('\tQuerying summary/quote table/stats ...')
    row_count = 0
    summ = {'name': prod._name, 'id': prod._id, 'symbol': prod._symbol, 
            'close price': prod._closeprice,
            'close date': prod._closedate, 
            'current price': si.get_live_price(ticker),
            'vwdId': prod._vwdId}
    df_summ = dict2dataframe(summ, 'info')
    df_summ.rename_axis('Summary', axis='index', inplace=True)
    df_summ.to_excel(writer, sheet_name='Summary', startrow=row_count, startcol=0)
    row_count = row_count + len(df_summ) + 2

    df_quote = dict2dataframe(si.get_quote_table(ticker))
    df_quote.rename_axis('Quote table', axis='index', inplace=True)
    df_quote.to_excel(writer, sheet_name='Summary', startrow=row_count, startcol=0)
    row_count = row_count + len(df_quote) + 2

    df_stats = si.get_stats(ticker)
    df_stats.rename_axis('Stats', axis='index', inplace=True)
    df_stats.to_excel(writer, sheet_name='Summary', startrow=row_count, startcol=0)
    row_count = row_count + len(df_stats) + 2

    # analyst
    print('\tQuerying analyst ...')
    ana = si.get_analysts_info(ticker)  # this return a dict of pandas dataframes
    row_count = 0
    for key, df in ana.items():
        df.name = key
        df.to_excel(writer, sheet_name='Analyst Info', startrow=row_count, startcol=0)
        row_count = row_count + len(df) + 2

    # balance sheet
    print('\tQuerying balance ...')
    df_bal = si.get_balance_sheet(ticker)
    df_bal.to_excel(writer,sheet_name='Balance', startrow=0 , startcol=0)

    # cash flow
    print('\tQuerying cash flow ...')
    df_cash = si.get_cash_flow(ticker)
    df_cash.to_excel(writer,sheet_name='Cash flow', startrow=0 , startcol=0)

    # data
    print('\tQuerying historic data ...')
    df_data = si.get_data(ticker)
    df_data.sort_index(ascending=False, inplace=True)
    df_data.to_excel(writer,sheet_name='Data', startrow=0 , startcol=0)

    # financial
    print('\tQuerying financial ...')
    fin = si.get_financials(ticker)  # this return a dict of dataframes
    row_count = 0
    for key, df in fin.items():
        df.rename_axis(key, axis='index', inplace=True)
        df.to_excel(writer, sheet_name='Financial', startrow=row_count, startcol=0)
        row_count = row_count + len(df) + 2

    # save
    writer.save()
    print(f'Data saved to {out_path}')
Ejemplo n.º 21
0
def my_stock_price(stock_nm):

    #stock_nm="DMART.NS"
    
    income_statement = si.get_income_statement(stock_nm)
    balance_sheet = si.get_balance_sheet(stock_nm)
    cash_flow_statement = si.get_cash_flow(stock_nm)
    
    income_statement.fillna(0, inplace=True)
    income_statement=income_statement.div(10000000).astype(int)
    
    balance_sheet.fillna(0, inplace=True)
    balance_sheet=balance_sheet.div(10000000).astype(int)
    
    cash_flow_statement.fillna(0, inplace=True)
    cash_flow_statement=cash_flow_statement.div(10000000).astype(int)
    
    income_statement_df=income_statement.transpose()
    balance_sheet_df=balance_sheet.transpose()
    cash_flow_statement_df=cash_flow_statement.transpose()
    
    revenue=income_statement_df['totalRevenue']
    pat=income_statement_df['incomeBeforeTax']
    nprof=income_statement_df['netIncomeFromContinuingOps']
    
    if "netReceivables" in balance_sheet_df:
        avg_recei=balance_sheet_df['netReceivables'].mean()
        avg_recei_latest=balance_sheet_df['netReceivables']
    else:
        avg_recei_df = revenue
        avg_recei_df = avg_recei_df.replace(avg_recei_df, 0)
        avg_recei=avg_recei_df.mean()
        avg_recei_latest=avg_recei_df
    
    #avg_recei=balance_sheet_df['netReceivables'].mean()
    avg_rev_20_pct=(income_statement_df['totalRevenue'].mean()*(20/100))
    #avg_recei_latest=balance_sheet_df['netReceivables']
    
    tot_share_hold=balance_sheet_df['totalStockholderEquity'].sort_index()
    net_income=income_statement_df['netIncome'].sort_index()
    
    roe=(net_income/tot_share_hold)*100
    roe_mean=roe.mean()
    
    
    np_share_hold=income_statement_df['netIncomeApplicableToCommonShares'].sort_index()
    prof_cap_emp=(np_share_hold/tot_share_hold)*100
    avg_prof_cap_emp=prof_cap_emp.mean()
    
    cfo=cash_flow_statement_df['totalCashFromOperatingActivities']
    CCFO=cfo.sum()
    CNPAT=income_statement_df['netIncomeApplicableToCommonShares'].sum()
    CCFO_to_CNPAT=round(CCFO/CNPAT,2)
    
    if "shortLongTermDebt" in balance_sheet_df:
        short_debt=balance_sheet_df['shortLongTermDebt']
    else:
        #print ("notfound")
        short_debt = revenue
        short_debt = short_debt.replace(short_debt, 0)
    
        
    if "longTermDebt" in balance_sheet_df:
        long_debt=balance_sheet_df['longTermDebt']
    else:
        long_debt = revenue
        long_debt = long_debt.replace(long_debt, 0)
    
    total_debt=short_debt+long_debt
    # sorting.......................
    
    revenue.sort_index()
    pat.sort_index()
    nprof.sort_index()
    avg_recei_latest.sort_index()
    cfo.sort_index()
    total_debt.sort_index()
    
    
    """ Values updates"""
    
    end_value = float(revenue.iloc[0])
    start_value = float(revenue.iloc[-1])
    num_periods = len(revenue)
    
    if end_value < 0:
        end_value=0.001
    else:
        end_value=end_value
        
    if start_value <= 0:
        start_value=0.001
    else:
        start_value=start_value
    
    if start_value == end_value:
        rev_grw=0
    else:
        rev_grw=((end_value / start_value) ** (1 / (num_periods )) - 1)*100
    
 
    end_value = float(pat.iloc[0])
    start_value = float(pat.iloc[-1])
    num_periods = len(pat)
    
    if end_value < 0:
        end_value=0.001
    else:
        end_value=end_value
        
    if start_value <= 0:
        start_value=0.001
    else:
        start_value=start_value
        
    if start_value == end_value:
        pat_grw=0
    else:
        pat_grw=((end_value / start_value) ** (1 / (num_periods )) - 1)*100
    
    
    end_value = float(nprof.iloc[0])
    start_value = float(nprof.iloc[-1])
    num_periods = len(nprof)
    
    if end_value < 0:
        end_value=0.001
    else:
        end_value=end_value
        
    if start_value <= 0:
        start_value=0.001
    else:
        start_value=start_value
    if start_value == end_value:
        nprof_grw=0
    else:
        nprof_grw=((end_value / start_value) ** (1 / (num_periods )) - 1)*100
    
    
    
    end_value = float(nprof.iloc[0])
    start_value = float(nprof.iloc[-1])
    num_periods = len(nprof)
    
    if end_value < 0:
        end_value=0.001
    else:
        end_value=end_value
        
    if start_value <= 0:
        start_value=0.001
    else:
        start_value=start_value
    
    if start_value == end_value:
        nprof_grw=0
    else:
        nprof_grw=((end_value / start_value) ** (1 / (num_periods )) - 1)*100
    
    
    end_value = float(avg_recei_latest.iloc[0])
    start_value = float(avg_recei_latest.iloc[-1])
    num_periods = len(avg_recei_latest)
    
    if end_value < 0:
        end_value=0.001
    else:
        end_value=end_value
        
    if start_value <= 0:
        start_value=0.001
    else:
        start_value=start_value
    
    if start_value == end_value:
        avg_recei_grw=0
    else:
        avg_recei_grw=((end_value / start_value) ** (1 / (num_periods )) - 1)*100
    
    latest_roe = float(roe.iloc[-1])
    
    end_value = float(cfo.iloc[0])
    start_value = float(cfo.iloc[-1])
    num_periods = len(cfo)
    
    if end_value < 0:
        end_value=0.001
    else:
        end_value=end_value
        
    if start_value <= 0:
        start_value=0.001
    else:
        start_value=start_value
    if start_value == end_value:
        cfo_grw=0
    else:
        cfo_grw=((end_value / start_value) ** (1 / (num_periods )) - 1)*100
    
    
    
    
    
    end_value = float(total_debt.iloc[0])
    start_value = float(total_debt.iloc[-1])
    num_periods = len(total_debt)
    
    if start_value == 0:
        start_value=0.01
    else:
        start_value=start_value
        
    if start_value == end_value:
        total_debt_grw=0
    else:
        total_debt_grw=((end_value / start_value) ** (1 / (num_periods )) - 1)*100
    
    
    
    total_debt_mean=total_debt.mean()
    total_rev_mean=revenue.mean()
    total_rev_mean_20_pct=total_rev_mean*(20/100)
    
    """ Values updates"""
    
    rev_simple=rev_grw-(rev_grw*(5/100))
    
    if rev_simple > 8:
        rev_score=1
    else:
        rev_score=0
        
    if pat_grw > (rev_simple - (rev_simple*(10/100))):
        pat_score=1
    else:
        pat_score=0
        
    if nprof_grw > (rev_simple - (rev_simple*(10/100))):
        nprof_score=1
    else:
        nprof_score=0
        
    if avg_recei < avg_rev_20_pct or avg_recei_grw <=(rev_simple - (rev_simple*(9/100))):
        avg_rec_score=1
    else:
        avg_rec_score=0
        
    if latest_roe > (roe_mean - (roe_mean*(10/100))):
        roe_score=1
    else:
        roe_score=0
        
    if avg_prof_cap_emp > 15 :
        avg_prof_cap_emp_score=1
    else:
        avg_prof_cap_emp_score=0
        
    if cfo_grw > (rev_simple - (rev_simple*(10/100))):
        cfo_score=1
    else:
        cfo_score=0
        
    if cfo_grw > 10:
        cfo_gt_10_score=1
    else:
        cfo_gt_10_score=0
        
    if CCFO_to_CNPAT > 0.8:
        ccflo_to_cnpat_score=1
    else:
        ccflo_to_cnpat_score=0
        
    if total_debt_mean < total_rev_mean_20_pct or total_debt_grw <=(rev_simple - (rev_simple*(10/100))) or total_debt_grw <0 :
        debt_score=1
    else:
        debt_score=0
   
    stock_stats = si.get_stats(stock_nm)
    opm=float(stock_stats[stock_stats.Attribute=='Profit Margin'].Value.item().replace('%', ''))
    book_per_share=float(stock_stats[stock_stats.Attribute=='Book Value Per Share (mrq)'].Value.item())
    promoter_hold=float(stock_stats[stock_stats.Attribute=='% Held by Insiders 1'].Value.item().replace('%', ''))
    roe=float(stock_stats[stock_stats.Attribute=='Return on Equity (ttm)'].Value.item().replace('%', ''))
    eps=float(stock_stats[stock_stats.Attribute=='Diluted EPS (ttm)'].Value.item())   
    
    if opm >=0 and book_per_share>=0 and promoter_hold>=45 and roe>=10 and eps>=0 :
        #print(stock_nm,opm,book_per_share,promoter_hold,roe,eps)
        base_validation=1

    total_score=(rev_score+pat_score+nprof_score+avg_rec_score+roe_score+avg_prof_cap_emp_score+cfo_score+cfo_gt_10_score+ccflo_to_cnpat_score+debt_score)
    
    if total_score >=8 and base_validation>0 :
        print (stock_nm, "Good For Investment" , total_score)
        selected_list.
        
    else:
        print (stock_nm, "Please skip", total_score)
Ejemplo n.º 22
0
    all_historical[ticker] = si.get_data(ticker)
    print(ticker)

dow_historical = {}
for ticker in dow_list:
    dow_historical = si.get_data(ticker, start_date='1990-01-01', end_date='2020-01-01', interval='1d')
    print(ticker)

print(si.get_quote_table('AAPL'))
print(si.get_stats('AAPL')[si.get_stats('AAPL')['Attribute'] == 'EBITDA']['Value'].iloc[0])
"""
all_data = {}
for ticker in {'AMZN'}:
    balance_sheet = si.get_balance_sheet(ticker, False)
    income_statement = si.get_income_statement(ticker, False)
    cash_flow = si.get_cash_flow(ticker, False)
    stats = si.get_stats(ticker)
    analysts_info = si.get_analysts_info(ticker)
    earnings = si.get_earnings(ticker)
    oneyear_return = (si.get_data(ticker, start_date=datetime.today()-timedelta(days=365), end_date=datetime.today())['close'].iloc[-1] - si.get_data(ticker, start_date=datetime.today()-timedelta(days=365), end_date=datetime.today())['close'][0])/si.get_data(ticker, start_date=datetime.today()-timedelta(days=365), end_date=datetime.today())['close'][0]

    stats.columns = ['Labels', 'Values']

    stats_labels = []
    stats_values = []
    for i in range(stats.shape[0]):
        stats_labels.append(stats.iat[i, 0])
        stats_values.append(stats.iat[i, 1])
    stats_df = pd.DataFrame({'Values': stats_values}, index=stats_labels)

    print(analysts_info['Earnings Estimate'])
Ejemplo n.º 23
0

stats = [
    "Net income available to common shareholders", "Total assets",
    "Net cash provided by operating activities", "Long-term debt",
    "Other long-term liabilities", "Total current assets",
    "Total current liabilities", "Common stock", "Total revenue",
    "Gross profit"
]

for ticker in tickers:
    temp_dict = {}
    temp_dict2 = {}
    temp_dict3 = {}
    bal = si.get_balance_sheet(ticker)
    cf = si.get_cash_flow(ticker)
    income = si.get_income_statement(ticker)
    print("getting financial data for: ", ticker)
    try:
        temp_dict["Net income available to common shareholders"] = income.loc[
            "netIncomeApplicableToCommonShares", :][0]
        temp_dict2["Net income available to common shareholders"] = income.loc[
            "netIncomeApplicableToCommonShares", :][1]
        temp_dict3["Net income available to common shareholders"] = income.loc[
            "netIncomeApplicableToCommonShares", :][2]
    except:
        temp_dict["Net income available to common shareholders"] = np.nan
        temp_dict2["Net income available to common shareholders"] = np.nan
        temp_dict3["Net income available to common shareholders"] = np.nan

    try:
Ejemplo n.º 24
0
    Ticker = input("Insert Ticker:")
    quote = yf.get_quote_table(Ticker)
    # indexing market cap
    MarketCap = quote["Market Cap"]
    # print market cap
    beta = quote["Beta (5Y Monthly)"]
    print('Market Cap:', "{:,}".format(conv_mrktcap(MarketCap)), '$')
    print('Beta:', beta)
    stats = yf.get_stats_valuation(Ticker)
    Data = yf.get_data(Ticker)
    Balance_Sheet = yf.get_balance_sheet(Ticker)
    financials = yf.get_financials(Ticker)
    analyst = yf.get_analysts_info(Ticker)
    # import company's valuations as stats
    income = yf.get_income_statement(Ticker)
    Cash = yf.get_cash_flow(Ticker)

    # import comapny's income statement as income
    ebit = income.loc["ebit"]
    # indexing ebit in icnome statement
    ebit2020 = int(ebit["2020"])
    # indexing latest ebit in income statement
    print('Latest Calender Ebit:', "{:,}".format(ebit2020), "$")

    interestExpense = income.loc['interestExpense']
    # indexing interest expense in imcome statement
    interestExpense2020 = int(-interestExpense["2020"])
    # indexing latest interest expemse in income statement
    print('Latest Calendar Interest Expense:',
          "{:,}".format(interestExpense2020), '$')
Ejemplo n.º 25
0
 def down_cf(self, ticker):
     cashf = si.get_cash_flow(ticker)
     filename = ticker + 'CashFlow.txt'
     f = open(filename, "x")
     print(cashf, file=f)
Ejemplo n.º 26
0
 def getCashFlow(self, symbol):
     cashFlow = si.get_cash_flow(symbol)
     return {'cashFlow': self.yahooFinanceDataModification.formatSheetData(cashFlow)}
Ejemplo n.º 27
0
def get_cash_flow(tickers, yearly=True):
    dict_data = {
        ticker: si.get_cash_flow(ticker, yearly)
        for ticker in tickers
    }
    return dict_data
Ejemplo n.º 28
0
nprof_score = 0
avg_rec_score = 0
roe_score = 0
avg_prof_cap_emp_score = 0
cfo_score = 0
cfo_gt_10_score = 0
ccflo_to_cnpat_score = 0
debt_score = 0

#def my_stock_price(stock_nm):

stock_nm = "TCS.NS"

income_statement = si.get_income_statement(stock_nm)
balance_sheet = si.get_balance_sheet(stock_nm)
cash_flow_statement = si.get_cash_flow(stock_nm)

income_statement.fillna(0, inplace=True)
income_statement = income_statement.div(10000000).astype(int)

balance_sheet.fillna(0, inplace=True)
balance_sheet = balance_sheet.div(10000000).astype(int)

cash_flow_statement.fillna(0, inplace=True)
cash_flow_statement = cash_flow_statement.div(10000000).astype(int)

income_statement_df = income_statement.transpose()
balance_sheet_df = balance_sheet.transpose()
cash_flow_statement_df = cash_flow_statement.transpose()

revenue = income_statement_df['totalRevenue']
Ejemplo n.º 29
0
def get_last_cash_flow(stock):
    return si.get_cash_flow(stock).iloc[:, 0]
from yahoo_fin import stock_info as si
import pandas as pd
import xlsxwriter

stock = 'NVDA'

directory = "/users/satish/Desktop/" + stock + "_fundamentals.xlsx"
writer = pd.ExcelWriter(directory, engine='xlsxwriter')

balance_sheet = si.get_balance_sheet(stock, True)
income_statement = si.get_income_statement(stock, True)
cash_flow = si.get_cash_flow(stock, True)
financials = si.get_financials(stock, yearly=True)

balance_sheet.to_excel(writer, sheet_name='Balance Sheet')
income_statement.to_excel(writer, sheet_name='Income Statement')
cash_flow.to_excel(writer, sheet_name='Cash Flow')
#financials.to_excel(writer, sheet_name = 'Financials')

writer.save()