Tutorial: operatore del calcolatore degli interessi composti

Importante

Questa funzionalità è in Anteprima Pubblica.

Questa esercitazione illustra come creare un operatore UDF Python per Lakeflow Designer che calcola l'interesse composto. Usare questo esempio per apprendere i concetti fondamentali degli operatori di compilazione che trasformano singoli valori o colonne. Per altre informazioni, vedere Operatori definiti dall'utente in Lakeflow Designer.

Informazioni generali

Questo tutorial ti guida nella creazione di un operatore definito dall'utente tramite una UDF Python. L'operatore calcola il valore futuro di un investimento usando la formula di interesse composta, A = P × (1 + r/n)^(n×t), dove:

  • P = Principal (importo iniziale)
  • r = Tasso di interesse annuale (come decimale)
  • n = Numero di periodi di composto all'anno
  • t = Tempo in anni

P 1: Scrivere e testare la funzione Python

Prima di tutto, definire la funzione di base Python che esegue il calcolo. Testarlo in una cella del notebook per assicurarsi che funzioni correttamente.

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)

È possibile testare la funzione con il codice seguente:

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

Passaggio 2: Creare il file YAML per l'operatore

La configurazione YAML definisce la modalità di visualizzazione dell'operatore in Lakeflow Designer. Per questo operatore:

  • Principal usa un expression widget in modo che gli utenti possano selezionare una colonna dai dati
  • Tasso annuale, Composti all'anno e Anni usano number widget con valori predefiniti e vincoli
  • L'operatore dispone di una porta di ingresso che fornisce i dati relativi alla colonna per il parametro expression
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

Per una guida completa a tutte le proprietà, ai tipi di dati, ai widget e alle opzioni disponibili, vedere il riferimento YAML per gli operatori definiti dall'utente.

Passaggio 3: Creare la funzione Catalogo Unity

Combinare lo schema YAML e la funzione Python in una singola istruzione CREATE FUNCTION. La configurazione YAML viene inserita nella docstring all'inizio del corpo della funzione.

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)
$$

Passaggio 4: Testare la funzione

Testare la funzione UC direttamente con 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

Passaggio 5: Registrare l'operatore

Aggiungi l'operatore nel file .user_defined_operators.yaml:

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

Annotazioni

Se si definisce questo file nella cartella utente, viene visualizzato solo per l'utente. Per altre informazioni, vedere Rendere individuabile l'operatore.

Passaggio 6: Configurare le autorizzazioni

Concedere l'accesso agli utenti che devono usare questo operatore:

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

Utilizzo dell'operatore in Lakeflow Designer

Dopo la registrazione, l'operatore verrà visualizzato in Lakeflow Designer con:

  • Elenco a discesa per selezionare la colonna principale dai dati di input
  • Input numerici per frequenza, frequenza composta e anni (con valori predefiniti sensibili)

Gli utenti possono applicare questo operatore per calcolare i valori futuri per intere colonne di dati di investimento.