python - 如何在Python中求解阶跃函数?

标签 python scipy

我正在用 Python 编写一个期权交易程序。该程序提出交易,然后确定特定交易可盈利的标的股票的价格点。

我将尝试表述这个问题,以便任何人,无论其选项知识如何,都可以提供解决方案。

示例交易包括购买 n看跌期权和 y来电。 (其中 ny 是整数)。交易成本称为变量 cost_of_trade

如果cost_of_trade < profit_from_trade,则交易是有利可图的


profit_of_trade = profit_from_calls + profit_from_puts

如果股票价格高于到期时看涨期权的执行价格,则:

profit_from_calls = (final_stock_price - calls.strike_price) * y)

其他:

profit_from_calls = 0

--

如果股票价格低于到期时看跌期权的执行价格,则:

profit_from_puts = (-final_stock_price + puts.strike_price) * n)

其他:

profit_from_puts = 0


我需要解方程 cost_of_trade == profit_from_trade 。解这个方程应该给我两个值。 我遇到的根本问题是我不知道如何用Python可以解决的术语来表达方程。 if statement方程式让事情变得困难。

在等式之外创建 if 语句并不是真正的选择。虽然这对于这个简单的示例问题可能有意义,但在实际程序中,有很多不同的交易和不同的交易组合,我必须编写 1000+ if statements ,这不是我想做的事情。

最佳答案

您可以解决大多数可以计算的问题,例如通过二分...:

def bisection(f, a, b, TOL=0.001, NMAX=100):
    """
    Takes a function f, start values [a,b], tolerance value(optional) TOL and
    max number of iterations(optional) NMAX and returns the root of the equation
    using the bisection method.
    """
    n=1
    while n<=NMAX:
        c = (a+b)/2.0
        # decomment to learn more about the process
        # print "a=%s\tb=%s\tc=%s\tf(c)=%s"%(a,b,c,f(c))
        if f(c)==0 or (b-a)/2.0 < TOL:
            return c
        else:
            n = n+1
            if f(c)*f(a) > 0:
                a=c
            else:
                b=c
    return None

def solve(y, call_strike, call_premium, n, put_strike, put_premium):
    cost = y * call_premium + n * put_premium
    def net(fp):
        call_profit = max(fp-call_strike, 0)
        put_profit = max(put_strike-fp, 0)
        tot_profit = call_profit * y + put_profit * n
        return tot_profit - cost
    return bisection(net, 0, 2 * max(call_strike, put_strike))

if __name__ == '__main__':
    # an example...:
    print solve(12, 20.0, 3.0, 15, 25.0, 2.0)

参见例如https://gist.github.com/swvist/3775568用于二分的原始代码和任意方程数值解的其他方法。

关于python - 如何在Python中求解阶跃函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27583021/

相关文章:

python - 如何向终端应用程序编写透明包装器?

python - pandas如何通过一行生成多行

python - numba 类型与 nd 过滤器匹配

python - 如何使用 scipy.optimize.minimize 进行最大似然回归

python - python 中 matlab (.mat) 文件 -v7 的部分加载

python - 将应用程序或脚本转换为 shell 命令

python - wxPython textCtrl 静默 AppendText

Python scipy chisquare 返回与 R chisquare 不同的值

python - 在 numpy/matplotlib 中以图形和数字方式求解线性二次方程组?

python - collective.googleanalytics 报告中的自定义维度