Пример #1
0
def opm_positive(stock_nm):
    #print("stock name is 1 ",stock_nm)
    stock_stats = si.get_stats(stock_nm)
    opm = float(stock_stats[stock_stats.Attribute ==
                            'Profit Margin'].Value.item().replace('%', ''))
    if opm >= 0:
        resonable_valuation(stock_nm, opm)
Пример #2
0
def shares(ticker):
    #This function calls a method from the yahoo api it converts into a dictionary
    test = yf.get_stats(ticker)
    test = test.set_index("Attribute")

    #converts a dataframe into an API
    dictionary = {}
    count = -1
    for i in test.index:
        count += 1
        for j in range(len(test["Value"])):
            if j == count:
                # print(test["Value"][j],i)
                dictionary[i] = test["Value"][j]

    string = dictionary["Shares Outstanding 5"]

    #the following takes a string and
    #converts it from a string into a int based on the string

    if string[-1] == "B":
        string = string.replace("B", "")
        shares_rounded = float(string) * 1000000000

    elif string[-1] == "M":
        string = string.replace("M", "")
        shares_rounded = float(string) * 1000000
    else:
        shares_rounded = float(string)

    return shares_rounded
Пример #3
0
 def getTickerStat(self, symbol):
     # remove white space, last number and format into {attribute: value}
     tickerStat = {"".join(rec[1].split())[:-1] if rec[1][-1].isdigit() else "".join(rec[1].split()): rec[2] for rec
                   in si.get_stats(symbol).to_records()}
     tickerStat = self.yahooFinanceDataModification.formatTickerStat(tickerStat)
     self.yahooFinanceDataModification.formatNanValues(tickerStat)
     return self.yahooFinanceDataModification.changeUnsupportedChart(tickerStat)
Пример #4
0
    def __init__(self, ticker, name, risk_free_return):
        yf_stock = YF(ticker)
        yf_stats = si.get_stats(ticker)
        key_statistics = yf_stock.get_key_statistics_data()

        self.ticker = ticker

        self.name = name

        self.risk_free_return = risk_free_return

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

        self.wacc = self.get_wacc(yf_stock)

        self.growth_estimate_per_annum = self.get_growth_estimate_per_annum()

        self.conservative_growth_rate = self.get_conservative_growth_rate()

        self.recommendation_rating = self.get_recommendation_rating()

        self.free_cash_flow = self.get_free_cash_flow()

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

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

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

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

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

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

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

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

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

        self.trailing_pe = self.get_trailing_pe(yf_stock)

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

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

        self.total_liabilities = self.get_total_liabilities(yf_stock)

        self.intrinsic_value = self.get_intrinsic_value()

        self.potential_upside = self.get_potential_upside()

        self.trailing_pe_pb_multiple = round(
            self.trailing_pe * self.price_per_book, 2)
Пример #5
0
def after_hours_usa():
    # Get After Hours Data from Source
    after_hours_url = 'https://www.marketwatch.com/tools/screener/after-hours'

    # K M B T string values to numbers
    m = {'K': 3, 'M': 6, 'B': 9, 'T': 12}

    # Symbol     Company Name    After HoursPrice    After HoursVol      After HoursChg      After HoursChg %
    main_df = pd.read_html(after_hours_url)[2]

    # List of Ticker Symbols
    tickers = main_df['Symbol'].tolist()

    #  Company Name      After HoursVol
    data_df = main_df[['Company Name', 'After HoursVol']]

    # Get M B to numbers for After Hours Volume
    after_hoursvol = data_df['After HoursVol'].tolist()
    after_hoursvol_list = [
        int(float(i[:-1]) * 10**m[i[-1]]) for i in after_hoursvol
    ]

    # Stock Symbol
    df0 = pd.DataFrame(tickers, columns=['Stock Symbol'])

    # Initializing DataFrame
    df2 = pd.DataFrame()

    # Get Data For all the Tickers
    for i in tickers:
        df = si.get_stats(i)
        df1 = df.loc[df['Attribute'] == 'Float']
        df2 = df2.append(df1, ignore_index=True)

    # Rename and Drop Columns of DataFrame
    df2 = df2.rename(columns={"Value": "Float Shares"}, errors="raise")
    df2 = df2.drop(columns=['Attribute'])

    # Get M B to numbers for float shares
    floatshares = df2['Float Shares'].tolist()
    float_list = [
        i if pd.isnull(i) else int(float(i[:-1]) * 10**m[i[-1]])
        for i in floatshares
    ]

    # After Hours Volume as a Percentage of Float Shares Calculation
    percentage = [
        after_hoursvol_list[i] / float_list[i] * 100
        for i in range(len(float_list))
    ]
    per_df = pd.DataFrame(percentage, columns=['Percentage'])

    # Float Shares      Symbol
    df3 = [df2, per_df, df0]

    # Company Name      After HoursVol      Float Shares        Stock Symbol
    final_df = data_df.join(df3)
    return final_df
Пример #6
0
def get_balance_sheet(ticker):
    stock = get_stats(f'{ticker}')

    l = []
    balance_sheet = stock.loc['28':, 'Attribute':'Value'].to_dict('records')
    price_his = stock.loc[0:8, 'Attribute':'Value'].to_dict('records')

    l = [balance_sheet, price_his]
    return l
Пример #7
0
 def get_market_cap(self, yahoo_ticker):
     try:
         stats = si.get_stats(yahoo_ticker)
     except (ValueError, KeyError):
         LOGGER.warning(
             'Could not find stock data for: {}, returning 0'.format(
                 yahoo_ticker))
         return 0
     market_cap = stats[stats.Attribute.str.contains('Market Cap')].Value[0]
     return self._convert_str_to_float(market_cap)
Пример #8
0
def process(symbols, path, key):
    for symbol in symbols:
        filename = build_file_name(symbol)
        bool = util.redis_set_read(key, symbol)
        if not bool:
            print(symbol)
            data = get_stats(symbol)
            out_file = path + filename
            data.to_csv(out_file)
            util.redis_set_write(key, symbol)
def update_asset_stats(managed_asset: asset.Asset) -> stats.AssetStats:
    """Updates stats of given assets.

  Args:
    managed_asset: Asset for which to update stats.

  Returns:
    Stats of the given asset.
  """
    tracker = managed_asset.get_tracker()
    price = managed_asset.current_price

    if not tracker:
        return stats.StockStats(managed_asset=managed_asset, price=price)

    try:
        fetched_price = _parse_and_format_value(
            stock_info.get_live_price(tracker))
    except AssertionError:
        fetched_price = None

    if not fetched_price:
        return stats.StockStats(managed_asset=managed_asset, price=price)

    price = fetched_price
    managed_asset.current_price = price

    stock_data = stock_info.get_stats(tracker)
    if stock_data.empty:
        return stats.StockStats(managed_asset=managed_asset, price=price)

    try:  # TODO: handle all types of assets instead of only stocks.
        stock_stats = stats.StockStats(
            managed_asset=managed_asset,
            price=price,
            debt_to_equity=_get_stock_stat_value(
                stock_data, StockAttribute.DEBT_TO_EQUITY),
            dividend_yield=_get_stock_stat_value(
                stock_data, StockAttribute.DIVIDEND_YIELD),
            eps=_get_stock_stat_value(stock_data, StockAttribute.EPS),
            pe=_get_stock_stat_value(stock_data, StockAttribute.PE),
            profit_margin=_get_stock_stat_value(stock_data,
                                                StockAttribute.PROFIT_MARGIN),
            return_on_equity=_get_stock_stat_value(
                stock_data, StockAttribute.RETURN_ON_EQUITY),
            revenue_growth=_get_stock_stat_value(
                stock_data, StockAttribute.REVENUE_GROWTH),
            value_over_ebitda=_get_stock_stat_value(
                stock_data, StockAttribute.VALUE_OVER_EBITDA),
        )
        managed_asset.stats = stock_stats
        return stock_stats
    except Exception:
        return stats.StockStats(managed_asset=managed_asset, price=price)
Пример #10
0
def getStockData(ticker):

    try:
        s = float(si.get_stats(ticker).Value[15].replace('%', ''))
        new_row = {'Stock': ticker, 'Short Percentage': s}

        if (s > 30):
            return new_row
        else:
            return False
    except:
        return False
Пример #11
0
def stats(request):
    ticker = json.loads(request.body)['ticker']

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

        return HttpResponse(output)
Пример #12
0
def Get_Stats_current(ticker):

    #print(ticker[0])
    df = si.get_stats(ticker[0])
    #print(df)
    df['ticker'] = ticker[0]

    #9,26,31,34,35,36,37,38,39,40,56,55
    df = df.iloc[[0, 2, 9, 26, 31, 34, 35, 36, 37, 38, 39, 40, 56, 55],
                 [0, 1, 2]]
    df = df.pivot(index='ticker', columns='Attribute', values='Value')
    df['RSI'] = ticker[1]
    df['Transdate'] = datetime.date.today()

    return df
Пример #13
0
def resonable_valuation(stock_nm, opm):
    #print("stock name is 2 ",stock_nm)
    #print("opm is pass 2 ",opm)
    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())
    #print("low",low_52)
    #print("200dma",dma_200)
    avg_price_to_consider = (low_52 + dma_200) / 2
    cmp = si.get_live_price(stock_nm)

    if cmp <= (avg_price_to_consider + avg_price_to_consider * (20 / 100)):
        stage_one_check(stock_nm, opm, avg_price_to_consider, cmp)
Пример #14
0
def resonable_valuation(stock_nm, opm, book_per_share, promoter_hold, roe,
                        eps):
    #print("stock name is 2 ",stock_nm)
    #print("opm is pass 2 ",opm)
    stock_nm = "ACC.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())
    #print("low",low_52)
    #print("200dma",dma_200)
    avg_price = (low_52 + dma_200) / 2
    cmp = si.get_live_price(stock_nm)

    final_print(stock_nm, opm, book_per_share, promoter_hold, roe, eps, cmp,
                avg_price)
Пример #15
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.")
Пример #16
0
def portDivYield(df, nShares):

    dvds = []
    nShares = np.array(nShares)

    for sec in df.columns.values:
        stts = si.get_stats(sec).set_index(['Attribute'])
        div = stts.loc['Trailing Annual Dividend Rate 3'].values[0]
        div = float(div)

        dvds.append(div)
    dvds = np.array(dvds)
    dvds = np.nan_to_num(dvds)
    totDvds = np.sum(dvds * nShares)
    totInvested = np.sum((df.iloc[-1] * nShares).values)

    yld = totDvds / totInvested

    return yld
Пример #17
0
    def is_good_business(self):
        """
        define the checker function for good busniess:
        - Good profit margin. Margin > 10%
        - Revenue keep grow. YOY rate > 20%
        - Revenue > 0.1 Billion USD
        - Positive cash flow.
        """
        status = True
        result = {}
        message = []
        stats = si.get_stats(self.name)
        logger.debug(stats)
        for index in range(len(stats)):
            result[stats.Attribute.iloc[index]] = _convert_to_numeric(
                stats.Value.iloc[index])

        # check rules
        if result["Profit Margin"] < 0.1:
            message.append(
                f"fail: weak profit margin. profit margin = {result['Profit Margin']*100}"
            )
            status = False
        if result["Revenue (ttm)"] < 100000000:
            message.append(f"fail: revenue less than 0.1 * billion." +
                           'Revenue = ' +
                           str(result["Revenue (ttm)"] / 1000000000) +
                           "Billion")
            status = False
        if result["Levered Free Cash Flow (ttm)"] < 0:
            message.append(
                f"fail: free cash flow is negative, Levered free cash flow (ttm) = "
                + str(result["Levered Free Cash Flow (ttm)"] / 1000000000) +
                "Billion USD")
            status = False
        if result["Quarterly Revenue Growth (yoy)"] < 0.1:
            message.append(f"fail: revenue growth yoy less than 10%." +
                           "rate = " +
                           str(result["Quarterly Revenue Growth (yoy)"] * 100))
            status = False
        logger.info(message)
        result_dict = result
        return status, message, result_dict
Пример #18
0
def Get_Stats(ticker, pindex):

    #print(ticker[0])
    df = si.get_stats(ticker)
    #print(df)
    df['ticker'] = ticker

    df = df.pivot(index='ticker', columns='Attribute', values='Value')
    #print(df)
    if not os.path.exists("/Users/rajubingi/Equity_Data/" + pindex +
                          "_stats.csv"):
        df.to_csv("/Users/rajubingi/Equity_Data/" + pindex + "_stats.csv",
                  mode='a')
    else:
        df.to_csv("/Users/rajubingi/Equity_Data/" + pindex + "_stats.csv",
                  header=False,
                  mode='a')

    return 'success'
Пример #19
0
 def update(self, new_ticker, rate):
     old_ticker = self.ticker
     self.risk_free_rate = rate / 100
     self.ticker = new_ticker.upper()
     if (self.ticker != '') & (new_ticker != old_ticker):
         self.current_price = si.get_live_price(self.ticker)
         self.todays_times = [
             datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")[11:]
         ]
         self.prices_today = [si.get_live_price(self.ticker)]
         self.historical = si.get_data(self.ticker)
         self.option_dates = options.get_expiration_dates(new_ticker)
         self.observed_options = {}
         try:
             self.stats = si.get_stats(self.ticker).to_dict('records')
         except ValueError:
             self.stats = [{
                 'Attribute': 'none available',
                 'Value': 'none available'
             }]
Пример #20
0
def opm_book_val_promoter_hold_roe_eps(stock_nm):
    #print("stock name is 1 ",stock_nm)
    #stock_nm="ACC.NS"
    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:
        resonable_valuation(stock_nm, opm, book_per_share, promoter_hold, roe,
                            eps)
Пример #21
0
def fair_value(ticker, years=1, wish_return=0.4):
    netincome = Decimal(si.get_income_statement(ticker)[si.get_income_statement(ticker).columns[0]].netIncome)

    shares_outstanding = number_encoder(str(si.get_stats(ticker)["Value"][9]))

    current_eps = netincome / shares_outstanding

    all_growth_rates = [Decimal(x[:-1]) for x in si.get_analysts_info(ticker)["Revenue Estimate"][
                                                     si.get_analysts_info(ticker)["Revenue Estimate"].columns[
                                                     :-2]].iloc[5][1:].dropna()]

    growth_rate = sum(all_growth_rates) / len(all_growth_rates) / 100

    projected_eps = current_eps * (1 + growth_rate) ** years

    projected_pe_ratio = Decimal(si.get_live_price(ticker)) / projected_eps

    forwarded_pe_ratio = Decimal(si.get_stats_valuation(ticker)[si.get_stats_valuation(ticker).columns[1]][2]) * (
                1 + growth_rate) ** (years - 1)

    return (forwarded_pe_ratio * projected_eps) / Decimal(1 + wish_return)
Пример #22
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
Пример #23
0
from yahoo_fin import stock_info as si
import numpy as np

#import the list as string array
theList = np.genfromtxt("listStock_lq45.txt", dtype='str')

for ticker in theList:
        #at yahoo finance, the IDX stocks are marked with .jk at the end
        tickerjk = ticker+".jk"

        #get lowest 52 week
        stockPrice = si.get_stats("%s" % tickerjk)
        lowest = stockPrice.iloc[13,1]

        #get highest 52 week
        stockPrice = si.get_stats("%s" % tickerjk)
        highest = stockPrice.iloc[12,1
        
        #get current price
        livePrice = si.get_live_price(("%s" % tickerjk))
                
        #print altogether ticker, lowest, current and highest
        print(ticker, lowest, livePrice, highest)
Пример #24
0
for company in df['compsymbol']:
    count = count + 1
    Market_Cap = []
    Enterprise_Value = []
    EBITDA_LIST_VALUES = []
    data_stats_valuation = si.get_stats_valuation(company)
    market_cap = data_stats_valuation.iloc[0]
    market_cap_final = market_cap[1]
    Market_Cap.append(market_cap_final)
    print('-----', company)
    print('marktcp', Market_Cap)
    enterprice_value = data_stats_valuation.iloc[1]
    enterprice_value_final = enterprice_value[1]
    Enterprise_Value.append(enterprice_value_final)
    print('enterpval', Enterprise_Value)
    mydata_stats = si.get_stats(company)
    row_touse = mydata_stats.loc[mydata_stats['Attribute'] == 'EBITDA']
    ebitda_row = row_touse.iloc[0]
    final_ebitda = ebitda_row[1]
    EBITDA_LIST_VALUES.append(final_ebitda)
    print('eb', EBITDA_LIST_VALUES)
    print('----------------API END')
    print('----------------WEBSCRAPING')
    try:
        empl = []
        time.sleep(3)
        full_profile = 'https://finance.yahoo.com/quote/' + company + '/profile?p=' + company
        print(full_profile)
        r = requests.get(full_profile)
        htmlcontent = r.content
        soup_profile = BeautifulSoup(htmlcontent, 'html.parser')
Пример #25
0
    Domestic_Business = Countries.get(Business_Country)
    print('Country Risk Premium Based Off Business\' Home Country:',
          (Revenue_stream * Domestic_Business))

    print('Equity Risk Premium:', ERP)

    # live pricing of United States 1O year Treasury Bond
    Tbond = yf.get_data('^TNX')
    Recent_Tbond = yf.get_live_price('^TNX')
    print("10 year Treasury bond:", "{:.4f}".format(Recent_Tbond), '%')

    # Cost of equity for that equity
    Cost_of_Equity = Recent_Tbond + beta * ERP
    print("Cost of Equity:", "{:.4f}".format(Cost_of_Equity), "%")

    stats2 = yf.get_stats(Ticker)
    OutstandingShares = conv_mrktcap(stats2.loc[9][1])
    print('Outstanding Shares:', "{:,}".format(OutstandingShares), 'Shares')
    LivePrice = yf.get_live_price(Ticker)
    MarketValueOfEquity = OutstandingShares * LivePrice
    print('Market Value of Equity', "{:,}".format(round(MarketValueOfEquity)),
          '$')
    TotalDebt = conv_mrktcap(stats2.loc[44][1])
    print('Total Debt:', "{:,}".format(TotalDebt), '$')

    if conv_mrktcap(MarketCap) > 5000000000:
        # Using for loop to iterate through the list to print out the necessary detail
        for i in range(0, len(ICR1)):
            # Checking if the ICR is in the boundary or not
            if (icr >= ICR1[i] and icr <= ICR2[i]):
                # Printing the results and breaking the loop
Пример #26
0
def process():
    for symbol in symbols:
        print(symbol)
        filename = build_file_name(symbol)
        data = get_stats(symbol)
        data.to_csv(filename)
Пример #27
0
tickersDF.index.rename('ticker', inplace=True)
tickersDF.drop(columns=['Symbol'], inplace=True)

# # Sort Data

table = pd.DataFrame()

ticker_index = []
retry_ticker = []
count = 0

for p in tickers:
    #     print(p)
    try:
        data = si.get_stats(p)
        data.index = data["Attribute"]
        data = data.drop(labels="Attribute", axis=1)
        raw_table = data.T
        raw_table['current_price'] = round(si.get_live_price(p), 2)
        table = table.append(raw_table)  #Table having Data about the company
        ticker_index.append(p)
    except:
        count = count + 1
        print('Bad Ticker {}: {}'.format(count, p))
        retry_ticker.append(p)

if len(retry_ticker) > 0:
    time.sleep(60 * 20)
    count = 0
Пример #28
0
#* http://theautomatic.net/yahoo_fin-documentation/#updates

import yahoo_fin.stock_info as si
df = si.get_stats('TSLA')
df = df.iloc[:9]
df['Attribute'][:2] = df['Attribute'][:2].str[:-2]
df['Attribute'][3:5] = df['Attribute'][3:5].str[:-2]
df['Attribute'][7:] = df['Attribute'][7:].str[:-2]
df.set_index('Attribute', inplace=True)
print(df)
Пример #29
0
def datePlusOne(str):
    date = datetime.strptime(str, '%b %d, %Y')
    addOne = timedelta(days=1)
    date = date + addOne
    strDate = date.strftime('%b %d, %Y')
    return strDate


for j in range(2, 30):
    if (sheet.cell(j, 1).value == ""):
        break

for i in range(2, j):
    ticker = sheet.cell(i, 1).value
    data = si.get_stats(ticker)

    ex_date = data['Value'][25]
    sheet.update_cell(i, 20, datePlusOne(ex_date))

    pay_date = data['Value'][24]
    sheet.update_cell(i, 21, datePlusOne(pay_date))

    div = data['Value'][18]
    if isinstance(div, float): sheet.update_cell(i, 9, "")
    else: sheet.update_cell(i, 9, div)

    beta = data['Value'][0]
    if isinstance(beta, float): sheet.update_cell(i, 22, "")
    else: sheet.update_cell(i, 22, beta)
Пример #30
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)