示例#1
0
def income_statement(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="incom",
        description="""
            Prints a complete income statement over time. This can be either quarterly or annually.
            The following fields are expected: Accepted date, Cost and expenses, Cost of revenue,
            Depreciation and amortization, Ebitda, Ebitdaratio, Eps, Epsdiluted, Filling date,
            Final link, General and administrative expenses, Gross profit, Gross profit ratio,
            Income before tax, Income before tax ratio, Income tax expense, Interest expense, Link,
            Net income, Net income ratio, Operating expenses, Operating income, Operating income
            ratio, Other expenses, Period, Research and development expenses, Revenue, Selling and
            marketing expenses, Total other income expenses net, Weighted average shs out, Weighted
            average shs out dil [Source: Alpha Vantage]""",
    )

    parser.add_argument(
        "-n",
        "--num",
        action="store",
        dest="n_num",
        type=check_positive,
        default=1,
        help="Number of latest years/quarters.",
    )
    parser.add_argument(
        "-q",
        "--quarter",
        action="store_true",
        default=False,
        dest="b_quarter",
        help="Quarter fundamental data flag.",
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, l_args)
        if not ns_parser:
            return

        if ns_parser.n_num == 1:
            pd.set_option("display.max_colwidth", None)
        else:
            pd.options.display.max_colwidth = 40

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas")
        if ns_parser.b_quarter:
            # pylint: disable=unbalanced-tuple-unpacking
            df_fa, _ = fd.get_income_statement_quarterly(symbol=s_ticker)
        else:
            # pylint: disable=unbalanced-tuple-unpacking
            df_fa, _ = fd.get_income_statement_annual(symbol=s_ticker)

        df_fa = clean_fundamentals_df(df_fa, num=ns_parser.n_num)
        print(df_fa)
        print("")

    except Exception as e:
        print(e)
        print("")
        return
示例#2
0
def income_init_annual(request):

    if request.method == 'GET':
        symbol = request.GET.get('symbol')

        data = FundamentalData(key='I7WB8M63PERU90OY', output_format='pandas')
        qincomes, vasymbol = data.get_income_statement_annual(symbol=symbol)

        for fical in qincomes['fiscalDateEnding']:
            income = qincomes[qincomes['fiscalDateEnding'] == fical]

            for col in income.columns:
                if col not in ['fiscalDateEnding', 'reportedCurrency']:
                    if income[col].values[0] == 'None':
                        income[col] = 0.0
                    else:
                        pass
                else:
                    pass

            inc = Income(
                symbol=symbol,
                report_type='quarterlyReport',
                fiscal_date_ending= datetime.strptime(income['fiscalDateEnding'].values[0], '%Y-%m-%d'),
                fiscal_year=income['fiscalDateEnding'].values[0].split('-')[0],
                reported_currency=income['reportedCurrency'].values[0],
                total_revenue=income['totalRevenue'].values[0],
                total_operating_expense=income['totalOperatingExpense'].values[0],
                cost_of_revenue=income['costOfRevenue'].values[0],
                gross_profit=income['grossProfit'].values[0],
                ebit=income['ebit'].values[0],
                net_income=income['netIncome'].values[0],
                research_and_development=income['researchAndDevelopment'].values[0],
                effect_of_accounting_charges=income['effectOfAccountingCharges'].values[0],
                income_before_tax=income['incomeBeforeTax'].values[0],
                minority_interest=income['minorityInterest'].values[0],
                selling_general_administrative=income['sellingGeneralAdministrative'].values[0],
                other_non_operating_income=income['otherNonOperatingIncome'].values[0],
                operating_income=income['operatingIncome'].values[0],
                other_operating_expense=income['otherOperatingExpense'].values[0],
                interest_expense=income['interestExpense'].values[0],
                tax_provision=income['taxProvision'].values[0],
                interest_income=income['interestIncome'].values[0],
                net_interest_income=income['netInterestIncome'].values[0],
                extraordinary_items=income['extraordinaryItems'].values[0],
                non_recurring=income['nonRecurring'].values[0],
                other_items=income['otherItems'].values[0],
                income_tax_expense=income['incomeTaxExpense'].values[0],
                total_other_income_expense=income['totalOtherIncomeExpense'].values[0],
                discontinued_operations=income['discontinuedOperations'].values[0],
                net_income_from_continuing_operations=income['netIncomeFromContinuingOperations'].values[0],
                net_income_applicable_to_common_shares=income['netIncomeApplicableToCommonShares'].values[0],
                preferred_stock_and_other_adjustments=income['preferredStockAndOtherAdjustments'].values[0],
            )

            inc.save()

        return JsonResponse({'message': 'Annual Data Save successlly'},  status=status.HTTP_200_OK)
示例#3
0
def get_data(console, ticker, ror):
    #This function returns the following details when given a stock ticker/symbol:
    #Earnings per Share, Equity Growth, P/E Ratio
    console.print('Fetching data...', style="blue")

    fd = FundamentalData(key=api_key)
    data = {
        "function": "OVERVIEW",
        "symbol": ticker,
        "outputsize": "compact",
        "datatype": "json",
        "apikey": api_key,
    }

    #Get Balance Sheet data of past five years
    bs_data, meta = fd.get_balance_sheet_annual(ticker)

    latest_equity = bs_data['totalShareholderEquity'][0]
    oldest_equity = bs_data['totalShareholderEquity'][4]

    #Calculating equity growth over five years
    eq_gr = calculate_equity_growth(latest_equity, oldest_equity, 5)

    #Get TTM EPS & PE Ratio
    response = requests.get(API_URL, data)
    co_data = response.json()
    eps = co_data['EPS']
    per = co_data['PERatio']

    #Get Company Details
    company_name = co_data['Name']
    company_country = co_data['Country']
    company_industry = co_data['Industry']
    company_sector = co_data['Sector']
    company_exchange = co_data['Exchange']

    trading_price = get_price(ticker)

    calculated_data = calculate_fair_value(console, ticker, eps, eq_gr, per,
                                           ror, 5)

    company_data = {
        'company_name': company_name,
        'company_country': company_country,
        'company_industry': company_industry,
        'company_sector': company_sector,
        'company_exchange': company_exchange,
        'eps': eps,
        'eq_gr': eq_gr,
        'per': per,
        'trading_price': trading_price,
        'calculated_data': calculated_data
    }

    console.print('Data Fetched!', style="green bold")

    return company_data
示例#4
0
def get_dupont(ticker: str) -> pd.DataFrame:
    """Get dupont ratios

    Parameters
    ----------
    ticker : str
        Stock ticker

    Returns
    -------
    dupont : pd.DataFrame
        The dupont ratio breakdown
    """

    try:
        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas")
        # pylint: disable=unbalanced-tuple-unpacking
        df_bs, _ = fd.get_balance_sheet_annual(symbol=ticker)
        df_is, _ = fd.get_income_statement_annual(symbol=ticker)

    except Exception as e:
        console.print(e)
        return pd.DataFrame()

    # pylint: disable=no-member
    df_bs = df_bs.set_index("fiscalDateEnding")
    df_is = df_is.set_index("fiscalDateEnding")
    dupont_years = pd.DataFrame()

    for i in range(len(df_bs)):
        ni = df_values(df_is, "netIncome", i, 1)
        pretax = df_values(df_is, "incomeBeforeTax", i, 1)
        ebit = df_values(df_is, "ebit", i, 1)
        sales = df_values(df_is, "totalRevenue", i, 1)
        assets = df_values(df_bs, "totalAssets", i, 1)
        equity = df_values(df_bs, "totalShareholderEquity", i, 1)

        ratios: Dict = {}
        try:
            ratios["Tax Burden"] = clean_fraction(ni[0], pretax[0])
            ratios["Interest Burden"] = clean_fraction(pretax[0], ebit[0])
            ratios["EBIT Margin"] = clean_fraction(ebit[0], sales[0])
            ratios["Asset Turnover"] = clean_fraction(sales[0], assets[0])
            ratios["Finance Leverage"] = clean_fraction(assets[0], equity[0])
            ratios["ROI"] = clean_fraction(ni[0], equity[0])
        except IndexError:
            pass

        if dupont_years.empty:
            dupont_years.index = ratios.keys()
        dupont_years[df_bs.index[i]] = ratios.values()
    dupont_years = dupont_years[sorted(dupont_years)]
    return dupont_years
示例#5
0
def generate_report(stock):
    logger.info(f"Generating report for {stock}")
    if stock.replace("$", "") in const.CRYPTO_CURRENCIES:
        crypto = CryptoCurrencies(key=environ["ALPHA_VANTAGE_API_KEY"])
        data, _ = crypto.get_digital_crypto_rating(stock)
    else:
        fd = FundamentalData(key=environ["ALPHA_VANTAGE_API_KEY"])
        data, _ = fd.get_company_overview(stock)
        for (key, val) in list(data.items()):
            if val.isnumeric():
                data[key] = "${:,.2f}".format(float(val))
            if key not in const.REPORT_FIELDS:
                data.pop(key)
    save_report_to_image(data)
示例#6
0
def get_split_factor(reminder):
    if reminder.stock_symbol in const.CRYPTO_CURRENCIES:
        return 1.0

    fd = FundamentalData(key=environ["ALPHA_VANTAGE_API_KEY"])
    data, _ = fd.get_company_overview(reminder.stock_symbol)

    if data["LastSplitDate"] == "None":
        return 1.0
    split_date = datetime.strptime(data["LastSplitDate"], "%Y-%m-%d").date()
    stock_was_split = reminder.created_on < split_date < date.today()
    if stock_was_split:
        return float(data["LastSplitFactor"][0]) / float(data["LastSplitFactor"][2])
    return 1.0
示例#7
0
class FundamentalDataAPI(BaseAPI):
    """

    xxx
    """
    def __init__(self):
        super(FundamentalDataAPI, self).__init__()
        self.fd = FundamentalData(key=self.api,
                                  output_format=self.output_format)

    def get_company_overview(self, symbol):
        return self.fd.get_company_overview(symbol)

    def get_earnings(self, symbol):
        return self.fd.get_income_statement_quarterly(symbol)

    def plot(self, **kwargs):
        return super().plot(**kwargs)
示例#8
0
文件: app.py 项目: TP70/FinancialData
def get_option():
    print(
        'Please inform one of the following options:\n1 - Stock Time Series\n2 - Fundamental Data\n'
    )
    if validation_user_input('OPTION NUMBER: ', ['1', '2'], True) == '1':
        return StockTimeSeries.display_options_ts(
            TimeSeries(key=API_key, output_format='pandas'))
    else:
        return Fundamental.display_options_fd(
            FundamentalData(key=API_key, output_format='pandas'))
示例#9
0
def get_portfolio_insights(request):
    try:
        portfolio = Portfolio.objects.get(user=request.user)
        holding_companies = StockHolding.objects.filter(portfolio=portfolio)
        fd = FundamentalData(key=get_alphavantage_key(), output_format='json')
        portfolio_beta = 0
        portfolio_pe = 0
        for c in holding_companies:
            data, meta_data = fd.get_company_overview(symbol=c.company_symbol)
            portfolio_beta += float(data['Beta']) * (
                c.investment_amount / portfolio.total_investment)
            portfolio_pe += float(data['PERatio']) * (
                c.investment_amount / portfolio.total_investment)
        return JsonResponse({
            "PortfolioBeta": portfolio_beta,
            "PortfolioPE": portfolio_pe
        })
    except Exception as e:
        return JsonResponse({"Error": str(e)})
示例#10
0
def add_holding(request):
    if request.method == "POST":
        try:
            portfolio = Portfolio.objects.get(user=request.user)
            holding_companies = StockHolding.objects.filter(
                portfolio=portfolio)
            company_symbol = request.POST['company'].split('(')[1].split(
                ')')[0]
            company_name = request.POST['company'].split('(')[0].strip()
            number_stocks = int(request.POST['number-stocks'])
            ts = TimeSeries(key=get_alphavantage_key(), output_format='json')
            data, meta_data = ts.get_daily(symbol=company_symbol,
                                           outputsize='full')
            buy_price = float(data[request.POST['date']]['4. close'])
            fd = FundamentalData(key=get_alphavantage_key(),
                                 output_format='json')
            data, meta_data = fd.get_company_overview(symbol=company_symbol)
            sector = data['Sector']

            found = False
            for c in holding_companies:
                if c.company_symbol == company_symbol:
                    c.buying_value.append([buy_price, number_stocks])
                    c.save()
                    found = True

            if not found:
                c = StockHolding.objects.create(portfolio=portfolio,
                                                company_name=company_name,
                                                company_symbol=company_symbol,
                                                number_of_shares=number_stocks,
                                                sector=sector)
                c.buying_value.append([buy_price, number_stocks])
                c.save()

            return HttpResponse("Success")
        except Exception as e:
            print(e)
            return HttpResponse(e)
示例#11
0
def get_financials(request):
    try:
        fd = FundamentalData(key=get_alphavantage_key(), output_format='json')
        data, meta_data = fd.get_company_overview(
            symbol=request.GET.get('symbol'))
        financials = {
            "52WeekHigh": data['52WeekHigh'],
            "52WeekLow": data['52WeekLow'],
            "Beta": data['Beta'],
            "BookValue": data['BookValue'],
            "EBITDA": data['EBITDA'],
            "EVToEBITDA": data['EVToEBITDA'],
            "OperatingMarginTTM": data['OperatingMarginTTM'],
            "PERatio": data['PERatio'],
            "PriceToBookRatio": data['PriceToBookRatio'],
            "ProfitMargin": data['ProfitMargin'],
            "ReturnOnAssetsTTM": data['ReturnOnAssetsTTM'],
            "ReturnOnEquityTTM": data['ReturnOnEquityTTM'],
            "Sector": data['Sector'],
        }
        return JsonResponse({"financials": financials})
    except Exception as e:
        return JsonResponse({"Error": str(e)})
示例#12
0
def connect():
    if len(CONNECTIONS) > 0:
        return

    module = sys.modules[__name__]

    secrets = defaultdict(lambda: '_:_', SECRETS)
    username, password = secrets['robinhood'].split(':')
    CONNECTIONS['rh'] = rh.login(username, password)
    rh.helper.set_output(open(os.devnull, "w"))

    iex_api_key = secrets['iex_api_key']
    os.environ['IEX_TOKEN'] = iex_api_key
    os.environ['IEX_OUTPUT_FORMAT'] = 'json'
    if iex_api_key[0] == 'T':
        os.environ['IEX_API_VERSION'] = 'sandbox'

    finnhub_api_key = secrets['finnhub_api_key']
    CONNECTIONS['fh'] = _fh.Client(
        api_key=finnhub_api_key) if finnhub_api_key else None
    module.fh = CONNECTIONS['fh']

    CONNECTIONS['yec'] = _yec.YahooEarningsCalendar()
    # use datetime.fromtimestamp() for ^^'s results
    module.yec = CONNECTIONS['yec']

    alpha_vantage_api_key = secrets['alpha_vantage_api_key']
    os.environ['ALPHAVANTAGE_API_KEY'] = alpha_vantage_api_key
    # ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas')
    # data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')

    CONNECTIONS['av'] = dict(fd=FundamentalData())
    module.fd = CONNECTIONS['av']['fd']

    CONNECTIONS['tii'] = tii.TiingoClient(
        dict(session=True, api_key=secrets['tiingo_api_key']))
    module.tii = CONNECTIONS['tii']
示例#13
0
def get_fraud_ratios(ticker: str) -> Tuple[Dict[str, float], float]:
    """Get fraud ratios based on fundamentals

    Parameters
    ----------
    ticker : str
        Stock ticker

    Returns
    -------
    Dict[float]:
        Dictionary of fraud metrics
    float:
        Z score for fraud metrics
    """
    fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas")
    # pylint: disable=unbalanced-tuple-unpacking
    # pylint: disable=no-member
    df_cf, _ = fd.get_cash_flow_annual(symbol=ticker)
    df_bs, _ = fd.get_balance_sheet_annual(symbol=ticker)
    df_is, _ = fd.get_income_statement_annual(symbol=ticker)
    df_cf = df_cf.set_index("fiscalDateEnding").iloc[:2]
    df_bs = df_bs.set_index("fiscalDateEnding").iloc[:2]
    df_is = df_is.set_index("fiscalDateEnding").iloc[:2]

    ar = df_bs["currentNetReceivables"].apply(lambda x: 0 if x else int(x)).values
    sales = df_is["totalRevenue"].apply(lambda x: 0 if x else int(x)).values
    cogs = (
        df_is["costofGoodsAndServicesSold"].apply(lambda x: 0 if x else int(x)).values
    )
    ni = df_is["netIncome"].apply(lambda x: 0 if x else int(x)).values
    ca = df_bs["totalCurrentAssets"].apply(lambda x: 0 if x else int(x)).values
    cl = df_bs["totalCurrentLiabilities"].apply(lambda x: 0 if x else int(x)).values
    ppe = df_bs["propertyPlantEquipment"].apply(lambda x: 0 if x else int(x)).values
    cash = (
        df_bs["cashAndCashEquivalentsAtCarryingValue"]
        .apply(lambda x: 0 if x else int(x))
        .values
    )
    cash_and_sec = (
        df_bs["cashAndShortTermInvestments"].apply(lambda x: 0 if x else int(x)).values
    )
    sec = [y - x for (x, y) in zip(cash, cash_and_sec)]
    ta = df_bs["totalAssets"].apply(lambda x: 0 if x else int(x)).values
    dep = (
        df_bs["accumulatedDepreciationAmortizationPPE"]
        .apply(lambda x: 0 if x else int(x))
        .values
    )
    sga = (
        df_is["sellingGeneralAndAdministrative"]
        .apply(lambda x: 0 if x else int(x))
        .values
    )
    tl = df_bs["totalLiabilities"].apply(lambda x: 0 if x else int(x)).values
    icfo = (
        df_is["netIncomeFromContinuingOperations"]
        .apply(lambda x: 0 if x else int(x))
        .values
    )
    cfo = df_cf["operatingCashflow"].apply(lambda x: 0 if x else int(x)).values
    ratios: Dict = {}
    ratios["DSRI"] = (ar[0] / sales[0]) / (ar[1] / sales[1])
    ratios["GMI"] = ((sales[1] - cogs[1]) / sales[1]) / (
        (sales[0] - cogs[0]) / sales[0]
    )
    ratios["AQI"] = (1 - ((ca[0] + ppe[0] + sec[0]) / ta[0])) / (
        1 - ((ca[1] + ppe[1] + sec[1]) / ta[1])
    )
    ratios["SGI"] = sales[0] / sales[1]
    ratios["DEPI"] = (dep[1] / (ppe[1] + dep[1])) / (dep[0] / (ppe[0] + dep[0]))
    ratios["SGAI"] = (sga[0] / sales[0]) / (sga[1] / sales[1])
    ratios["LVGI"] = (tl[0] / ta[0]) / (tl[1] / ta[1])
    ratios["TATA"] = (icfo[0] - cfo[0]) / ta[0]
    ratios["MSCORE"] = (
        -4.84
        + (0.92 * ratios["DSRI"])
        + (0.58 * ratios["GMI"])
        + (0.404 * ratios["AQI"])
        + (0.892 * ratios["SGI"])
        + (0.115 * ratios["DEPI"] - (0.172 * ratios["SGAI"]))
        + (4.679 * ratios["TATA"])
        - (0.327 * ratios["LVGI"])
    )

    zscore = (
        -4.336
        - (4.513 * (ni[0] / ta[0]))
        + (5.679 * (tl[0] / ta[0]))
        + (0.004 * (ca[0] / cl[0]))
    )

    return ratios, zscore
示例#14
0
def balancesheet_init_annual(request):

    if request.method == 'GET':

        symbol = request.GET.get('symbol')

        data = FundamentalData(key='I7WB8M63PERU90OY', output_format='pandas')
        balancesheets, vasymbol = data.get_balance_sheet_annual(symbol=symbol)

        for fical in balancesheets['fiscalDateEnding']:
            balancesheet = balancesheets[balancesheets['fiscalDateEnding'] ==
                                         fical]

            for col in balancesheet.columns:
                if col not in ['fiscalDateEnding', 'reportedCurrency']:
                    if balancesheet[col].values[0] == 'None':
                        balancesheet[col] = 0.0
                    else:
                        pass
                else:
                    pass

            bs = BalanceSheet(
                symbol=symbol,
                report_type='annualReport',
                fiscal_date_ending=datetime.strptime(
                    balancesheet['fiscalDateEnding'].values[0], '%Y-%m-%d'),
                reported_currency=balancesheet['reportedCurrency'].values[0],
                total_assets=balancesheet['totalAssets'].values[0],
                intangible_assets=balancesheet['intangibleAssets'].values[0],
                earning_assets=balancesheet['earningAssets'].values[0],
                other_current_assets=balancesheet['otherCurrentAssets'].
                values[0],
                total_liabilities=balancesheet['totalLiabilities'].values[0],
                total_shareholder_equity=balancesheet['totalShareholderEquity']
                .values[0],
                deferred_long_term_liabilities=balancesheet[
                    'deferredLongTermLiabilities'].values[0],
                other_current_liabilities=balancesheet[
                    'otherCurrentLiabilities'].values[0],
                common_stock=balancesheet['commonStock'].values[0],
                retained_earnings=balancesheet['retainedEarnings'].values[0],
                other_liabilities=balancesheet['otherLiabilities'].values[0],
                goodwill=balancesheet['goodwill'].values[0],
                other_assets=balancesheet['otherAssets'].values[0],
                cash=balancesheet['cash'].values[0],
                total_current_liabilities=balancesheet[
                    'totalCurrentLiabilities'].values[0],
                short_term_debt=balancesheet['shortTermDebt'].values[0],
                current_long_term_debt=balancesheet['currentLongTermDebt'].
                values[0],
                other_shareholder_equity=balancesheet['otherShareholderEquity']
                .values[0],
                property_plant_equipment=balancesheet['propertyPlantEquipment']
                .values[0],
                total_current_assets=balancesheet['totalCurrentAssets'].
                values[0],
                long_term_investment=balancesheet['longTermInvestments'].
                values[0],
                net_tangible_assets=balancesheet['netTangibleAssets'].
                values[0],
                short_term_investment=balancesheet['shortTermInvestments'].
                values[0],
                net_receivables=balancesheet['netReceivables'].values[0],
                long_term_debt=balancesheet['longTermDebt'].values[0],
                inventory=balancesheet['inventory'].values[0],
                accounts_payable=balancesheet['accountsPayable'].values[0],
                total_permanent_equity=balancesheet['totalPermanentEquity'].
                values[0],
                additional_paid_in_capital=balancesheet[
                    'additionalPaidInCapital'].values[0],
                common_stock_total_equity=balancesheet[
                    'commonStockTotalEquity'].values[0],
                preferred_stock_total_equity=balancesheet[
                    'preferredStockTotalEquity'].values[0],
                retained_earnings_total_equity=balancesheet[
                    'retainedEarningsTotalEquity'].values[0],
                treasury_stock=balancesheet['treasuryStock'].values[0],
                accumulated_amortization=balancesheet[
                    'accumulatedAmortization'].values[0],
                other_non_current_assets=balancesheet['otherNonCurrrentAssets']
                .values[0],
                deferred_long_term_asset_charges=balancesheet[
                    'deferredLongTermAssetCharges'].values[0],
                total_non_current_assets=balancesheet['totalNonCurrentAssets'].
                values[0],
                capital_lease_obligations=balancesheet[
                    'capitalLeaseObligations'].values[0],
                total_long_term_debt=balancesheet['totalLongTermDebt'].
                values[0],
                other_non_current_liabilities=balancesheet[
                    'otherNonCurrentLiabilities'].values[0],
                total_non_current_liabilities=balancesheet[
                    'totalNonCurrentLiabilities'].values[0],
                negative_goodwill=balancesheet['negativeGoodwill'].values[0],
                warrants=balancesheet['warrants'].values[0],
                preferred_stock_redeemable=balancesheet[
                    'preferredStockRedeemable'].values[0],
                capital_surplus=balancesheet['capitalSurplus'].values[0],
                liabilities_and_shareholder_equity=balancesheet[
                    'liabilitiesAndShareholderEquity'].values[0],
                cash_and_short_term_investments=balancesheet[
                    'cashAndShortTermInvestments'].values[0],
                accumulated_depreciation=balancesheet[
                    'accumulatedDepreciation'].values[0],
                common_stock_shares_outstanding=balancesheet[
                    'commonStockSharesOutstanding'].values[0],
            )

            bs.save()

        return JsonResponse(
            {'message': 'Annualy BalanceSheet Data Save successlly'},
            status=status.HTTP_200_OK)
示例#15
0
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.fundamentaldata import FundamentalData
import alpha_vantage
from alpha_vantage import techindicators
from alpha_vantage import sectorperformance
import requests
import json
from datetime import date
import sqlite3

keyread = open("C:\Key Dump\Alphavantagekey.txt", "r")
api_key = keyread.read()

ts = TimeSeries(api_key)
fd = FundamentalData(api_key)

z = True
while z is True:
    orders = input("Enter request: ")

    def CompanyOverview():
        global symbols
        symbols = input("Enter search term: ")
        if symbols == "Cancel":
            return ()
        try:
            print(" ")
            print(fd.get_company_overview(symbols))
            print(" ")
        except:
            wp = f"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={symbols}&apikey={api_key}"
示例#16
0
 def eps(self):
     FundamentalData.get_company_overview(self.ticker)
import sys
sys.path.append(r'C:\Users\sdisawal\Desktop\Stocks\Code')
sys.path.append(r'C:\Users\sdisawal\PycharmProjects\LearnApi\alpha_vantage')
#print(sys.path)

#%% Import Statements
import secrets_key as sk
from alpha_vantage.fundamentaldata import FundamentalData
import pandas as pd
import time

#%% Generate api key
api_key = sk.fmp_api_key()

#%%
fd = FundamentalData(key=api_key, output_format='pandas')

#%%
p_df = pd.read_csv(r'C:\Users\sdisawal\python_projects\focusedstock\rbh.csv')
tickers = p_df["Symbol"].to_list()


#%%
###################### Data Ingestion ######################
def fin_dfs(tickers, st_type):
    df = pd.DataFrame()
    start_time = time.time()
    api_call_count = 1

    for ticker in tickers:
def cash_flow(other_args: List[str], ticker: str):
    """Alpha Vantage cash flow

    Parameters
    ----------
    other_args : List[str]
        argparse other args
    ticker : str
        Fundamental analysis ticker symbol
    """

    parser = argparse.ArgumentParser(
        add_help=False,
        prog="cash",
        description="""
            Prints a complete cash flow statement over time. This can be either quarterly or
            annually. The following fields are expected: Accepted date, Accounts payables, Accounts
            receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, Cash
            at end of period, Change in working capital, Common stock issued, Common stock
            repurchased, Debt repayment, Deferred income tax, Depreciation and amortization,
            Dividends paid, Effect of forex changes on cash, Filling date, Final link, Free cash
            flow, Inventory, Investments in property plant and equipment, Link, Net cash provided
            by operating activities, Net cash used for investing activities, Net cash used provided
            by financing activities, Net change in cash, Net income, Operating cash flow, Other
            financing activities, Other investing activities, Other non cash items, Other working
            capital, Period, Purchases of investments, Sales maturities of investments, Stock based
            compensation. [Source: Alpha Vantage]
        """,
    )

    parser.add_argument(
        "-n",
        "--num",
        action="store",
        dest="n_num",
        type=check_positive,
        default=1,
        help="Number of latest years/quarters.",
    )
    parser.add_argument(
        "-q",
        "--quarter",
        action="store_true",
        default=False,
        dest="b_quarter",
        help="Quarter fundamental data flag.",
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if not ns_parser:
            return

        if ns_parser.n_num == 1:
            pd.set_option("display.max_colwidth", None)
        else:
            pd.options.display.max_colwidth = 40

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format="pandas")
        if ns_parser.b_quarter:
            # pylint: disable=unbalanced-tuple-unpacking
            df_fa, _ = fd.get_cash_flow_quarterly(symbol=ticker)
        else:
            # pylint: disable=unbalanced-tuple-unpacking
            df_fa, _ = fd.get_cash_flow_annual(symbol=ticker)

        df_fa = clean_fundamentals_df(df_fa, num=ns_parser.n_num)
        print(df_fa)
        print("")

    except Exception as e:
        print(e)
        print("")
        return
def balance_sheet(other_args: List[str], ticker: str):
    """Alpha Vantage balance sheet

    Parameters
    ----------
    other_args : List[str]
        argparse other args
    ticker : str
        Fundamental analysis ticker symbol
    """

    parser = argparse.ArgumentParser(
        add_help=False,
        prog="balance",
        description="""
            Prints a complete balance sheet statement over time. This can be either quarterly or
            annually. The following fields are expected: Accepted date, Account payables,
            Accumulated other comprehensive income loss, Cash and cash equivalents, Cash and short
            term investments, Common stock, Deferred revenue, Deferred revenue non current,
            Deferred tax liabilities non current, Filling date, Final link, Goodwill,
            Goodwill and intangible assets, Intangible assets, Inventory, Link, Long term debt,
            Long term investments, Net debt, Net receivables, Other assets, Other current assets,
            Other current liabilities, Other liabilities, Other non current assets, Other non
            current liabilities, Othertotal stockholders equity, Period, Property plant equipment
            net, Retained earnings, Short term debt, Short term investments, Tax assets, Tax
            payables, Total assets, Total current assets, Total current liabilities, Total debt,
            Total investments, Total liabilities, Total liabilities and stockholders equity, Total
            non current assets, Total non current liabilities, and Total stockholders equity.
            [Source: Alpha Vantage]
        """,
    )

    parser.add_argument(
        "-n",
        "--num",
        action="store",
        dest="n_num",
        type=check_positive,
        default=1,
        help="Number of latest years/quarters.",
    )
    parser.add_argument(
        "-q",
        "--quarter",
        action="store_true",
        default=False,
        dest="b_quarter",
        help="Quarter fundamental data flag.",
    )

    try:
        (ns_parser, l_unknown_args) = parser.parse_known_args(other_args)

        if l_unknown_args:
            print(
                f"The following args couldn't be interpreted: {l_unknown_args}\n"
            )
            return

        if ns_parser.n_num == 1:
            pd.set_option("display.max_colwidth", None)
        else:
            pd.options.display.max_colwidth = 40

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format="pandas")
        if ns_parser.b_quarter:
            # pylint: disable=unbalanced-tuple-unpacking
            df_fa, _ = fd.get_balance_sheet_quarterly(symbol=ticker)
        else:
            # pylint: disable=unbalanced-tuple-unpacking
            df_fa, _ = fd.get_balance_sheet_annual(symbol=ticker)

        df_fa = clean_fundamentals_df(df_fa, num=ns_parser.n_num)
        print(df_fa)
        print("")

    except Exception as e:
        print(e)
        print("")
        return
示例#20
0
def overview_all(request, symbol):

    if request.method == 'GET':
        data = FundamentalData(key='I7WB8M63PERU90OY', output_format='pandas')
        company_overview, meta_data = data.get_company_overview(symbol=symbol)

        num_cols = [
            'EBITDA', 'Beta', 'PERatio', 'PEGRatio', 'BookValue',
            'DividendPerShare', 'DividendYield', 'Beta', 'EPS'
        ]
        for col in num_cols:
            if company_overview[col].values[0] == 'None':
                company_overview[col] = 0.0
            else:
                pass

        date_cols = ['DividendDate', 'ExDividendDate', 'LastSplitDate']

        for col in date_cols:
            if company_overview[col].values[0] == 'None':
                company_overview[col] = '1901-01-01'
            else:
                pass

        co = Overview(
            tid=datetime.now().strftime('%Y-%m-%d') + '_' + symbol,
            symbol=company_overview['Symbol'].values[0],
            asset_type=company_overview['AssetType'].values[0],
            name=company_overview['Name'].values[0],
            exchange=company_overview['Exchange'].values[0],
            currency=company_overview['Currency'].values[0],
            sector=company_overview['Sector'].values[0],
            industry=company_overview['Industry'].values[0],
            full_time_employees=company_overview['FullTimeEmployees'].
            values[0],
            fiscal_year_end=company_overview['FiscalYearEnd'].values[0],
            latest_quarter=company_overview['LatestQuarter'].values[0],
            market_capitalization=company_overview['MarketCapitalization'].
            values[0],
            ebitda=company_overview['EBITDA'].values[0],
            pe_ratio=company_overview['PERatio'].values[0],
            peg_ratio=company_overview['PEGRatio'].values[0],
            book_value=company_overview['BookValue'].values[0],
            dividend_per_share=company_overview['DividendPerShare'].values[0],
            dividend_yield=company_overview['DividendYield'].values[0],
            eps=company_overview['EPS'].values[0],
            revenue_per_share_ttm=company_overview['RevenuePerShareTTM'].
            values[0],
            profit_margin=company_overview['ProfitMargin'].values[0],
            operating_margin_ttm=company_overview['OperatingMarginTTM'].
            values[0],
            return_on_assets_ttm=company_overview['ReturnOnAssetsTTM'].
            values[0],
            return_on_equity_ttm=company_overview['ReturnOnEquityTTM'].
            values[0],
            revenue_ttm=company_overview['RevenueTTM'].values[0],
            gross_profit_ttm=company_overview['GrossProfitTTM'].values[0],
            diluted_eps_ttm=company_overview['DilutedEPSTTM'].values[0],
            quarterly_earning_growth_yoy=company_overview[
                'QuarterlyEarningsGrowthYOY'].values[0],
            quarterly_revenue_growth_yoy=company_overview[
                'QuarterlyRevenueGrowthYOY'].values[0],
            analyst_target_price=company_overview['AnalystTargetPrice'].
            values[0],
            trailing_pe=company_overview['TrailingPE'].values[0],
            forward_pe=company_overview['ForwardPE'].values[0],
            price_to_sales_ratio_ttm=company_overview['PriceToSalesRatioTTM'].
            values[0],
            price_to_book_ratio=company_overview['PriceToBookRatio'].values[0],
            ev_to_revenue=company_overview['EVToRevenue'].values[0],
            ev_to_ebitda=company_overview['EVToEBITDA'].values[0],
            beta=company_overview['Beta'].values[0],
            p52_week_high=company_overview['52WeekHigh'].values[0],
            p52_week_low=company_overview['52WeekLow'].values[0],
            p50_day_moving_average=company_overview['50DayMovingAverage'].
            values[0],
            p200_day_moving_average=company_overview['200DayMovingAverage'].
            values[0],
            shares_outstanding=company_overview['SharesOutstanding'].values[0],
            short_ratio=company_overview['ShortRatio'].values[0],
            short_percent_outstanding=company_overview[
                'ShortPercentOutstanding'].values[0],
            short_percent_float=company_overview['ShortPercentFloat'].
            values[0],
            percent_insiders=company_overview['PercentInsiders'].values[0],
            percent_institutions=company_overview['PercentInstitutions'].
            values[0],
            forword_annual_dividend_rate=company_overview[
                'ForwardAnnualDividendRate'].values[0],
            forword_annual_dividend_yield=company_overview[
                'ForwardAnnualDividendYield'].values[0],
            payout_ratio=company_overview['PayoutRatio'].values[0],
            dividend_date=company_overview['DividendDate'].values[0],
            exdividend_date=company_overview['ExDividendDate'].values[0],
            last_split_factor=company_overview['LastSplitFactor'].values[0],
            last_split_date=company_overview['LastSplitDate'].values[0])

        try:
            co.save()
        except:
            pass

        start_date = request.GET.get('from_')

        end_date = request.GET.get('end_')

        if end_date is None:
            end_date = datetime.now().strftime('%Y-%m-%d')

        dates = pd.bdate_range(start=start_date, end=end_date)

        with RESTClient(auth_key='u8arVdihlX_6p_pRuvRUwa94YmI4Zrny') as client:

            for date in dates:
                try:
                    rep = client.stocks_equities_daily_open_close(
                        symbol=symbol, date=date.strftime('%Y-%m-%d'))
                    if rep.symbol != '':
                        openAndClose = OpenClose(
                            tid=rep.from_ + '_' + rep.symbol,
                            symbol=symbol,
                            tdate=datetime.strptime(rep.from_, '%Y-%m-%d'),
                            open=rep.open,
                            high=rep.high,
                            low=rep.low,
                            close=rep.close,
                            afterHours=rep.after_hours,
                            preMarket=rep.preMarket,
                            volumne=rep.volume)
                        try:
                            openAndClose.save()
                        except:
                            pass
                    else:
                        pass
                except:
                    pass

    return JsonResponse({'message': 'save successflly'},
                        status=status.HTTP_200_OK)
示例#21
0
def balance_sheet(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        prog='balance',
        description=
        """Prints a complete balance sheet statement over time. This can be 
                                     either quarterly or annually. The following fields are expected: Accepted date, 
                                     Account payables, Accumulated other comprehensive income loss, Cash and cash 
                                     equivalents, Cash and short term investments, Common stock, Deferred revenue, 
                                     Deferred revenue non current, Deferred tax liabilities non current, Filling date, 
                                     Final link, Goodwill, Goodwill and intangible assets, Intangible assets, Inventory, 
                                     Link, Long term debt, Long term investments, Net debt, Net receivables, Other assets, 
                                     Other current assets, Other current liabilities, Other liabilities, Other non current 
                                     assets, Other non current liabilities, Othertotal stockholders equity, Period, Property 
                                     plant equipment net, Retained earnings, Short term debt, Short term investments, Tax assets, 
                                     Tax payables, Total assets, Total current assets, Total current liabilities, Total debt, 
                                     Total investments, Total liabilities, Total liabilities and stockholders equity, Total 
                                     non current assets, Total non current liabilities, and Total stockholders equity. 
                                     [Source: Alpha Vantage]""")

    parser.add_argument('-n',
                        "--num",
                        action="store",
                        dest="n_num",
                        type=check_positive,
                        default=1,
                        help='Number of latest years/quarters.')
    parser.add_argument('-q',
                        "--quarter",
                        action="store_true",
                        default=False,
                        dest="b_quarter",
                        help='Quarter fundamental data flag.')

    try:
        (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

        if l_unknown_args:
            print(
                f"The following args couldn't be interpreted: {l_unknown_args}\n"
            )
            return

        if ns_parser.n_num == 1:
            pd.set_option('display.max_colwidth', -1)
        else:
            pd.options.display.max_colwidth = 40

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format='pandas')
        if ns_parser.b_quarter:
            df_fa, d_fd_metadata = fd.get_balance_sheet_quarterly(
                symbol=s_ticker)
        else:
            df_fa, d_fd_metadata = fd.get_balance_sheet_annual(symbol=s_ticker)

        df_fa = df_fa.set_index('fiscalDateEnding')
        df_fa = df_fa.head(n=ns_parser.n_num).T
        df_fa = df_fa.mask(
            df_fa.astype(object).eq(ns_parser.n_num * ['None'])).dropna()
        df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num *
                                                   ['0'])).dropna()
        df_fa = df_fa.applymap(lambda x: long_number_format(x))
        df_fa.index = [
            ''.join(' ' + char if char.isupper() else char.strip()
                    for char in idx).strip() for idx in df_fa.index.tolist()
        ]
        df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
        df_fa.columns.name = "Fiscal Date Ending"
        print(df_fa)

        print("")

    except:
        print("")
        return
示例#22
0
def overview_init(request):

    if request.method == 'GET':

        symbol = request.GET.get('symbol')

        data = FundamentalData(key='I7WB8M63PERU90OY', output_format='pandas')
        company_overview, meta_data = data.get_company_overview(symbol=symbol)

        num_cols = [
            'EBITDA', 'Beta', 'PERatio', 'PEGRatio', 'BookValue',
            'DividendPerShare', 'DividendYield', 'Beta', 'EPS'
        ]
        for col in num_cols:
            if company_overview[col].values[0] == 'None':
                company_overview[col] = 0.0
            else:
                pass

        date_cols = ['DividendDate', 'ExDividendDate', 'LastSplitDate']

        for col in date_cols:
            if company_overview[col].values[0] == 'None':
                company_overview[col] = '1901-01-01'
            else:
                pass

        co = Overview(
            tid=datetime.now().strftime('%Y-%m-%d') + '_' + symbol,
            symbol=company_overview['Symbol'].values[0],
            asset_type=company_overview['AssetType'].values[0],
            name=company_overview['Name'].values[0],
            exchange=company_overview['Exchange'].values[0],
            currency=company_overview['Currency'].values[0],
            sector=company_overview['Sector'].values[0],
            industry=company_overview['Industry'].values[0],
            full_time_employees=company_overview['FullTimeEmployees'].
            values[0],
            fiscal_year_end=company_overview['FiscalYearEnd'].values[0],
            latest_quarter=company_overview['LatestQuarter'].values[0],
            market_capitalization=company_overview['MarketCapitalization'].
            values[0],
            ebitda=company_overview['EBITDA'].values[0],
            pe_ratio=company_overview['PERatio'].values[0],
            peg_ratio=company_overview['PEGRatio'].values[0],
            book_value=company_overview['BookValue'].values[0],
            dividend_per_share=company_overview['DividendPerShare'].values[0],
            dividend_yield=company_overview['DividendYield'].values[0],
            eps=company_overview['EPS'].values[0],
            revenue_per_share_ttm=company_overview['RevenuePerShareTTM'].
            values[0],
            profit_margin=company_overview['ProfitMargin'].values[0],
            operating_margin_ttm=company_overview['OperatingMarginTTM'].
            values[0],
            return_on_assets_ttm=company_overview['ReturnOnAssetsTTM'].
            values[0],
            return_on_equity_ttm=company_overview['ReturnOnEquityTTM'].
            values[0],
            revenue_ttm=company_overview['RevenueTTM'].values[0],
            gross_profit_ttm=company_overview['GrossProfitTTM'].values[0],
            diluted_eps_ttm=company_overview['DilutedEPSTTM'].values[0],
            quarterly_earning_growth_yoy=company_overview[
                'QuarterlyEarningsGrowthYOY'].values[0],
            quarterly_revenue_growth_yoy=company_overview[
                'QuarterlyRevenueGrowthYOY'].values[0],
            analyst_target_price=company_overview['AnalystTargetPrice'].
            values[0],
            trailing_pe=company_overview['TrailingPE'].values[0],
            forward_pe=company_overview['ForwardPE'].values[0],
            price_to_sales_ratio_ttm=company_overview['PriceToSalesRatioTTM'].
            values[0],
            price_to_book_ratio=company_overview['PriceToBookRatio'].values[0],
            ev_to_revenue=company_overview['EVToRevenue'].values[0],
            ev_to_ebitda=company_overview['EVToEBITDA'].values[0],
            beta=company_overview['Beta'].values[0],
            p52_week_high=company_overview['52WeekHigh'].values[0],
            p52_week_low=company_overview['52WeekLow'].values[0],
            p50_day_moving_average=company_overview['50DayMovingAverage'].
            values[0],
            p200_day_moving_average=company_overview['200DayMovingAverage'].
            values[0],
            shares_outstanding=company_overview['SharesOutstanding'].values[0],
            short_ratio=company_overview['ShortRatio'].values[0],
            short_percent_outstanding=company_overview[
                'ShortPercentOutstanding'].values[0],
            short_percent_float=company_overview['ShortPercentFloat'].
            values[0],
            percent_insiders=company_overview['PercentInsiders'].values[0],
            percent_institutions=company_overview['PercentInstitutions'].
            values[0],
            forword_annual_dividend_rate=company_overview[
                'ForwardAnnualDividendRate'].values[0],
            forword_annual_dividend_yield=company_overview[
                'ForwardAnnualDividendYield'].values[0],
            payout_ratio=company_overview['PayoutRatio'].values[0],
            dividend_date=company_overview['DividendDate'].values[0],
            exdividend_date=company_overview['ExDividendDate'].values[0],
            last_split_factor=company_overview['LastSplitFactor'].values[0],
            last_split_date=company_overview['LastSplitDate'].values[0])

        co.save()

        return JsonResponse({'message': 'save successflly'},
                            status=status.HTTP_200_OK)
示例#23
0
def get_fraud_ratios(
    ticker: str,
) -> Tuple[Optional[Dict[str, float]], Optional[float], Optional[float]]:
    """Get fraud ratios based on fundamentals

    Parameters
    ----------
    ticker : str
        Stock ticker

    Returns
    -------
    Dict[float]:
        Dictionary of fraud metrics
    float:
        Z score for fraud metrics
    """

    try:
        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format="pandas")
        # pylint: disable=unbalanced-tuple-unpacking
        df_cf, _ = fd.get_cash_flow_annual(symbol=ticker)
        df_bs, _ = fd.get_balance_sheet_annual(symbol=ticker)
        df_is, _ = fd.get_income_statement_annual(symbol=ticker)

    except Exception as e:
        console.print(e)
        return None, None, None

    # pylint: disable=no-member
    df_cf = df_cf.set_index("fiscalDateEnding").iloc[:2]
    df_bs = df_bs.set_index("fiscalDateEnding").iloc[:2]
    df_is = df_is.set_index("fiscalDateEnding").iloc[:2]

    ar = df_values(df_bs, "currentNetReceivables")
    sales = df_values(df_is, "totalRevenue")
    cogs = df_values(df_is, "costofGoodsAndServicesSold")
    ni = df_values(df_is, "netIncome")
    ca = df_values(df_bs, "totalCurrentAssets")
    cl = df_values(df_bs, "totalCurrentLiabilities")
    ppe = df_values(df_bs, "propertyPlantEquipment")
    cash = df_values(df_bs, "cashAndCashEquivalentsAtCarryingValue")
    cash_and_sec = df_values(df_bs, "cashAndShortTermInvestments")
    sec = [y - x for (x, y) in zip(cash, cash_and_sec)]
    ta = df_values(df_bs, "totalAssets")
    dep = df_values(df_bs, "accumulatedDepreciationAmortizationPPE")
    sga = df_values(df_is, "sellingGeneralAndAdministrative")
    tl = df_values(df_bs, "totalLiabilities")
    icfo = df_values(df_is, "netIncomeFromContinuingOperations")
    cfo = df_values(df_cf, "operatingCashflow")

    ratios: Dict = {}
    ratios["DSRI"] = (ar[0] / sales[0]) / (ar[1] / sales[1])
    ratios["GMI"] = ((sales[1] - cogs[1]) / sales[1]) / (
        (sales[0] - cogs[0]) / sales[0])
    ratios["AQI"] = (1 - ((ca[0] + ppe[0] + sec[0]) / ta[0])) / (1 - (
        (ca[1] + ppe[1] + sec[1]) / ta[1]))
    ratios["SGI"] = sales[0] / sales[1]
    ratios["DEPI"] = (dep[1] / (ppe[1] + dep[1])) / (dep[0] /
                                                     (ppe[0] + dep[0]))
    ratios["SGAI"] = (sga[0] / sales[0]) / (sga[1] / sales[1])
    ratios["LVGI"] = (tl[0] / ta[0]) / (tl[1] / ta[1])
    ratios["TATA"] = (icfo[0] - cfo[0]) / ta[0]
    ratios["MSCORE"] = (-4.84 + (0.92 * ratios["DSRI"]) +
                        (0.58 * ratios["GMI"]) + (0.404 * ratios["AQI"]) +
                        (0.892 * ratios["SGI"]) + (0.115 * ratios["DEPI"] -
                                                   (0.172 * ratios["SGAI"])) +
                        (4.679 * ratios["TATA"]) - (0.327 * ratios["LVGI"]))

    zscore = (-4.336 - (4.513 * (ni[0] / ta[0])) + (5.679 * (tl[0] / ta[0])) +
              (0.004 * (ca[0] / cl[0])))
    v1 = np.log(ta[0] / 1000)
    v2 = ni[0] / ta[0]
    v3 = cash[0] / cl[0]

    x = ((v1 + 0.85) * v2) - 0.85
    y = 1 + v3

    mckee = x**2 / (x**2 + y**2)

    return ratios, zscore, mckee
示例#24
0
def fraud(other_args: List[str], ticker: str):
    """Fraud indicators for given ticker
    Parameters
    ----------
    other_args : List[str]
        argparse other args
    ticker : str
        Fundamental analysis ticker symbol
    """
    parser = argparse.ArgumentParser(
        add_help=False,
        formatter_class=argparse.RawTextHelpFormatter,
        prog="fraud",
        description=
        ("Mscore:\n------------------------------------------------\n"
         "The Beneish model is a statistical model that uses financial ratios calculated with"
         " accounting data of a specific company in order to check if it is likely (high"
         " probability) that the reported earnings of the company have been manipulated."
         " A score of -5 to -2.22 indicated a low chance of fraud, a score of -2.22 to -1.78"
         " indicates a moderate change of fraud, and a score above -1.78 indicated a high"
         " chance of fraud.[Source: Wikipedia]\n\nDSRI:\nDays Sales in Receivables Index"
         " gauges whether receivables and revenue are out of balance, a large number is"
         " expected to be associated with a higher likelihood that revenues and earnings are"
         " overstated.\n\nGMI:\nGross Margin Index shows if gross margins are deteriorating."
         " Research suggests that firms with worsening gross margin are more likely to engage"
         " in earnings management, therefore there should be a positive correlation between"
         " GMI and probability of earnings management.\n\nAQI:\nAsset Quality Index measures"
         " the proportion of assets where potential benefit is less certain. A positive"
         " relation between AQI and earnings manipulation is expected.\n\nSGI:\nSales Growth"
         " Index shows the amount of growth companies are having. Higher growth companies are"
         " more likely to commit fraud so there should be a positive relation between SGI and"
         " earnings management.\n\nDEPI:\nDepreciation Index is the ratio for the rate of"
         " depreciation. A DEPI greater than 1 shows that the depreciation rate has slowed and"
         " is positively correlated with earnings management.\n\nSGAI:\nSales General and"
         " Administrative Expenses Index measures the change in SG&A over sales. There should"
         " be a positive relationship between SGAI and earnings management.\n\nLVGI:\nLeverage"
         " Index represents change in leverage. A LVGI greater than one indicates a lower"
         " change of fraud.\n\nTATA: \nTotal Accruals to Total Assets is a proxy for the"
         " extent that cash underlies earnigns. A higher number is associated with a higher"
         " likelihood of manipulation.\n\n\n"
         "Zscore:\n------------------------------------------------\n"
         "The Zmijewski Score is a bankruptcy model used to predict a firm's bankruptcy in two"
         " years. The ratio uses in the Zmijewski score were determined by probit analysis ("
         "think of probit as probability unit). In this case, scores less than .5 represent a"
         " higher probability of default. One of the criticisms that Zmijewski made was that"
         " other bankruptcy scoring models oversampled distressed firms and favored situations"
         " with more complete data.[Source: YCharts]"),
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, other_args)

        if not ns_parser:
            return

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format="pandas")
        # pylint: disable=unbalanced-tuple-unpacking
        # pylint: disable=no-member
        df_cf, _ = fd.get_cash_flow_annual(symbol=ticker)
        df_bs, _ = fd.get_balance_sheet_annual(symbol=ticker)
        df_is, _ = fd.get_income_statement_annual(symbol=ticker)
        df_cf = df_cf.set_index("fiscalDateEnding").iloc[:2]
        df_bs = df_bs.set_index("fiscalDateEnding").iloc[:2]
        df_is = df_is.set_index("fiscalDateEnding").iloc[:2]

        ar = df_bs["currentNetReceivables"].apply(lambda x: int(x)).values
        sales = df_is["totalRevenue"].apply(lambda x: int(x)).values
        cogs = df_is["costofGoodsAndServicesSold"].apply(
            lambda x: int(x)).values
        ni = df_is["netIncome"].apply(lambda x: int(x)).values
        ca = df_bs["totalCurrentAssets"].apply(lambda x: int(x)).values
        cl = df_bs["totalCurrentLiabilities"].apply(lambda x: int(x)).values
        ppe = df_bs["propertyPlantEquipment"].apply(lambda x: int(x)).values
        cash = (df_bs["cashAndCashEquivalentsAtCarryingValue"].apply(
            lambda x: int(x)).values)
        cash_and_sec = (df_bs["cashAndShortTermInvestments"].apply(
            lambda x: int(x)).values)
        sec = [y - x for (x, y) in zip(cash, cash_and_sec)]
        ta = df_bs["totalAssets"].apply(lambda x: int(x)).values
        dep = (df_bs["accumulatedDepreciationAmortizationPPE"].apply(
            lambda x: int(x)).values)
        sga = df_is["sellingGeneralAndAdministrative"].apply(
            lambda x: int(x)).values
        tl = df_bs["totalLiabilities"].apply(lambda x: int(x)).values
        icfo = df_is["netIncomeFromContinuingOperations"].apply(
            lambda x: int(x)).values
        cfo = df_cf["operatingCashflow"].apply(lambda x: int(x)).values
        ratios: Dict = {}
        ratios["DSRI"] = (ar[0] / sales[0]) / (ar[1] / sales[1])
        ratios["GMI"] = ((sales[1] - cogs[1]) / sales[1]) / (
            (sales[0] - cogs[0]) / sales[0])
        ratios["AQI"] = (1 - ((ca[0] + ppe[0] + sec[0]) / ta[0])) / (1 - (
            (ca[1] + ppe[1] + sec[1]) / ta[1]))
        ratios["SGI"] = sales[0] / sales[1]
        ratios["DEPI"] = (dep[1] / (ppe[1] + dep[1])) / (dep[0] /
                                                         (ppe[0] + dep[0]))
        ratios["SGAI"] = (sga[0] / sales[0]) / (sga[1] / sales[1])
        ratios["LVGI"] = (tl[0] / ta[0]) / (tl[1] / ta[1])
        ratios["TATA"] = (icfo[0] - cfo[0]) / ta[0]
        ratios["MSCORE"] = (-4.84 + (0.92 * ratios["DSRI"]) +
                            (0.58 * ratios["GMI"]) + (0.404 * ratios["AQI"]) +
                            (0.892 * ratios["SGI"]) +
                            (0.115 * ratios["DEPI"] -
                             (0.172 * ratios["SGAI"])) +
                            (4.679 * ratios["TATA"]) -
                            (0.327 * ratios["LVGI"]))

        zscore = (-4.336 - (4.513 * (ni[0] / ta[0])) +
                  (5.679 * (tl[0] / ta[0])) + (0.004 * (ca[0] / cl[0])))

        if ratios["MSCORE"] > -1.78:
            chanceM = "high"
        elif ratios["MSCORE"] > -2.22:
            chanceM = "moderate"
        else:
            chanceM = "low"

        if zscore < 0.5:
            chanceZ = "high"
        else:
            chanceZ = "low"

        print("Mscore Sub Stats:")
        for rkey, value in ratios.items():
            if rkey != "MSCORE":
                print("  ", f"{rkey} : {value:.2f}")

        print(
            "\n" + "MSCORE: ",
            f"{ratios['MSCORE']:.2f} ({chanceM} chance of fraud)",
        )

        print("ZSCORE: ", f"{zscore:.2f} ({chanceZ} chance of bankruptcy)",
              "\n")

    except Exception as e:
        print(e, "\n")
示例#25
0
def fundamentalData(API_key, ticker):
  from alpha_vantage.fundamentaldata import FundamentalData
  import matplotlib.pyplot as plt

  fd=FundamentalData(key=API_key, output_format='pandas')
  option=input('1. Company Overview\n2. Earnings\n3. Income Statement\n4. Balance Sheet\n5. Cash Flow\n6. Listing Status\n7. Earnings Calendar\n8. IPO calandar\n').lower()
  
  if option=='company overview' or option=='1':
    data=fd.get_company_overview(symbol=ticker)[0]
    return data

  elif option=='earnings' or option=='2':
    data=fd.get_earnings(symbol=ticker)
    return data

  elif option=='income statement' or option=='3':
    period=input("1. Annual\n2. Quaterly\n").lower()
    if period=='annual' or period=='1':
      data=fd.get_income_statement_annual(symbol=ticker)[0].T
      return data
    elif period=='quaterly' or period=='2':
      data=fd.get_income_statement_quaterly(symbol=ticker)[0].T
      return data
    else:
      print("No data available")

  elif option=='balance sheet' or option=='4':
    period=input("1. Annual\n2. Quaterly\n").lower()
    if period=='annual' or period=='1':
      data=fd.get_balance_sheet_annual(symbol=ticker)[0].T
      return data
    elif period=='quaterly' or period=='2':
      data=fd.get_balance_sheet_quaterly(symbol=ticker)[0].T
      return data
    else:
      print("No data available")

  elif option=='cash flow' or option=='5':
    period=input("1. Annual\n2. Quaterly\n").lower()
    if period=='annual' or period=='1':
      data=fd.get_cash_flow_annual(symbol=ticker)[0].T
      return data
    elif period=='quaterly' or period=='2':
      data=fd.get_cash_flow_quaterly(symbol=ticker)[0].T
      return data
    else:
      print("No data available")

  elif option=='listing status' or option=='6':
    data=fd.get_listing_status()
    return data

  elif option=='earnings calendar' or option=='7':
    data=fd.get_earnings_calendar()

  elif option=='ipo calendar' or option=='8':
    data=fd.get_ipo_calendar()

  else:
    print("CANNOT RECOGNIZE")
示例#26
0
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.fundamentaldata import FundamentalData

# serial key for alpha vantage
s_key = 'S2WB1VTMRBDU2XV3'

# alpha vantage time series data and fundamental data as a pandas object
time_series = TimeSeries(key=s_key, output_format = 'pandas')
fund_data = FundamentalData(key = s_key, output_format = 'pandas')

# EXAMPLE: printing ALL data points for Apple (AAPL)
aapl_time_series = time_series.get_daily_adjusted('AAPL', outputsize='full')
#print(aapl_time_series)

# EXAMPLE: printing Apple (AAPL) annual income statements
aapl_income_statements = fund_data.get_income_statement_annual('AAPL')
#print(aapl_income_statements)

# sec data imported from the CSV file
sec_data = pd.read_csv('cik_ticker.csv', sep = '|')

# filtered to only top 100 (alphabetical) NYSE companies
t100_nyse = sec_data[sec_data["Exchange"] == "NYSE"].head(100)

# SIC codes are actually already present in the CSV, we can filter by SIC code
# For example, 7389 is for business services
t100_nyse_business_services_sector = t100_nyse[t100_nyse["SIC"] == 7389]
#print(t100_nyse_business_services_sector)

# Binding SIC values to NAICS values where there exists a valid conversion
示例#27
0
def income_statement(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        prog='incom',
        description=
        """Prints a complete income statement over time. This can be either quarterly 
                                     or annually. The following fields are expected: Accepted date, Cost and expenses, Cost of 
                                     revenue, Depreciation and amortization, Ebitda, Ebitdaratio, Eps, Epsdiluted, Filling date, 
                                     Final link, General and administrative expenses, Gross profit, Gross profit ratio, Income 
                                     before tax, Income before tax ratio, Income tax expense, Interest expense, Link, Net income, 
                                     Net income ratio, Operating expenses, Operating income, Operating income ratio, Other expenses, 
                                     Period, Research and development expenses, Revenue, Selling and marketing expenses, Total other 
                                     income expenses net, Weighted average shs out, Weighted average shs out dil [Source: Alpha Vantage]"""
    )

    parser.add_argument('-n',
                        "--num",
                        action="store",
                        dest="n_num",
                        type=check_positive,
                        default=1,
                        help='Number of latest years/quarters.')
    parser.add_argument('-q',
                        "--quarter",
                        action="store_true",
                        default=False,
                        dest="b_quarter",
                        help='Quarter fundamental data flag.')

    try:
        (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

        if l_unknown_args:
            print(
                f"The following args couldn't be interpreted: {l_unknown_args}\n"
            )
            return

        if ns_parser.n_num == 1:
            pd.set_option('display.max_colwidth', -1)
        else:
            pd.options.display.max_colwidth = 40

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format='pandas')
        if ns_parser.b_quarter:
            df_fa, d_fd_metadata = fd.get_income_statement_quarterly(
                symbol=s_ticker)
        else:
            df_fa, d_fd_metadata = fd.get_income_statement_annual(
                symbol=s_ticker)

        df_fa = df_fa.set_index('fiscalDateEnding')
        df_fa = df_fa.head(n=ns_parser.n_num).T
        df_fa = df_fa.mask(
            df_fa.astype(object).eq(ns_parser.n_num * ['None'])).dropna()
        df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num *
                                                   ['0'])).dropna()
        df_fa = df_fa.applymap(lambda x: long_number_format(x))
        df_fa.index = [
            ''.join(' ' + char if char.isupper() else char.strip()
                    for char in idx).strip() for idx in df_fa.index.tolist()
        ]
        df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
        df_fa.columns.name = "Fiscal Date Ending"
        print(df_fa)

        print("")

    except:
        print("")
        return
import json
import sys
import pandas as pd
from alpha_vantage.timeseries import TimeSeries 
from alpha_vantage.fundamentaldata import FundamentalData

# API key - JM
my_api_key = 'VRUL91KKCG09FLXV'

# price action
ts = TimeSeries(my_api_key, output_format="json")
parsePdata = ts.get_daily(sys.argv[1])

#financials 
fd = FundamentalData(my_api_key, output_format="json")
parseFdata = fd.get_company_overview(sys.argv[1])

# writing to the json file
with open(f'financial-reports.json', 'w') as outfile:
    outfile.truncate()
    json.dump(parseFdata, outfile)

with open(f'price-action.json', 'w') as outfile2:
    outfile2.truncate()
    json.dump(parsePdata, outfile2)

示例#29
0
def cash_flow(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        prog='cash',
        description=
        """Prints a complete cash flow statement over time. This can be either 
                                     quarterly or annually. The following fields are expected: Accepted date, Accounts payables, 
                                     Accounts receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, 
                                     Cash at end of period, Change in working capital, Common stock issued, Common stock repurchased, 
                                     Debt repayment, Deferred income tax, Depreciation and amortization, Dividends paid, 
                                     Effect of forex changes on cash, Filling date, Final link, Free cash flow, Inventory, 
                                     Investments in property plant and equipment, Link, Net cash provided by operating activities, 
                                     Net cash used for investing activities, Net cash used provided by financing activities, Net 
                                     change in cash, Net income, Operating cash flow, Other financing activities, Other investing 
                                     activities, Other non cash items, Other working capital, Period, Purchases of investments, 
                                     Sales maturities of investments, Stock based compensation. [Source: Alpha Vantage]"""
    )

    parser.add_argument('-n',
                        "--num",
                        action="store",
                        dest="n_num",
                        type=check_positive,
                        default=1,
                        help='Number of latest years/quarters.')
    parser.add_argument('-q',
                        "--quarter",
                        action="store_true",
                        default=False,
                        dest="b_quarter",
                        help='Quarter fundamental data flag.')

    try:
        (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

        if l_unknown_args:
            print(
                f"The following args couldn't be interpreted: {l_unknown_args}\n"
            )
            return

        if ns_parser.n_num == 1:
            pd.set_option('display.max_colwidth', -1)
        else:
            pd.options.display.max_colwidth = 40

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format='pandas')
        if ns_parser.b_quarter:
            df_fa, d_fd_metadata = fd.get_cash_flow_quarterly(symbol=s_ticker)
        else:
            df_fa, d_fd_metadata = fd.get_cash_flow_annual(symbol=s_ticker)

        df_fa = df_fa.set_index('fiscalDateEnding')
        df_fa = df_fa.head(n=ns_parser.n_num).T
        df_fa = df_fa.mask(
            df_fa.astype(object).eq(ns_parser.n_num * ['None'])).dropna()
        df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num *
                                                   ['0'])).dropna()
        df_fa = df_fa.applymap(lambda x: long_number_format(x))
        df_fa.index = [
            ''.join(' ' + char if char.isupper() else char.strip()
                    for char in idx).strip() for idx in df_fa.index.tolist()
        ]
        df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
        df_fa.columns.name = "Fiscal Date Ending"
        print(df_fa)

        print("")

    except:
        print("")
        return
示例#30
0
def cashflow_init_annual(request):

    if request.method == 'GET':

        symbol = request.GET.get('symbol')

        data = FundamentalData(key='I7WB8M63PERU90OY', output_format='pandas')
        cashflows, vasymbol = data.get_cash_flow_annual(symbol=symbol)

        for fical in cashflows['fiscalDateEnding']:
            cashflow = cashflows[cashflows['fiscalDateEnding'] == fical]

            for col in cashflow.columns:
                if col not in ['fiscalDateEnding', 'reportedCurrency']:
                    if cashflow[col].values[0] == 'None':
                        cashflow[col] = 0.0
                    else:
                        pass
                else:
                    pass

            cash = CashFlow(
                symbol=symbol,
                report_type='annualReport',
                fiscal_date_ending=datetime.strptime(
                    cashflow['fiscalDateEnding'].values[0], '%Y-%m-%d'),
                reported_currency=cashflow['reportedCurrency'].values[0],
                investments=cashflow['investments'].values[0],
                change_in_liabilities=cashflow['changeInLiabilities'].
                values[0],
                cashflow_from_investment=cashflow['cashflowFromInvestment'].
                values[0],
                cashflow_from_financing=cashflow['cashflowFromFinancing'].
                values[0],
                other_cashflow_from_financing=cashflow[
                    'otherCashflowFromFinancing'].values[0],
                change_in_operating_activities=cashflow[
                    'changeInOperatingActivities'].values[0],
                net_income=cashflow['netIncome'].values[0],
                change_in_cash=cashflow['changeInCash'].values[0],
                operating_cashflow=cashflow['operatingCashflow'].values[0],
                other_operating_cashflow=cashflow['otherOperatingCashflow'].
                values[0],
                depreciation=cashflow['depreciation'].values[0],
                dividend_payout=cashflow['dividendPayout'].values[0],
                stock_sale_and_purchase=cashflow['stockSaleAndPurchase'].
                values[0],
                change_in_inventory=cashflow['changeInInventory'].values[0],
                change_in_account_receivables=cashflow[
                    'changeInAccountReceivables'].values[0],
                change_in_net_income=cashflow['changeInNetIncome'].values[0],
                capital_expenditures=cashflow['capitalExpenditures'].values[0],
                change_in_receivables=cashflow['changeInReceivables'].
                values[0],
                change_in_exchange_rate=cashflow['changeInExchangeRate'].
                values[0],
                change_in_cash_and_cash_equivalents=cashflow[
                    'changeInCashAndCashEquivalents'].values[0])

            cash.save()

        return JsonResponse({'message': 'Annualy Data Save successlly'},
                            status=status.HTTP_200_OK)