Home > Software design >  How do you convert a string percent to a float decimal?
How do you convert a string percent to a float decimal?

Time:11-03

How do you convert a string percent to a float decimal? I wrote this code and when I run it I just get back errors like "cannot convert the series to <class 'int'>" and "TypeError: unsupported operand type(s) for /: 'str' and 'int'" the problematic line seems to be "sigma = chain["calls"]['Implied Volatility']" because I think the Implied Volatility is a string and because its a string I can't do mathematical operations with it. here's my code:

from yahoo_fin import options
from yahoo_fin import stock_info as si
import numpy as np
from scipy.stats import norm

stock = input("Enter stock symbol: Ex:QQQ ") #this is the stock ticker
expiry = input("Enter option expiration: Ex:11/05/2021 ") # date of expiry

options.get_options_chain(stock)
chain = options.get_options_chain(stock,expiry)

si.get_live_price(stock)
chain["calls"]

r = .025 #risk free interest rate
S = si.get_live_price(stock) #current price of the underlying stock
K = chain["calls"].Strike #the strike price of the option
t = float(input("time until expiry in days  = ")) #days until expiry
T = t/365 #years until expiry
s = chain["calls"]['Implied Volatility'] 
sigma = chain["calls"]['Implied Volatility'] #the Implied Volatility
print(sigma)

def blackScholes(r, S, K, T, sigma): #using the Black-Scholes formula
    "Calculate BS option price for a call/put"
    d1 = (np.log(S/K) (r sigma**2/2)*T)/(sigma*np.sqrt(T))
    d2 = d1 - sigma*np.sqrt(T)
    try:
            price = S*norm.cdf(d1, 0, 1) - K*np.exp(-r*T)*norm.cdf(d2, 0, 1) 
            #print("Option Delta is: ",norm.cdf(d1, 0, 1))
            return price
    except:
        print("Please confirm all option parameters above!!!")
print("Option Value is: ", round(blackScholes(r, S, K, T, sigma),2))

CodePudding user response:

This code is unreadable or testable as it references variables that haven't even been declared.

However, if you're question is "How do you convert a string percent to a float decimal?" when dealing with a series, you can do this:

import pandas

s = pandas.Series(["2%", "2.0%", ".09999%", "100%"]) // example series
s = s.apply(lambda x: float(x[:-1]) / 100)
print(s)

Or in your case:

chain["calls"]["Implied Volatility"] = chain["calls"]["Implied Volatility"].apply(lambda x: float(x[:-1]) / 100)

This code runs pandas.Series.apply on a series with a function passed in (lambda x: [code] refers to a small unnamed function where x is each value in the Series) that chops off the % sign, converts to a float, and divides by 100.

Hope that helps (first stackoverflow answer).

  • Related