0

I'm a math guy trying to self teach myself Python. Through some pointers here, I have this program working (without a class implementation) but being a math guy, my code is ugly. I'd like some help using classes to make it look cleaner.

But I think I'm confused on how to make one class flow into another. Or at the very least functions be put into other functions.

Anyway, I've read a lot of material and have this part working well:

#-----------------------------------------------
# Plain vanilla european option pricer 
# by DudeWah
#-----------------------------------------------

#import libraries
import time as walltime
from random import gauss
from math import exp, sqrt

#-----------------------------------------------
#Class for all parameters
#-----------------------------------------------

class parameters():
    """parameters to be used for program"""

    #--------------------------
    def __init__(self):
        """initializa parameters"""

        self.c_or_p = "call"
        self.S = 857.29 #underlying asset price
        self.v = 0.2076 #volatility
        self.r = 0.0014 #rf treasury rate
        self.T = 18/ 365.0 #days till maturity
        self.K = 860.00 #strike rate
        self.simulations = 10000000 #no. of simulations

    #---------------------------
    def print_parameters(self):
        """print parameters"""

        print "---------------------------------------------"
        print "---------------------------------------------"
        print "Pricing a:", self.c_or_p.upper()
        print "---------------------------------------------"
        print "Parameters of Monte Carlo Vanilla Call Pricer"
        print "Underlying Asset Price = ", self.S
        print "Volatility = ", self.v
        print "Risk-Free 10 Year Treasury Rate =", self.r
        print "Days Until Expiration = ", self.T
        print "Number of Simulations = ", self.simulations
        print "---------------------------------------------"
        print "---------------------------------------------"

This part is the issue. I have no idea what I'm doing lol. I can provide the algorithm if anyone cares.

#-----------------------------------------------
#Class for Monte Carlo
#-----------------------------------------------    
class vanilla_option_mc():
    def __init__(self):
        self.payoffs = []
        self.discount_factor = exp(-prm.r * prm.T)

    def gen_asset_price(self):
    #def gen_asset_price(S,v,r,T):
        """One of two main functions to be used. This will 
        generate the price of the security. This function
        will be used repetitively inside the for loop 
        later on during the actual Monte Carlo simulation"""

        self.asset_price = prm.S * exp((prm.r - 0.5 * prm.v**2) * prm.T 
                      + prm.v * sqrt(prm.T) * gauss(0,1.0))

        return self.asset_price


    def call_payoff(self):
        """use to price a call"""
        self.cp = max(self.call_S - self.call_K, 0.0)
        return self.cp

    def put_payoff(self):
        """Use to price a put"""
        self.pp = max(prm.K - prm.S, 0.0)
        return self.pp

    def calculate_payoff_vector(self):
        """main iterative loop to run the 
        Monte Carlo simulation. Returns a vector
        of different potential payoffs""" 

        self.count = 0
        for i in xrange(simulations):
            self.S_T = gen_asset_price()
            if self.c_or_p == "call":
                self.payoffs.append(call_payoff(self.S_T,prm.K))
            elif self.c_or_p == "put":
                self.payoffs.append(put_payoff(self.S_T,prm.K))
        self.count += 1

        return self.payoffs    

    def compute_price(self):
        """Uses payoff vector and discount
        factor to compute the price of the
        option"""
        self.V_i = [x*self.discount_factor for x in self.payoffs]
        self.price = sum(self.V_i) / float(prm.simulations)

    def print_price(self):
        """prints the option price to terminal"""
        print str(prm.c_or_p.upper()),"Price: %.4f" % self.price        

    def calc_statistics():
        """uses payoffs and price to calc
        variance, standard deviation, and
        a 95% confidence interval for price"""
        self.V_i_minus_price_squared = [(x - self.price)**2 for x in self.V_i]
        self.variance = sum(self.V_i_minus_price_squared) /float(prm.simulations-1)
        self.sd = sqrt(self.variance)
        self.CI = [self.price - (1.96*sd/sqrt(float(prm.simulations))),
                   self.price + (1.96*sd/sqrt(float(prm.simulations)))]


    def print_statistics():
        print "Variance: %.4f" % self.variance
        print "Standard Deviation: %.4f" % self.sd
        print "95% Confidence Interval:", self.CI


prm = parameters()
prm.print_parameters()

I've hit the problem in the learning curve that I can make a lot of things work pretty well now. But as far as a little bit more in depth classes go, as well as readability and clean code, I am lacking.

I'd like to improve on these things.

Thanks in advance.

DudeWah
  • 359
  • 3
  • 20
  • "but being a math guy, my code is ugly" Why does that follow? A math guy should find things like comprehensions, generators, and advanced modules such as itertools very natural, which are the key for non-ugly Python code. Use classes if you find them useful for your problem, but not because you think that they are the key for nice code. They aren't. In any event, your question is awfully unclear. Perhaps you could focus it. – John Coleman Dec 02 '16 at 00:47
  • I'm going to go ahead and just put this out there. Even if my OP was a "bad (lack of a) question" responses of this nature are not helpful to anything. I could have corrected the issue, if you pointed out what was wrong with my approach. Instead of just pointing me in the right direction and telling me to research these topics, it seems that you took slight at my math comment (not sure why) and chose an oddly passive aggressive route to take. I really don't think the snarky tone was necessary. Just to follow up I realized what my flaw was and solved this issue. In the end, thanks. – DudeWah Dec 03 '16 at 05:01
  • I am a mathematician, so I simply disagreed with the implication that there is something about being a mathematician that explains ugly code. I was perfectly serious that having a math background is good for Python programming, since e.g. comprehension notation is quite similar to set notation. Don't sell yourself short. If you are a math guy -- then for that very reason you have the skills to write beautiful code. I was also serious that over-emphasis on classes isn't the way to go. It is the functional elements in Python which are the keys to its beauty. (I didn't downvote you, by the way.) – John Coleman Dec 03 '16 at 05:28
  • I agree with you. I'm just new to scientific computing and since I've been self teaching, there seems to be a lot of points where some details get lost in the fray that lead me astray. I had a similar problem early on in undergraduate Real Analysis and the like. I apologize if my response was in any way rude, I may have taken your response the wrong way. Your comment actually ended up helping me in the end. And this response has given me some more insight and motivation on how to improve. So really, thanks. :) – DudeWah Dec 03 '16 at 07:14

0 Answers0