Beispiel #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
Beispiel #2
0
def income_init_quarterly(request):

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

        data = FundamentalData(key='I7WB8M63PERU90OY', output_format='pandas')
        qincomes, vasymbol = data.get_income_statement_quarterly(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': 'Quarterly Data Save successlly'},  status=status.HTTP_200_OK)
Beispiel #3
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)
Beispiel #4
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
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)