Mibian returning "NameError: name 'norm' is not defined..." when using with xlwings - python-3.7

I was trying to write an Excel UDF using xlwings to return finance options calculation from the Mibian library. I've tried the code below.
import xlwings as xw
import mibian
#xw.func
def BSPutOptionImpVol(underlyingPrice,strike,interestRate,expiryDays,premium):
c = mibian.BS([underlyingPrice, strike, interestRate, expiryDays], putPrice=premium)
return c.impliedVolatility
From Excel, I then call the function with the following =BSPutOptionImpVol(45,32,1,127,0.95)
It's returning the following error:
"NameError: name 'norm' is not defined
call = self.underlyingPrice * norm.cdf(self.d1) - \
File ""C:\Users...\anaconda3\lib\site-packages\mibian__init__.py"", line 307, in _price
[self.callPrice, self.putPrice] = self._price()
File ""C:\Users...\anaconda3\lib\site-packages\mibian__init__.py"", line 276, in init
estimate = eval(className)(args, volatility=mid, performance=True).putPrice
File ""C:\Users...\anaconda3\lib\site-packages\mibian__init__.py"", line 29, in impliedVolatility
self.class.name, args, putPrice=self.putPrice)
File ""C:\Users...\anaconda3\lib\site-packages\mibian__init__.py"", line 293, in init
c = mibian.BS([underlyingPrice, strike, interestRate, expiryDays], putPrice=premium)
File ""c:\users...\documents\python scripts\BSPutImVol.py"", line 6, in BSPutOptionImpVol
ret = func(*args)
File ""C:\Users...\anaconda3\lib\site-packages\xlwings\udfs.py"", line 298, in call_udf
res = call_udf(script, fname, args, this_workbook, FromVariant(caller))
File ""C:\Users...\anaconda3\lib\site-packages\xlwings\server.py"", line 195, in CallUDF
return func(args)
File ""C:\Users...\anaconda3\lib\site-packages\win32com\server\policy.py"", line 586, in _invokeex_
return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None)
File ""C:\Users...\anaconda3\lib\site-packages\win32com\server\policy.py"", line 283, in _invoke_
return self._invoke_(dispid, lcid, wFlags, args)
File ""C:\Users...\anaconda3\lib\site-packages\win32com\server\policy.py"", line 278, in _Invoke_"
I have also tried just calling the function without passing the parameters in (ie the input values are in the python code) but I still get the same error.
However, if I comment out xlwings and just run the Python code from Spyder as below, it works.
#import xlwings as xw
import mibian
##xw.func
def BSPutOptionImpVol(underlyingPrice,strike,interestRate,expiryDays,premium):
c = mibian.BS([underlyingPrice, strike, interestRate, expiryDays], putPrice=premium)
# return c.impliedVolatility
print(c.impliedVolatility)
I'm a newbie to Python, so appreciate any help and advice. Thanks.

Try..
from scipy.stats import norm

Try add
import scipy
to your code. That resolved the 'norm' issue for me.

This worked for me
pip uninstall numpy scipy
and then
pip install -U numpy scipy

Related

python AttributeError when attempting to save excel chart using PIL

I am trying to save an chart from excel into a file, which I want to use later in a powerpoint presentation, but the code I am running keeps on coming up with
"AttributeError: 'NoneType' object has no attribute 'save'" .
Have been looking around google/stackoverflow but none of the suggestions I can find actually help, I keep on getting the error.
The code I am trying is below,
import win32com.client
import PIL
folder_path = r'C:/temp/Monthly_Graphs.xlsm'
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
wb.Sheets('Sheet1').Shapes('Sheet1_Pie_Chart').CopyPicture()
pie_image = PIL.ImageGrab.grabclipboard()
pie_image.savefig(r'C:/temp/pie_test.bmp','BMP')
the traceback is below
Traceback (most recent call last):
File "<ipython-input-12-b8e52c17e4d1>", line 1, in <module>
runfile('C:/python/stackoverflow_1.py', wdir='C:/python')
File "C:\Users\xxxxxxx\AppData\Local\conda\conda\envs\py64bit\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "C:\Users\xxxxxxx\AppData\Local\conda\conda\envs\py64bit\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/python/stackoverflow_1.py", line 26, in <module>
pie_image.savefig(r'C:/temp/pie_test.bmp','BMP')
AttributeError: 'NoneType' object has no attribute 'savefig'
Managed to get it to work by referring to the below Q and setting the format of the CopyPicture line. Issue seems to be that excel default copy of the image is not in a format that PIL understands
Python Export Excel Sheet Range as Image
import win32com.client
from PIL import ImageGrab
import win32clipboard as clip
folder_path = r'C:/temp/Monthly_Graphs.xlsm'
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
wb.Sheets('Sheet1').Shapes('Sheet1_Pie_Chart').CopyPicture(Format=clip.CF_BITMAP)
pie_image = ImageGrab.grabclipboard()
pie_image.save(r'C:/temp/pie_test.bmp','BMP')

PyPDF2.PdfFileReader hangs indefinitely

I'm trying to read this pdf file (https://www.accessdata.fda.gov/cdrh_docs/pdf14/K141693.pdf) and am following these suggestions from SO
Opening pdf urls with pyPdf
I have actually downloaded the file locally and am running the following code
import PyPDF2
pdf_file = open("K141693.pdf")
pdf_read = PyPDF2.PdfFileReader(pdf_file)
but my code hangs indefinitely. I'm running Python 2.7 and here is the stacktrace.
Traceback (most recent call last):
File "", line 1, in
runfile('C:/PoC/pdf_reader.py', wdir='C:/PoC')
File
"C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py",
line 880, in runfile
execfile(filename, namespace)
File
"C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py",
line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/PoC/pdf_reader.py", line 13, in
pdf_read = PyPDF2.PdfFileReader(pdf_file)
File "C:\ProgramData\Anaconda2\lib\site-packages\PyPDF2\pdf.py",
line 1084, in init
self.read(stream)
File "C:\ProgramData\Anaconda2\lib\site-packages\PyPDF2\pdf.py",
line 1697, in read
line = self.readNextEndLine(stream)
File "C:\ProgramData\Anaconda2\lib\site-packages\PyPDF2\pdf.py",
line 1938, in readNextEndLine
x = stream.read(1)
KeyboardInterrupt
I came across another post here PyPDF2 hangs on processing but that too doesn't have a response.
You need to parse the file in binary ('rb') mode. (This works in Python 3:)
import PyPDF2
pdf_file = open("K141693.pdf", "rb")
read_pdf = PyPDF2.PdfFileReader(pdf_file)

TensorFlow: use gfile.FastGfile() method can't not read a file with its path include Chinese characters

I want to read use gfile.FastGFile(image_path, 'rb').read() to read a picture and use it as the input of my project, and I use the directory name as the lable of these pictures which are include in the directory, when the directory name is in English, my code works fine, but when the directory name is in Chinese, it throws this Error:
Traceback (most recent call last):
File "F:/pythonWS/imageFilter/jpegFileJudge.py", line 27, in <module>
image_data = gfile.FastGFile(image_path, 'rb').read()
File "C:\Program Files\Python35\lib\site-
packages\tensorflow\python\lib\io\file_io.py", line 106, in read
self._preread_check()
File "C:\Program Files\Python35\lib\site-
packages\tensorflow\python\lib\io\file_io.py", line 73, in _preread_check
compat.as_bytes(self.__name), 1024 * 512, status)
File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__
next(self.gen)
File "C:\Program Files\Python35\lib\site-
packages\tensorflow\python\framework\errors_impl.py", line 466, in
raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile
failed to Create/Open: F:\vsWorkspace\pics\test\三宝鸟
\0ff41bd5ad6eddc403fa02d13bdbb6fd526633fe.jpg :
ϵͳ\udcd5Ҳ\udcbb\udcb5\udcbdָ\udcb6\udca8\udcb5\udcc4\udcceļ\udcfe\udca1\udca3
my test code is :
# -*- coding: utf-8 -*-
import glob
import os
import random
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
image_folder='F:/vsWorkspace/pics/test'
os.chdir(image_folder)
count=0
for each in os.listdir(image_folder):
each=os.path.abspath(each)
os.chdir(each)
for image_path in os.listdir(each):
image_path = os.path.abspath(image_path)
print(image_path)
image_data = gfile.FastGFile(image_path, 'rb').read()
count += 1
os.chdir(image_folder)
My envirorment is Windows7 x64, python 3.5.3 and TensorFlow 1.0, How can I solve this problem?
By the way,I have to use Chinese directories' name use my pictures lables.

pyang and JNC integration

I'm trying to integrate JNC and Pyang. As the jnc steps describes I have copied jnc.py under PYANG_HOME/pyang/plugins. I try to generate the java classes for simple.yang under $JNC_HOME/examples/yang using the command
pyang -f jnc --jnc-output src/gen/simple yang/simple.yang
facing the following error,
Traceback (most recent call last):
File "D:/tools/pyang-master/bin/pyang", line 434, in <module>
run()
File "D:/tools/pyang-master/bin/pyang", line 408, in run
emit_obj.emit(ctx, modules, fd)
File "C:\Users\Siva\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyang-1.7-py3.5.egg\pyang/plugins\jnc.py", line 208, in emit
if module_stmt in (imported + included):
TypeError: unsupported operand type(s) for +: 'map' and 'map'
Anyone faced this kind of issue. please let me know how to fix this.
Problem is with map implementation:
map in Python-3 returns an iterator, while map in Python 2 returns a list:
Python 2:
>>> type(map(abs, [43, -12, 13, -14]))
<type 'list'>
Python 3:
>>> type(map(abs, [99, -52, 32, -34, 13]))
<class 'map'>
You can edit file jnc.py and change code as below:
for (module_stmt, rev) in self.ctx.modules:
if module_stmt in (imported + included):
module_set.add(self.ctx.modules[(module_stmt, rev)])
for (module_stmt, rev) in self.ctx.modules:
if module_stmt in (included):
module_set.add(self.ctx.modules[(module_stmt, rev)])
if module_stmt in (imported):
module_set.add(self.ctx.modules[(module_stmt, rev)])

Plotting many datapoints with matplotlib in Python

I recently switched from MATLAB to Python for data analysis and I am using matplotlib for visualization of the data. This works fine if the number of data points I would like to visualise are low. However, if I would like to visualize e.g.
import matplotlib.pyplot as plt
signal = [round(random.random() * 100) for i in xrange(0, 1000000)]
plt.plot(signal)
plt.show()
I am getting an error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__
return self.func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 276, in resize
self.show()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 1034, in draw
func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 2086, in draw
a.draw(renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/lines.py", line 562, in draw
drawFunc(renderer, gc, tpath, affine.frozen())
File "/usr/lib/pymodules/python2.7/matplotlib/lines.py", line 938, in _draw_lines
self._lineFunc(renderer, gc, path, trans)
File "/usr/lib/pymodules/python2.7/matplotlib/lines.py", line 978, in _draw_solid
renderer.draw_path(gc, path, trans)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 145, in draw_path
self._renderer.draw_path(gc, path, transform, rgbFace)
OverflowError: Allocated too many blocks
Can you give me an advise what you would do in this case? Are you down sampling your data?
If I perform the same plot in MATLAB even with more data points, I haven't had this problem before.
Not sure exactly what you are trying to show but you can change the plot to '.' and it will work.
import random
import pylab as plt
signal = [round(random.random() * 100) for i in xrange(0, 1000000)]
plt.plot(signal, '.')
plt.show()
You may be able to get what you want by customising using the matlotlibrc file, the docs are here
I think scatter plot is faster
import matplotlib.pyplot as plt
x=np.random.normal(0,1,1000000)
y=np.random.normal(0,1,1000000)
plt.scatter(x,y)