为每一列/行生成一个遵循数学函数的数据框 [英] Generate a Dataframe that follow a mathematical function for each column / row

查看:37
本文介绍了为每一列/行生成一个遵循数学函数的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从头开始创建/生成 Pandas DataFrame,这样每条记录都遵循特定的数学函数?

Is there a way to create/generate a Pandas DataFrame from scratch, such that each record follows a specific mathematical function?

背景:在金融数学中,非常基本的金融衍生品(例如看涨期权和看跌期权)具有封闭形式的定价公式(例如 Black Scholes).这些定价公式可以称为随机函数(因为它们涉及随机项)

Background: In Financial Mathematics, very basic financial-derivatives (e.g. calls and puts) have closed-form pricing formulas (e.g. Black Scholes). These pricing formulas can be called stochastic functions (because they involve a random term)

我正在尝试创建股票价格的蒙特卡罗模拟(以及随后基于股票价格的期权收益和价格).比如说,我需要 1000 条路径(行)和 100 个时间步长(列).我想启动"一个 1000 x 100 并遵循随机方程的数据帧.

I'm trying to create a Monte Carlo simulation of a stock price (and subseuqently an option payoff and price based on the stock price). I need, say, 1000 paths (rows) and 100 time-steps (columns). I want to "initiate" a dataframe that is 1000 by 100 and follows a stochastic equation.

# Psuedo-code
MonteCarloDF = DataFrame(rows=1000, columns=100, customFunc=TRUE,
        appliedBy='by column', 
        FUNC={s0=321; 
              s_i=prev*exp(r-q*sqrt(sigma))*T + 
                 (etc)*NormDist(rnd())*sqr(deltaT)}
        )

每行的第 0 列是 321,随后的每一列将根据上面的 FUNC 计算出来.

Column 0 in every row would be 321, and each subsequent column would be figured out based on the FUNC above.

这是在 VBA 中完成的类似操作的示例

This is an example of something similar done in VBA

Function MonteCarlo_Vanilla_call(S, K, r, q, vol, T, N)

sum = 0
payoff = 0

For i = 1 To N
 S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd()))
 payoff = Application.Max(S_T - K, 0)
 sum = sum + payoff
Next i

MonteCarlo_Vanilla_call = Exp(-r * T) * sum / N

End Function

每一个传入的变量都是一个常量.就我而言,我希望同一行中的每一列都与 VBA 代码中的 S_T 一样.这真的是唯一重要的事情.我想应用一个函数,如 S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd())).每个 S_T 是同一行中的下一列.有 N 列进行一次模拟.例如,我将进行 1000 次模拟.

Every passed in variable is a constant. In my case, I want each next column in the same row to be just like S_T in the VBA code. That's really the only like that matters. I want to apply a function like S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd())) . Each S_T is the next column in the same row. There's N columns making one simulation. I will have, for example, 1000 simulations.

321     | 322.125 | 323.277 | ... | column 100 value
321     | 320.704 | 319.839 | ... | column 100 value
321     | 321.471 | 318.456 | ... | column 100 value
...
row 1000| etc     | etc     | ... | value (1000,100)

推荐答案

IIUC,您可以创建自己的函数来生成DataFrame.在函数中使用 .iloc[:, -1] 使用最后创建的列.

IIUC, you could create your own function to generate a DataFrame. Within the function iterate using .iloc[:, -1] to use the last created column.

我们还将使用 numpy.random.randn 生成一组正态分布的随机值.

We'll also use numpy.random.randn to generate an array of normally distributed random values.

您可能需要调整变量的默认值,但想法如下:

You may need to adjust the default values of your variables, but the idea would be something like:

import pandas as pd
import numpy as np
from math import exp, sqrt

def monte_carlo_df(nrows,
                   ncols,
                   col_1_val,
                   r=0.03,
                   q=0.5,
                   sigma=0.002,
                   T=1.0002,
                   deltaT=0.002):
    """Returns stochastic monte carlo DataFrame"""

    # Create first column
    df = pd.DataFrame({'s0': [col_1_val] * nrows})

    # Create subsequent columns
    for i in range(1, ncols):
        df[f's{i}'] = (df.iloc[:, -1] * exp(r - q * sqrt(sigma)) * T
                       + (np.random.randn(nrows) * sqrt(deltaT)))
    return df

使用示例

df = monte_carlo_df(nrows=1000, ncols=100, col_1_val=321)

这篇关于为每一列/行生成一个遵循数学函数的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆