def calculateVolatility(self, primium, type, stockPrice, strike, expiryYears, riskfreeRate):
        if stockPrice <= 0 or primium <= 0 or expiryYears <= 0:
            return 0
            
        bs = BlackScholesCalculator()

        loopVolatility = self.initVolatility(stockPrice, expiryYears, primium)

        prevVolatility = loopVolatility / 2.0
        loopPremium = bs.getValue(type, stockPrice, strike, prevVolatility, expiryYears, riskfreeRate)
        
        loop = 0
        while (1 == 1):
            loop += 1
            if loop > 1000: return -1
                
            newPrimium = bs.getValue(type, stockPrice, strike, loopVolatility, expiryYears, riskfreeRate)
            prevPrimium = loopPremium
            loopPrimium = newPrimium
            
            if newPrimium < 0.00001: return -1
            
            var1 = loopPrimium - primium
            
            if (abs(loopPrimium - primium) <= 0.01):
                return loopVolatility
            
            loopVega = bs.getVega(stockPrice, strike, loopVolatility, expiryYears, riskfreeRate)
            newVolatility = self.adjVolatility(loopVolatility, loopPrimium, loopVega, prevVolatility, prevPrimium, primium)
            prevVolatility = loopVolatility
            loopVolatility = newVolatility
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 17 12:55:25 2015

@author: ka
"""

import sys

sys.dont_write_bytecode = True

from entity.EuropeanOptions import *
from model.BlackScholesCalculator import *

bs = BlackScholesCalculator()

opt = EuropeanOptions("call", 100.0, 100.0, 0.35607, 1, 0.02)
value = bs.getValue(opt.type, opt.stockPrice, opt.strike, opt.volatility, opt.expiryYears, opt.riskfreeRate)
print "value of call:", value

delta = bs.getDelta(opt.type, opt.stockPrice, opt.strike, opt.volatility, opt.expiryYears, opt.riskfreeRate)
print "delta of call:", delta

theta = bs.getTheta(opt.type, opt.stockPrice, opt.strike, opt.volatility, opt.expiryYears, opt.riskfreeRate)
print "theta of call:", theta

rho = bs.getRho(opt.type, opt.stockPrice, opt.strike, opt.volatility, opt.expiryYears, opt.riskfreeRate)
print "rho of call:", rho

print
def main():
    PortfolioData = '../Strategy/' + 'Bear Put Spread.csv'
    # PortfolioData = '../Strategy/' + 'Bear Put Spread.csv'

    try:
        qd = open(PortfolioData, 'r')
        qd_head = []
        qd_head.append(qd.readline())
        qd_head.append(qd.readline())
        qd.close()
    except:
        sys.stderr.write("Usage: OptionStrategy.py PortfolioData.dat\n")
        sys.stderr.write("Couldn't read PortfolioData")
        sys.exit(1)

    bs = BlackScholesCalculator()

    first = qd_head[0].split(',')
    second = qd_head[1].split(',')

    stockPrice = float(first[1])
    riskfreeRate = float(first[2])
    optionStyle = first[3]
    
    daysFromToday = float(second[1])
    plVolatility = float(second[2])
    plRiskfreeRate = float(second[3])
    plMin = float(second[4])
    plMax = float(second[5])
    
    priceStep = (float(plMax) - float(plMin)) / 36.0

    data = pd.io.parsers.read_csv(PortfolioData, sep=',', header=2, na_values=' ')
    print data.tail(9)

    plCurrent = plMin
    results = pd.DataFrame([], columns=list('ABC'))
    
    while (plCurrent <= plMax):
        todayValue = 0
        expiryValue = 0
        totalPremium = 0
        
        for i in data.index:
            if data.Buy_Sell[i].lower() == 'sell':
                positionFactor = -1
            else:
                positionFactor = 1
                
            quantity = float(data.Quantity[i])

            totalPremium += float(data.Primium[i]) * positionFactor * quantity
                
            theTodayValue = bs.getValue(data.Call_Put_Stock[i].lower(),
                                plCurrent,
                                float(data.Strike[i]),
                                plVolatility,
                                (float(data.ExpiryDays[i]) - daysFromToday) / 365.0,
                                riskfreeRate)
                                
            theExpiryValue = getProfitValue(data.Call_Put_Stock[i].lower(),
                                plCurrent,
                                float(data.Strike[i]))
            
            todayValue += theTodayValue * positionFactor * quantity
            expiryValue += theExpiryValue * positionFactor * quantity
            
            print plCurrent, i, ':', theExpiryValue, expiryValue

        theResult = pd.DataFrame([[plCurrent, todayValue - totalPremium, expiryValue - totalPremium]], columns=list('ABC'))
        results = results.append(theResult)
        
        plCurrent += priceStep
        
    print results.tail(10)
    
    results.plot(x='A', y=list('BC'))