LibreOffice Calc Python UDF的基本包装器

2024-09-27 00:16:51 发布

您现在位置:Python中文网/ 问答频道 /正文

基本包装器调用是如何形成的,以使用非整数电子表格范围运行LibreOffice Calc Python用户定义函数

我不清楚如何正确地为valuesexcel_date数组声明函数,这两个数组都是实数数组,在我理解的基本术语中都是Variant

我遵循了Calling a python function from within LibreCalc,范围可以作为整数参数传递,而不需要定义它们,但它们是实值。这两个数组都是一维数组,因此多维数组问题不适用于How can I call a Python macro in a cell formula in OpenOffice.Org Calc?中讨论的问题

基本代码是:

Function xnpv_helper(rate as Double, values() as Variant, excel_date() as Variant) as Double
    Dim scriptPro As Object, myScript As Object
    scriptPro = ThisComponent.getScriptProvider()
    myScript = scriptPro.getScript("vnd.sun.star.script:MyPythonLibrary/Develop/math.py$xnpv_helper?language=Python&location=user")
    xnpv_helper = myScript.invoke(Array(rate, values, excel_date), Array(), Array() )
end function

电子表格数据:

Date    Amount  Rate    xnpv
31/12/19    100 -0.1    
31/12/20    -110

xnpv_helper在底部。实际的python脚本基于来自financial python library that has xirr and xnpv function?https://github.com/tarioch/xirr

# Demo will run in python REPL - uncomment last line
import scipy.optimize

DAYS_PER_YEAR = 365.0

def xnpv(valuesPerDate, rate):
    '''Calculate the irregular net present value.

    >>> from datetime import date
    >>> valuesPerDate = {date(2019, 12, 31): -100, date(2020, 12, 31): 110}
    >>> xnpv(valuesPerDate, -0.10)
    22.257507852701295
    '''
    if rate == -1.0:
        return float('inf')
    t0 = min(valuesPerDate.keys())
    if rate <= -1.0:
        return sum([-abs(vi) / (-1.0 - rate)**((ti - t0).days / DAYS_PER_YEAR) for ti, vi in valuesPerDate.items()])
    return sum([vi / (1.0 + rate)**((ti - t0).days / DAYS_PER_YEAR) for ti, vi in valuesPerDate.items()])


from datetime import date
def excel2date(excel_date):
    return date.fromordinal(date(1900, 1, 1).toordinal() + int(excel_date) - 2)

def xnpv_helper(rate, values, excel_date):
    dates = [excel2date(i) for i in excel_date]
    valuesPerDate = dict(zip(dates, values))
    return xnpv(valuesPerDate, rate)

# valuesPerDate = {date(2019, 12, 31): -100, date(2020, 12, 31): 110}
# xnpv_helper(-0.10, [-100, 110], [43830.0, 44196.0])

Tags: inhelperdatereturnrateastifunction

热门问题