Re: [Tutor] urgent help required! invalid syntax

2011-02-18 Thread Timo
On 18-02-11 09:42, lim chee siong wrote:
>
>
> Hi,
>
> I was writing a module for the black-scholes pricing model in python,
> but I keep getting this error message:
>
> Traceback (most recent call last):
> File "", line 1, in 
> File "C:\Python26\lib\blackscholes.py", line 25
> d2=d1-v*sqrt(t)
That's not the whole traceback, is it?

>
> This is the code in my blackscholes.py file:
> #Black-Scholes model
>
> [snip]
>
> def dividend(s,x,r,t,v):
> d1=(log(s/x)+((r+v**2/2)*t)/(v*sqrt(t))
> d2=d1-v*sqrt(t)
>
> [snip]
>
>
> What is wrong here? What do I need to change?
Check the line before the line which throws a syntax error. Have a good
look at it and you will see you are missing a character.

Cheers,
Timo

> Thanks! Quick reply will be much appreciated because the deadline is
> tomorrow!
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] urgent help required! invalid syntax

2011-02-18 Thread lim chee siong



Hi,
I was writing a module for the black-scholes pricing model in python, but I 
keep getting this error message: 
Traceback (most recent call last):  File "", line 1, in   File 
"C:\Python26\lib\blackscholes.py", line 25d2=d1-v*sqrt(t) 
This is the code in my blackscholes.py file:#Black-Scholes model
import mathimport numpyimport scipy
#Cumulative normal distribution
def CND(x):  
(a1,a2,a3,a4,a5)=(0.31938153,-0.356563782,1.781477937,-1.821255978,1.330274429) 
 L=abs(x)  K=1.0/(1.0+0.2316419*L)  
w=1.0-1.0/sqrt(2*pi)*exp(-L*L/2)*(a1*K+a2*K*K+a3*pow(K,3)+a4*pow(K,4)+a5*pow(K,5))
  if x<0:w=1.0-w  return w
#s: price of underlying stockx:strike price#r: continuously compounded risk 
free interest rate#t: time in years until expiration of option#v: implied 
volatility of underlying stock
def dividend(s,x,r,t,v):  d1=(log(s/x)+((r+v**2/2)*t)/(v*sqrt(t))  
d2=d1-v*sqrt(t)
def BS(s,x,r,t,v):  c=s*CND(d1)-x*exp(-r*t)*CND(d2)  
p=x*exp(-r*t)*CND(-d2)-s*CND(-d1)  delta=CND(d1)-1  gamma=CND(d1)/(s*v*sqrt(t)) 
 vega=s*CND(d1)*sqrt(t)  
theta=-((s*CND(d1)*v)/(2*sqrt(t))+r*x*exp(-r*t)*CND(-d2)  
rho=-x*t*exp(-r*t)*CND(-d2)

What is wrong here? What do I need to change? Thanks! Quick reply will be much 
appreciated because the deadline is tomorrow!
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Odd behavior with eval, list comps, and name lookup

2011-02-18 Thread John
I noticed some odd behavior relating to eval(). First, a baseline case for
behavior:

>>> def test():
... x = 5
... return [a for a in range(10) if a == x]
...
>>> test()
[5]

So far so good. Now let's try eval:

>>> c = compile('[a for a in range(10) if a == x]', '', 'single')
>>> eval(c, globals(), {'x': 5})
Traceback (most recent call last):
File "", line 1, in 
File "", line 1, in 
File "", line 1, in 
NameError: global name 'x' is not defined

Looks like 'x' is searched for only among the globals, bypassing the locals.
The same behavior is seen between exec and eval, with and without compile,
and between 3.1.3 and 3.2rc2. Given simpler code without a list comp, the
locals are used just fine:

>>> c = compile('a=5; a==x', '', 'single')
>>> eval(c, {}, {'x': 5})
True

Could anyone help me understand these scoping rules? Thanks.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regex questions

2011-02-18 Thread Albert-Jan Roskam
Hi Steven,

Thanks a BUNCH for helping me! Yes, you were correct in assuming that my input 
data are already names. They're names in a column in a csv file.  They're the 
names of GPs, in various formats. Besides the forms I've mentioned already 
there 
are examples such as 'Doctor's office Duh, J. & Dah, J.', with or without 
initials and/or connecting words. There are also offices with names as Doctor's 
Office 'Under the Oaks'. I want to normalise those cases too till  'Doctor's 
office J. Duh & J. Dah', etc. Currently I use " & ".split() and apply my 
regexes 
(I use three, so I will certainly study your very fancy function!).


So the raw string \b means means "ASCII backspace". Is that another way of 
saying that it means 'Word boundary'?

You're right: debugging regexes is a PIA. One teeny weeny mistake makes all the 
difference. Could one say that, in general, it's better to use a Divide and 
Conquer strategy and use a series of regexes and other string operations to 
reach one's goal?

http://code.activestate.com/recipes/251871-latin1-to-ascii-the-unicode-hammer/ 
is interesting. I did something similar with  unicode.translate(). Many people 
here have their keyboard settings as US, so accented letters are not typed very 
easily, and are therefore likely to be omitted (e.g. enquĂȘte vs enquete). 


Thanks again!

Cheers!!
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a fresh water system, and public health, what have 
the 
Romans ever done for us?
~~





From: Steven D'Aprano 
To: Python Mailing List 
Sent: Fri, February 18, 2011 4:45:42 AM
Subject: Re: [Tutor] regex questions

Albert-Jan Roskam wrote:
> Hello,
> 
> I have a couple of regex questions:
> 
> 1 -- In the code below, how can I match the connecting words 'van de' , 'van 
>der', etc. (all quite common in Dutch family names)?

You need to step back a little bit and ask, what is this regex supposed to 
accomplish? What is your input data? Do you expect this to tell the difference 
between van used as a connecting word in a name, and van used otherwise?

In other words, do you want:

re.search(???, "J. van Meer")  # matches
re.search(???, "The van stopped")  # doesn't match

You might say, "Don't be silly, of course not!" *but* if you expect this regex 
to detect names in arbitrary pieces of text, that is exactly what you are 
hoping 
for. It is beyond the powers of a regex alone to distinguish between arbitrary 
text containing a name:

"... and to my nephew Johann van Meer I leave my collection of books..."

and arbitrary text without a name:

"... and the white van merely touched the side of the building..."

You need a proper parser for that.

I will assume that your input data will already be names, and you just want to 
determine the connecting words:

van der
van den
van de
van

wherever they appear. That's easy: the only compulsory part is "van":

pattern = r"\bvan\b( de[rn]?)?"

Note the use of a raw string. Otherwise, \b doesn't mean "backslash b", but 
instead means "ASCII backspace".

Here's a helper function for testing:

def search(pattern, string):
mo = re.search(pattern, string, re.IGNORECASE)
if mo:
return mo.group(0)
return "--no match--"


And the result is:

>>> names = ["J. van der Meer", "J. van den Meer", "J. van Meer",
... "Meer, J. van der", "Meer, J. van den", "Meer, J. van de",
... "Meer, J. van"]
>>>
>>> for name in names:
... print search(pattern, name)
...
van der
van den
van
van der
van den
van de
van

Don't forget to test things which should fail:

>>> search(pattern, "Fred Smith")
'--no match--'
>>> search(pattern, "Fred Vanderbilt")
'--no match--'



> 2 -- It is quite hard to make a regex for all surnames, but easier to make 

"\b[a-z]+[-']?[a-z]*\b" should pretty much match all surnames using only 
English 
letters, apostrophes and hyphens. You can add in accented letters as need.

(I'm lazy, so I haven't tested that.)


> regexes for the initials and the connecting words. How could I ' subtract'  
>those two regexes to end up with something that matches the surnames (I used 
>two 
>.replaces() in my code, which roughly work, but I'm thinking there's a re way 
>to 
>do it, perhaps with carets (^).

Don't try to use regexes to do too much. Regexes are a programming language, 
but 
the syntax is crap and there's a lot they can't do. They make a good tool for 
*parts* of your program, not the whole thing!

The best approach, I think, is something like this:


def detect_dutch_name(phrase):
"""Return (Initial, Connecting-words, Surname) from a potential
Dutch name in the form "Initial [Connecting-words] Surname" or
"Surname, Initial Connecting-words".
"""
pattern = (  r"(?P.*?), "
 r"(?P[a-z]\.) ?(?Pvan (de[r

Re: [Tutor] urgent help required! invalid syntax

2011-02-18 Thread Steven D'Aprano
lim chee siong wrote:
> 
> 
> Hi,
> I was writing a module for the black-scholes pricing model in python, but I 
> keep getting this error message: 
> Traceback (most recent call last):  File "", line 1, in   File 
> "C:\Python26\lib\blackscholes.py", line 25d2=d1-v*sqrt(t) 


Please COPY AND PASTE the FULL error message, including the entire
traceback. Do not re-type it, summarise it, simplify it, or change it in
any other way.

But my guess is that you're probably missing a closing bracket ) on that
line, or the one before it.



-- 
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regex questions

2011-02-18 Thread Steven D'Aprano

Albert-Jan Roskam wrote:

So the raw string \b means means "ASCII backspace". Is that another way of 
saying that it means 'Word boundary'?


No.

Python string literals use backslash escapes for special characters, 
similar to what many other computer languages, including C, do.


So when you type "hello world\n" as a *literal* in source code, the \n 
doesn't mean backslash-n, but it means a newline character. The special 
escapes used by Python include:


\0  NULL (ASCII code 0)
\a  BELL character (ASCII code 7)
\b  BACKSPACE (ASCII code 8)
\n  newline
\t  tab
\r  carriage return
\'  single quote  (does not close string)
\"  double quote  (does not close string)
\\  backslash
\0nn  character with ASCII code nn in octal
\xXX  character with ASCII code XX in hex

\b (backspace) doesn't have anything to do with word boundaries.

Regexes, however, are a computer language in themselves, and they use an 
*actual backslash* to introduce special meaning. Because that backslash 
clashes with the use of backslashes in Python string literals, you have 
to work around the clash. You could do any of these:


# Escape the backslash, so Python won't treat it as special:
pattern = '\\bword\\b'

# Use chr() to build up a non-literal string:
pattern = chr(92) + 'bword' + chr(92) + 'b'

# Use raw strings:
pattern = r'\bword\b'

The Python compiler treats backslashes as just an ordinary character 
when it compiles raw strings. So that's the simplest and best solution.



You're right: debugging regexes is a PIA. One teeny weeny mistake makes all the 
difference. Could one say that, in general, it's better to use a Divide and 
Conquer strategy and use a series of regexes and other string operations to 
reach one's goal?


Absolutely!



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Odd behavior with eval, list comps, and name lookup

2011-02-18 Thread Peter Otten
John wrote:

> I noticed some odd behavior relating to eval(). First, a baseline case for
> behavior:
> 
 def test():
> ... x = 5
> ... return [a for a in range(10) if a == x]
> ...
 test()
> [5]
> 
> So far so good. Now let's try eval:
> 
 c = compile('[a for a in range(10) if a == x]', '', 'single')
 eval(c, globals(), {'x': 5})
> Traceback (most recent call last):
> File "", line 1, in 
> File "", line 1, in 
> File "", line 1, in 
> NameError: global name 'x' is not defined
> 
> Looks like 'x' is searched for only among the globals, bypassing the
> locals. The same behavior is seen between exec and eval, with and without
> compile, and between 3.1.3 and 3.2rc2. Given simpler code without a list
> comp, the locals are used just fine:
> 
 c = compile('a=5; a==x', '', 'single')
 eval(c, {}, {'x': 5})
> True
> 
> Could anyone help me understand these scoping rules? Thanks.

Except for class definitions the compiler statically determines whether a 
variable is global or local (or a closure).
List comprehensions and generator expressions are realized as functions; 
therefore they have their own local scope that you cannot provide via 
eval/exec. 

You could argue that in the following example

>>> exec("x = 2; print([a for a in range(3) if a == x])", {}, {})
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
  File "", line 1, in 
NameError: global name 'x' is not defined

the assignment x = 2 should give the compiler a clue that x is supposed to 
be a local name, just like in

def f():
   x = 2
   print([a for a in range(3) if a == x])

My *guess* is that this is an implementation restriction rather than a 
conscious decision. It works for the common case of module-level code 
because there local and global namespace are identical:

>>> exec("x = 2; print([a for a in range(3) if a == x])", {})
[2]

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urgent help required! invalid syntax

2011-02-18 Thread James Reynolds
There's a few things I've noticed:

1. I would recommend using an IDE of some sort. I copy and pasted this into
eclipse, and it told me straight away that you had a parenthesis problem on
this line: d1=(log(s/x)+((r+v**2/2)*t)/(v*sqrt(t))

2. Your function "dividend" isn't returning a value.

3. Unless there is more to the program that you haven't shown us, all of the
math stuff that I can see, such as sqrt, pi, log, exp and possibly others
I'm not thinking of should be prefixed with math..

4. The function BS isn't returning anything.

5. Lastly, if you are a familiar with object oriented programing, the black
scholes is better suited towards OOP.

2011/2/18 lim chee siong 

>
>
> Hi,
>
> I was writing a module for the black-scholes pricing model in python, but I
> keep getting this error message:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python26\lib\blackscholes.py", line 25
> d2=d1-v*sqrt(t)
>
>
> This is the code in my blackscholes.py file:
> #Black-Scholes model
>
> import math
> import numpy
> import scipy
>
> #Cumulative normal distribution
>
> def CND(x):
>
>   
> (a1,a2,a3,a4,a5)=(0.31938153,-0.356563782,1.781477937,-1.821255978,1.330274429)
>   L=abs(x)
>   K=1.0/(1.0+0.2316419*L)
>   
> w=1.0-1.0/sqrt(2*pi)*exp(-L*L/2)*(a1*K+a2*K*K+a3*pow(K,3)+a4*pow(K,4)+a5*pow(K,
> 5))
>   if x<0:
> w=1.0-w
>   return w
>
> #s: price of underlying stockx:strike price
> #r: continuously compounded risk free interest rate
> #t: time in years until expiration of option
> #v: implied volatility of underlying stock
>
> def dividend(s,x,r,t,v):
>   d1=(log(s/x)+((r+v**2/2)*t)/(v*sqrt(t))
>   d2=d1-v*sqrt(t)
>
> def BS(s,x,r,t,v):
>   c=s*CND(d1)-x*exp(-r*t)*CND(d2)
>   p=x*exp(-r*t)*CND(-d2)-s*CND(-d1)
>   delta=CND(d1)-1
>   gamma=CND(d1)/(s*v*sqrt(t))
>   vega=s*CND(d1)*sqrt(t)
>   theta=-((s*CND(d1)*v)/(2*sqrt(t))+r*x*exp(-r*t)*CND(-d2)
>   rho=-x*t*exp(-r*t)*CND(-d2)
>
>
> What is wrong here? What do I need to change? Thanks! Quick reply will be
> much appreciated because the deadline is tomorrow!
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor