教程:复合兴趣计算器运算符

在本教程中,你将为 Lakeflow Designer 创建一个Python UDF 运算符,用于计算复合兴趣。 使用此示例可了解转换单个值或列的生成运算符的基础知识。 若要了解详细信息,请参阅 Lakeflow Designer 中的用户定义的运算符。

概述

本教程逐步讲解如何使用 Python UDF 创建用户定义的运算符。 运算符使用复利公式计算投资的未来值, A = P × (1 + r/n)^(n×t)其中:

  • P = 主体(起始金额)

  • r = 年利率(如十进制)

  • n = 每年复合周期数

  • t = 以年为单位的时间

Requirements

  • 在支持Unity Catalog的工作区中访问Lakeflow Designer。 请参阅 先决条件。

  • 在 main 目录上执行 USE CATALOG,在 main 上执行 CREATE SCHEMA,或者在现有 main.example_output 架构上执行 USE SCHEMA 和 CREATE FUNCTION。 如果要使用不同的目录或模式,就将全文中的 main.example_output 替换掉。 请参阅 Unity Catalog 权限参考。

  • 可运行 Unity Catalog Python UDF 的计算资源。 请参阅 Unity 目录中的 SQL 和Python用户定义的函数(UDF)。

步骤 1:编写和测试Python函数

首先,定义执行计算的核心Python函数。 在笔记本单元格中进行测试,以确保其正确运行。

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)

用示例投资测试函数:1000元,年利率为5%,按月复利,持续10年。 结果应约为 1647.01。

compound_amount(1000, 0.05, 12, 10)

步骤 2:为操作员创建 YAML

YAML 配置定义运算符在 Lakeflow Designer 中的显示方式。 对于此运算符:

  • Principal 使用 expression 组件,以便用户从其数据中选择一列

  • 年利率、每年复利次数和年数使用具有默认值和约束条件的number控件

  • 运算符有一个输入端口,该端口为表达式参数提供列数据

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

关于所有可用的属性、数据类型、控件和选项,请参见 用户自定义操作符 YAML 参考。

步骤 3:创建 Unity 目录函数

将 YAML 架构和Python函数合并为单个 CREATE FUNCTION 语句。 YAML 配置位于函数正文开头的 docstring 中。

该示例在 main.example_output 中创建该函数。 如果没有模式,先创建它:

CREATE SCHEMA IF NOT EXISTS main.example_output
CREATE OR REPLACE FUNCTION main.example_output.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)
$$

步骤 4:测试函数

直接用SQL测试UC函数。 这些查询会检查三种情况:

  • 人民币1,000元,按5%年利率按月复利,10年后约为 1647.01

  • 1000元,按年复利5%,期限1年,回报 1050.00

  • 1000元按15%年利率按月复利,存1年,约可获得 1160.75

SELECT main.example_output.compound_amount(1000, 0.05, 12, 10);
SELECT main.example_output.compound_amount(1000, 0.05, 1, 1);
SELECT main.example_output.compound_amount(1000, 0.15, 12, 1);

步骤 5:注册操作员

将运算符添加到 .user_defined_operators.yaml 文件:

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

注释

如果在用户文件夹中定义此文件,则只会为你显示该文件。 更多信息,请参阅“注册并将您的运算符部署到 Lakeflow Designer”。

步骤 6:设置权限

向需要使用此操作员的用户授予访问权限:

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

步骤 7:在 Lakeflow Designer 中使用运算符

  1. 在可视化数据准备中,打开左侧面板的 运算符 菜单,找到 复合金额 运算符。

  2. 把操作符拖到画布上,然后将一个输入连接到它。

  3. 双击该操作符以打开其配置面板,然后设置其字段。

  4. 选择操作符,在输出面板中预览其结果。

操作员的配置面板包括:

  • 用于从输入数据中选择主体列的下拉列表

  • 利率、复利频率和年限的数字输入框(带有合理的默认值)

用户可以应用此运算符来计算整个投资数据列的未来值。

其他资源