Esempio n. 1
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
Esempio n. 2
0
def cashflow_init_quarterly(request):

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

        data = FundamentalData(key='I7WB8M63PERU90OY', output_format='pandas')
        qcashflows, vasymbol = data.get_cash_flow_quarterly(symbol=symbol)

        for fical in qcashflows['fiscalDateEnding']:
            cashflow = qcashflows[qcashflows['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],
                other_cashflow_from_investment=cashflow[
                    'otherCashflowFromInvestment'].values[0],
                net_borrowings=cashflow['netBorrowings'].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': 'Quarterly Data Save successlly'},
                            status=status.HTTP_200_OK)
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
period = input('Period- annual, quarterly : ')
statement = input('Statement- balance sheet, income statement, cash flow : ')
fd = FundamentalData(key,output_format = 'pandas')
if period == 'annual':
    if statement == 'balance sheet':
        state = fd.get_balance_sheet_annual(symbol)[0].T[2:]
        state.columns = list(fd.get_balance_sheet_annual(symbol)[0].T.iloc[0])
    elif statement == 'income statement':
        state = fd.get_income_statement_annual(symbol)[0].T[2:]
        state.columns = list(fd.get_income_statement_annual(symbol)[0].T.iloc[0])
    elif statement == 'cash flow':
        state = fd.get_cash_flow_annual(symbol)[0].T[2:]
        state.columns = list(fd.get_cash_flow_annual(symbol)[0].T.iloc[0])
    else:
        print("wrong input given by the user ")

elif period == 'quarterly':
    if statement == 'balance sheet':
        state = fd.get_balance_sheet_quarterly(symbol)[0].T[2:]
        state.columns = list(fd.get_balance_sheet_quarterly(symbol)[0].T.iloc[0])
    elif statement == 'income statement':
        state = fd.get_income_statement_quarterly(symbol)[0].T[2:]
        state.columns = list(fd.get_income_statement_quarterly(symbol)[0].T.iloc[0])
    elif statement == 'cash flow':
        state = fd.get_cash_flow_quarterly(symbol)[0].T[2:]
        state.columns = list(fd.get_cash_flow_quarterly(symbol)[0].T.iloc[0])
    else:
        print('Wrong Entry')
else:
    print('Wrong Entry')
print(state)