Kurz: Operátor kalkulačky složeného úroku

V tomto kurzu vytvoříte operátor Python UDF pro Návrháře Lakeflow, který vypočítá složený úrok. V tomto příkladu se seznámíte se základy vytváření operátorů, které transformují jednotlivé hodnoty nebo sloupce. Další informace najdete v tématu Uživatelem definované operátory v Návrháři Lakeflow.

Overview

Tento kurz vás provede vytvořením uživatelem definovaného operátora pomocí Python UDF. Operátor vypočítá budoucí hodnotu investice pomocí vzorce složeného úroku, A = P × (1 + r/n)^(n×t)kde:

  • P = jistina (počáteční částka)
  • r = roční úroková sazba (jako desetinná čárka)
  • n = Počet složených období za rok
  • t = Čas v letech

Step 1: Zápis a otestování funkce Python

Nejprve definujte základní Python funkci, která provádí výpočet. Otestujte ji v buňce poznámkového bloku, abyste měli jistotu, že funguje správně.

def compound_amount(principal: float,
                    annual_rate: float,
                    compounds_per_year: int,
                    years: float) -> float:
    """
    Compute compound interest future value.

    A = P * (1 + r/n)^(n*t)

    principal: starting amount (P)
    annual_rate: annual nominal rate as decimal (r), e.g. 0.05
    compounds_per_year: compounding periods per year (n), e.g. 12
    years: time in years (t), can be fractional
    """
    import math
    if principal is None or annual_rate is None or compounds_per_year is None or years is None:
        return None

    if compounds_per_year <= 0:
        raise ValueError("compounds_per_year must be > 0")

    return principal * math.pow(1.0 + annual_rate / compounds_per_year,
                                 compounds_per_year * years)

Funkci můžete otestovat pomocí následujícího kódu:

# $1,000 invested at 5% annual rate, compounded monthly for 10 years
compound_amount(1000, 0.05, 12, 10)
# Expected result: ~1647.01

Krok 2: Vytvoření YAML pro operátor

Konfigurace YAML definuje, jak se operátor zobrazuje v Návrháři Lakeflow. Pro tento operátor:

  • Principál používá widget expression, aby si uživatelé mohli vybrat sloupec ze svých dat.
  • Roční sazba, Počet složení za rok a Roky používají widgety number s výchozími hodnotami a omezeními
  • Operátor má jeden vstupní port, který poskytuje data sloupců pro parametr výrazu.
schema: user-defined-operator-v0.1.0
type: uc-udf
name: Compound Amount
id: finance.compound_amount
version: '1.0.0'
description: >
  Computes the future value of an investment using compound interest.
  Formula: A = P * (1 + r/n)^(n*t)
config:
  type: object
  properties:
    principal:
      type: string
      format: expression
      title: Principal
      examples:
        - 'Select principal column or expression'
      x-ui:
        widget: expression
        port: in
    annual_rate:
      type: number
      title: Annual rate (decimal)
      default: 0.05
      minimum: 0
      examples:
        - 'e.g. 0.05 for 5%'
      x-ui:
        widget: number
    compounds_per_year:
      type: number
      title: Compounds per year
      default: 12
      minimum: 1
      examples:
        - 'e.g. 12 for monthly'
      x-ui:
        widget: number
    years:
      type: number
      title: Years
      default: 10
      minimum: 0
      examples:
        - 'Time in years (t)'
      x-ui:
        widget: number
  required:
    - principal
    - annual_rate
    - compounds_per_year
    - years
  additionalProperties: false
ports:
  input:
    - name: in
      title: Input
  output:
    - name: out
      title: Output

Podrobné informace o všech dostupných vlastnostech, datových typech, widgetech a možnostech najdete v referenční dokumentaci YAML uživatelem definovaného operátora .

Krok 3: Vytvoření funkce Katalogu Unity

Zkombinujte schéma YAML a funkci Python do jednoho příkazu CREATE FUNCTION. Konfigurace YAML probíhá v docstringu na začátku těla funkce.

CREATE OR REPLACE FUNCTION main.my_schema.compound_amount(
    principal DOUBLE,
    annual_rate DOUBLE,
    compounds_per_year INT,
    years FLOAT)
RETURNS DOUBLE
LANGUAGE PYTHON
AS $$
  """
  schema: user-defined-operator-v0.1.0
  type: uc-udf
  name: Compound Amount
  id: finance.compound_amount
  version: "1.0.0"
  description: >
    Computes the future value of an investment using compound interest.
    Formula: A = P * (1 + r/n)^(n*t)
  config:
    type: object
    properties:
      principal:
        type: string
        format: expression
        title: Principal
        examples:
          - "Select principal column or expression"
        x-ui:
          widget: expression
          port: in
      annual_rate:
        type: number
        title: Annual rate (decimal)
        default: 0.05
        minimum: 0
        examples:
          - "e.g. 0.05 for 5%"
        x-ui:
          widget: number
      compounds_per_year:
        type: number
        title: Compounds per year
        default: 12
        minimum: 1
        examples:
          - "e.g. 12 for monthly"
        x-ui:
          widget: number
      years:
        type: number
        title: Years
        default: 10
        minimum: 0
        examples:
          - "Time in years (t)"
        x-ui:
          widget: number
    required:
      - principal
      - annual_rate
      - compounds_per_year
      - years
    additionalProperties: false
  ports:
    input:
      - name: in
        title: Input
    output:
      - name: out
        title: Output
  """

  def compound_amount(principal: float,
                      annual_rate: float,
                      compounds_per_year: int,
                      years: float) -> float:
      import math
      if principal is None or annual_rate is None or compounds_per_year is None or years is None:
          return None

      if compounds_per_year <= 0:
          raise ValueError("compounds_per_year must be > 0")

      return principal * math.pow(1.0 + annual_rate / compounds_per_year,
                                   compounds_per_year * years)

  return compound_amount(principal, annual_rate, compounds_per_year, years)
$$

Krok 4: Testování funkce

Otestujte funkci UC přímo pomocí SQL:

-- Test 1: $1,000 at 5% compounded monthly for 10 years
SELECT main.my_schema.compound_amount(1000, 0.05, 12, 10)
-- Expected: ~1647.01

-- Test 2: $1,000 at 5% compounded annually for 1 year
SELECT main.my_schema.compound_amount(1000, 0.05, 1, 1)
-- Expected: 1050.00

-- Test 3: $1,000 at 15% compounded monthly for 1 year
SELECT main.my_schema.compound_amount(1000, 0.15, 12, 1)
-- Expected: ~1160.75

Krok 5: Registrace operátoru

Přidejte operátor do souboru .user_defined_operators.yaml:

operators:
  - catalog: main
    schema: my_schema
    functionName: compound_amount

Note

Pokud tento soubor definujete ve složce uživatele, zobrazí se vám jenom za vás. Další informace najdete v článku Jak zajistit, aby byl váš operátor dohledatelný.

Krok 6: Nastavení oprávnění

Udělte přístup uživatelům, kteří potřebují používat tento operátor:

GRANT USE SCHEMA ON SCHEMA main.my_schema TO `<user>`;
GRANT EXECUTE ON FUNCTION main.my_schema.compound_amount TO `<user>`;

Použití operátoru v nástroji Lakeflow Designer

Po registraci se operátor zobrazí v Návrháři Lakeflow s následujícími informacemi:

  • Rozevírací seznam pro výběr hlavního sloupce ze vstupních dat
  • Číselné vstupy pro sazbu, frekvenci připisování úroků a počet let (s rozumnými výchozími hodnotami)

Uživatelé můžou tento operátor použít k výpočtu budoucích hodnot pro celé sloupce investičních dat.