Пример #1
0
def bs_chart_input(search_btn,search):
    if search_btn:
        balance_sheet = si.get_balance_sheet(search)
        bs = balance_sheet.T
    else:
        balance_sheet = si.get_balance_sheet("aapl")
        bs = balance_sheet.T

    bs["date"] = bs.index
    date= bs["date"].dt.year
    ta = (bs["totalAssets"]/1000000000).astype(float).round(2)
    tl = (bs["totalLiab"]/1000000000).astype(float).round(2)

    # color=np.array(['rgb(255,255,255)']*ta.shape[0])
    # color[ta<0]='red'
    # color[ta>=0]='green'

    fig3 = go.Figure(data=[
        go.Bar(name='Total Asset', x=date, y=bs["totalAssets"],marker_color="green", text = ta,textfont_size=8,  textposition='outside',),
        go.Bar(name='Total Liability', x=date, y=bs["totalLiab"],marker_color="crimson",  text = tl,textfont_size=8,  textposition='outside',),
    ])
    # Change the bar mode
    fig3.update_layout(barmode='group',width = 444,title_text='Asset vs Liability',title_x=0.5,margin=dict(t=70,b=20,l=55,r=40),paper_bgcolor='rgba(0,0,0,0)',plot_bgcolor='rgba(0,0,0,0)')
    fig3.update_layout(legend=dict(orientation="h",yanchor="bottom",y=1,xanchor="right",x=0.75,font=dict(size=9,),))
    return fig3
Пример #2
0
 def gearing(self, tck):
     equity = int(
         get_balance_sheet(tck).loc[get_balance_sheet(
             tck)['Breakdown'] == "Total stockholders' equity"].iloc[:, 1])
     debt = int(
         get_balance_sheet(tck).loc[get_balance_sheet(tck)['Breakdown'] ==
                                    "Total Liabilities"].iloc[:, 1])
     gear = debt / equity
     return gear
Пример #3
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
Пример #4
0
def balance(request):
    ticker = json.loads(request.body)['ticker']

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

        return HttpResponse(output)
Пример #5
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.")
Пример #6
0
def format_object(ticker):
    # The following function will pass in our ticker
    # and format the dataframe files from Panda and from our API
    try:
        # the following will format the ticker enter above into a more readable dataframe format form our pandas import
        bs_stock_1 = yf.get_balance_sheet(ticker)
        # format original columns into these easy to read columns
        bs_stock_1.columns = ["2020", "2019", "2018", "2017"]
        bs_stock_1.index.name = "Account"

        # formatting for the income statement portion
        is_stock_1 = yf.get_income_statement(ticker)
        is_stock_1.columns = ["2020", "2019", "2018", "2017"]
        is_stock_1.index.name = "Account"

        # Calling the function to format shares from a dictionary to get a float
        # We also want the daily stock and market cap
        shares_outstanding = sy.shares(ticker)
        daily_share_price = yf.get_live_price(ticker)
        market_cap = shares_outstanding * daily_share_price

        # this calls the year function
        year = sy.year_call()
        stock_attributes = {
            "Income Statement": is_stock_1,
            "Balance Sheet": bs_stock_1,
            "total Shares": shares_outstanding,
            "Daily Shares": daily_share_price,
            "market_cap": market_cap,
            "year": year,
            "ticker": ticker,
            "daily_share_price": daily_share_price
        }
        control(stock_attributes)

    except:
        # if they did not enter a ticker
        # this will be a pseudo recursive approach and take us back to the main page
        print(
            "you did not enter a ticker with a correct symbol,you will be taken back to the ticker login section"
        )
        format_ticker()
Пример #7
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))
Пример #8
0
    def balance_sheet(self):
        bundle = [
            self.stock_one, self.stock_two, self.stock_three, self.stock_four
        ]
        for symbol in bundle:
            try:
                sheet = si.get_balance_sheet(stock_class)
                stats = si.get_stats(symbol)
                sheet.cash
                sheet.longTermInvestments
                #balancesheet
                ebitda = stats[stats.Attribute == 'EBITDA']
                ebitda_value = ebitda['Value'].values[0]
                company = stock.upper()
            except KeyError as err:
                sector = 'N/A'
                symbol = company.info['symbol']
                print(f'{symbol} sector not found {sector}')
            except TypeError as err:
                print(f'{symbol} showing {err}')
                PS_TTM = 'Nan'
                print('setting Nan for PS_TTM')
                pass
            except IndexError as err:
                print(f'{symbol} showing {err}')
            except Exception as e:
                print(e)
            tweet = f"DAILY STOCK\nStock: ${company}\nMarket Cap: ${market_cap}\n52 Week Range: ${fiftytwo_wk}\nClose: ${previous_close}\n1y Target Est: ${one_year_target}\nEPS (TTM): ${eps_ttm}\nPE Ratio (TTM) {pe_ratio}"

            # response = tweet_api.update_status(status=tweet)
            # original_tweet = original_tweet.id
            # tweet_id = response.id
            ### to respond to a tweet ####
            # status=textforreply,
            #         in_reply_to_status_id=original_twee.id
            #          auto_populate_reply_metadata=True#

            print(f'tweet sent!\n{tweet}')
            print(f'tweet Char Count: {len(tweet)}')
        return tweet
Пример #9
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)
Пример #10
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)
Пример #11
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}')
 def update_yearly_balance_sheet(self, symbol):
     
     yearly_balance_sheet = si.get_balance_sheet(symbol).to_dict(orient="dict")
     self.update(symbol, yearly_balance_sheet, 'Stocks', 'Yearly_Balance_Sheet')
Пример #13
0
 def NCAV(self, tck):
     df = get_balance_sheet(tck)
     NCAV_last = (int(df.loc[df['Breakdown'] == 'Total Current Assets'].iloc[:,1]) - \
                  int(df.loc[df['Breakdown'] == 'Total Liabilities'].iloc[:,1]))*1000 / \
                 self.market_cap(tck)
     return NCAV_last
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()
Пример #15
0
pat_score = 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()
Пример #16
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()
Пример #17
0
def get_balance_sheet(tickers, yearly=True):
    dict_data = {
        ticker: si.get_balance_sheet(ticker, yearly)
        for ticker in tickers
    }
    return dict_data
Пример #18
0
 def down_bs(self, ticker):
     balance = si.get_balance_sheet(ticker)
     filename = ticker + 'BalanceSheet.txt'
     f = open(filename, "x")
     print(balance, file=f)
Пример #19
0
def getYearlyBalanceSheet(ticker):
    return si.get_balance_sheet(ticker)
Пример #20
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_quote_table(input_arguments.symbol))
        
    elif input_arguments.information == 'stats':
        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):
Пример #22
0
import yahoo_fin.stock_info as info
import datetime

ticker = []
test = 'ZM'

date = datetime.date.today()
print(date)

file = open('guide/tickers.txt', 'r').readlines()
for line in file:
    line = line.replace('\n', '')
    ticker.append(line)

print(info.get_data(test, start_date="1/2/2018"))
print(info.get_balance_sheet(test))
print(info.get_analysts_info(test))
Пример #23
0
 def get_balance_sheet(self):
     if self.storage == None:
         return self.format1D(stock_info.get_balance_sheet(self.stock))
     else:
         self.storage['balance_sheet'] = self.format1D(stock_info.get_balance_sheet(self.stock))
]

A = open('InformationTech.csv', 'w')
writer1 = csv.writer(A)
Col = ['Company'] + column_names
writer1.writerow(Col)

#this for loop cycles through every company
for companies in list_of_companies:
    print(companies)
    #add a csv writer that adds these to rows
    data_list = [companies]

    #this is the information from the balance sheet
    Loaded = 0
    company_data = get_balance_sheet(companies)

    #no matter how many times I try to redownload the data, the key is always missing

    #this line is being problematic
    Loaded += sum(
        company_data['Breakdown'].str.count("Total stockholders' equity"))

    while Loaded == 0.0:
        company_data = get_balance_sheet(companies)
        Loaded += sum(
            company_data['Breakdown'].str.count("Total stockholders' equity"))

    SE1 = float(company_data.iloc[company_data[
        company_data['Breakdown'] == "Total stockholders' equity"].index[0],
                                  1])
Пример #25
0
            return np.nan


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
Пример #26
0
def getQuarterlyBalanceSheet(ticker):
    return si.get_balance_sheet(ticker, yearly=False)
Пример #27
0
async def balance_sheet(ctx, *, ticker):
    await ctx.send(si.get_balance_sheet(ticker))
Пример #28
0
all_historical = {}
for ticker in all_tickers:
    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)
Пример #29
0
    WAM = int(
        input(
            'What is the Weighted Average Maturity of Debt Found in 10k Report (if unsure write 5):'
        ))
    print(int(input('Stock Based Compensation:')))
    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
    symbol = symbol.upper()
    
    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'