Josh
Josh

Reputation: 3311

Python "unsupported operand type (s) for"

I am writing my first program in Python and I was getting an error:

 "TypeError: unsupported operand type (s) for /: 'str' and 'str'

This is what I'm doing:

import sys
import math
import scipy.stats import norm

S_t = sys.argv[1];
K = sys.argv[2];
r = sys.argv[3];
T = sys.argv[4];
sigma_0 = sys.argv[5];

d1 = (math.log(S_t/K) + (r - pow(sigma_0, 2)/2)*T)/(simga_0*math.sqrt(T));
x = norm.cdf(d1);

I'm not sure where my mistakes are. Also, is x = norm.cdf(d1) the best way of calculating the cumulative norm?

Upvotes: 0

Views: 1168

Answers (1)

abarnert
abarnert

Reputation: 365767

The problem is that S_t and K are strings, because command-line arguments are strings.

If you want to convert them to some other type, you have to tell Python how/what to convert. For example:

S_t = float(sys.argv[1])
K = float(sys.argv[2])
r = float(sys.argv[3])
T = float(sys.argv[4])

Meanwhile, it's worth learning to debug this yourself. When you get an error in a long line like that, and you can't tell what part of it's wrong, break it down. If you've got this:

d1 = (math.log(S_t/K) + (r - pow(sigma_0, 2)/2)*T)/(simga_0*math.sqrt(T))

Try breaking it down into

d1a = math.log(S_t/K)
d1b = (r - pow(sigma_0, 2)/2)*T)/(simga_0*math.sqrt(T))
d1 = d1a + d1b

Now, see whether the error is in d1a or d1b. Since it's in d1a, break it up again:

d1a1 = S_t/k
d1a = math.log(d1a1)

And now you can see it's in d1a1. That's much easier to figure out—and, if you still can't figure it out, you can post a much shorter question here:

import sys

S_t = sys.argv[1]
K = sys.argv[2]

d1a1 = S_t/k

Upvotes: 6

Related Questions