首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何应用此函数并在python中的dataframe的新列中分配计算值?

如何应用此函数并在python中的dataframe的新列中分配计算值?
EN

Stack Overflow用户
提问于 2022-05-19 05:48:06
回答 1查看 23关注 0票数 0

我希望计算选项希腊增量值,并在dataframe的新列中分配计算值。这是我的代码below_

代码语言:javascript
复制
#!pip install mibian

import requests
import json
import pandas as pd
import mibian
import time

session = requests.Session() # Create request session object

url1 = "https://www.nseindia.com/option-chain?type=currency"
url = "https://www.nseindia.com/api/option-chain-currency?symbol=USDINR"

headers = {
    "user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 
    (KHTML, like Gecko) Chrome/99.0.4844.74 Mobile Safari/537.36",
    "accept-encoding": "gzip, deflate, br",
    "accept-language": "en-US,en;q=0.9"
    }

request = session.get(url1, headers=headers)
cookies = dict(request.cookies)

response = session.get(url, headers=headers, cookies=cookies).text
data = json.loads(response)

exp_list = data['records']['expiryDates']
# print(exp_list)
exp_date = exp_list[0]
# print("Expiry Date: " +exp_date)

ce = {}
pe = {}
n = 0
m = 0

for i in data['records']['data']:
    if i['expiryDate'] == exp_date:
        try:
            ce[n] = i['CE']
            n = n+1
        except:
            pass
        try:
            pe[m] = i['PE']
            m = n+1
        except:
            pass


intrestRate = 10
daysToExpiry = 1

def call_delta(a, b, c, d, e):
  # BS([underlyingPrice, strikePrice, interestRate, daysToExpiration], volatility=x, 
    callPrice=y, putPrice=z)
  c = mibian.BS([a, b, c, d], volatility=e)
  return c.callDelta

def call_theta(a, b, c, d, e):
  # BS([underlyingPrice, strikePrice, interestRate, daysToExpiration], volatility=x, 
    callPrice=y, putPrice=z)
  c = mibian.BS([a, b, c, d], volatility=e)
  return c.callTheta

def call_vega(a, b, c, d, e):
  # BS([underlyingPrice, strikePrice, interestRate, daysToExpiration], volatility=x, 
    callPrice=y, putPrice=z)
  c = mibian.BS([a, b, c, d], volatility=e)
  return c.vega


ce_df = pd.DataFrame.from_dict(ce).transpose()
ce_df = ce_df.drop(["underlying", "identifier", "openInterest", "changeinOpenInterest", 
"pchangeinOpenInterest", "totalTradedVolume", "change", "pChange", "totalBuyQuantity", 
"totalSellQuantity", "bidQty", "bidprice", "askQty", "askPrice"], axis=1)
ce_df = ce_df.rename(columns = {'strikePrice':'strike', 'expiryDate':'ce_expiryDate', 
'impliedVolatility':'ce_impliedVolatility', 'lastPrice':'ce_lastPrice', 
'underlyingValue':'ce_underlyingValue'})
ce_df["strike"] = ce_df["strike"].astype(float) # Change strike column dataType of ce_df from 
object to float
ce_df["ce_impliedVolatility"] = ce_df["ce_impliedVolatility"].astype(float) # Change 
ce_impliedVolatility column dataType of ce_df from object to float
ce_df["ce_lastPrice"] = ce_df["ce_lastPrice"].astype(float) # Change ce_lastPrice column 
dataType of ce_df from object to float
ce_df["ce_underlyingValue"] = ce_df["ce_underlyingValue"].astype(float) # Change 
ce_underlyingValue column dataType of ce_df from object to float
ce_df['ce_expiryDate'] = pd.to_datetime(ce_df['ce_expiryDate']) # Change dataType of 
ce_expiryDate column into datetime format

ce_df["ce_delta"] = ce_df.apply(call_delta(ce_df["ce_underlyingValue"], ce_df["strike"], 
int(intrestRate), int(daysToExpiry), ce_df["ce_impliedVolatility"]))

print(ce_df.head())
print(ce_df.info())

当我运行这段代码时,它会抛出错误,比如

代码语言:javascript
复制
TypeError: cannot convert the series to <class 'float'>

有人能告诉我,请告诉我如何解决这个问题,并在一个新的数据分配计算值。还有别的办法吗?

EN

回答 1

Stack Overflow用户

发布于 2022-05-19 06:01:32

更改以下代码行,

代码语言:javascript
复制
ce_df["ce_delta"] = ce_df.apply(call_delta(ce_df["ce_underlyingValue"], ce_df["strike"], 
int(intrestRate), int(daysToExpiry), ce_df["ce_impliedVolatility"]))

代码语言:javascript
复制
ce_df["ce_delta"] = ce_df.apply(call_delta, axis=1)

代码语言:javascript
复制
def call_delta(a, b, c, d, e):
  # BS([underlyingPrice, strikePrice, interestRate, daysToExpiration], volatility=x, 
    callPrice=y, putPrice=z)
  c = mibian.BS([a, b, c, d], volatility=e)
  return c.callDelta

代码语言:javascript
复制
def _call_delta(a, b, c, d, e):
  # BS([underlyingPrice, strikePrice, interestRate, daysToExpiration], volatility=x, callPrice=y, putPrice=z)
  c = mibian.BS([a, b, c, d], volatility=e)
  return c.callDelta

def call_delta(row):
  return _call_delta(row['ce_underlyingValue'], row['strike'], int(intrestRate), int(daysToExpiry), row['ce_impliedVolatility'])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72299238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档