xlwings - for python quants conference (london 2014)
TRANSCRIPT
• PyXLL • DataNitro • pywin32 • xlwings ExcelPython
The current Python/Excel Landscape
4
Read/Write Program/Interact • xlwt/xlrd/xlutils • XlsxWriter • OpenPyxl
Why xlwings?
• Open source • Cross-Platform (!!): Windows & Mac • Make things EASY: – pip install xlwings (requires pywin32 on Win) – Works out of the box for default installation – Easily switch between different installations – Flexible: Python (2.6-3.4), Excel (2000-2013),
Architecture Mix (!!), IDE – Easy debugging
5
Send an array to Excel with pywin32…
• xxx
6
>>> from win32com.client import Dispatch >>> import numpy as np
>>> xlApp = Dispatch("Excel.Application") >>> xlApp.Visible = True >>> xlWb = xlApp.Workbooks.Add() >>> xlSht = xlWb.ActiveSheet
>>> data = np.array([[1,2],[3,4]])
>>> r, c = data.shape >>> xlSht.Range(xlSht.Cells(1,1), xlSht.Cells(r,c)).Value = data.tolist()
…and with xlwings
• xxx
7
>>> from xlwings import Workbook, Range >>> import numpy as np
>>> wb = Workbook() >>> Range("A1").value = np.array([[1,2],[3,4]])
Replace VBA macros
myarray.py
8
from xlwings import Workbook, Range import numpy as np
def get_array(): wb = Workbook.caller() # <v0.3: wb = Workbook() Range("A1").value = np.array([[1,2],[3,4]])
Sub GetArray() RunPython ("import myarray;myarray.get_array()") End Sub
VBA (requires xlwings VBA module)
xlwings v0.3.0
• Experimental ExcelPython integration: – Optimized connection on Win (COM server) – UDFs (User Defined Functions) on Windows
• Comparison with PyXXL: ExcelPython is slower and needs a VBA wrapper, but: – Allows the Excel 32bit & Python 64bit combo – Can access existing functions w/o decorators – It’s easy to switch between Python installations
9
Pseudo Inverse: numpy.linalg.pinv
10
Public Function pinv(x As Range) On Error GoTo Fail: Set numpy_array = Py.GetAttr(Py.Module("numpy"), "array") Set pseudo_inv = Py.GetAttr(Py.GetAttr(Py.Module("numpy"), _ "linalg"), "pinv") Set x_array = Py.Call(numpy_array, Py.Tuple(x.Value)) Set result_array = Py.Call(pseudo_inv, Py.Tuple(x_array)) Set result_list = Py.Call(result_array, "tolist") pinv = Py.Var(result_list) Exit Function Fail: pinv = Err.Description End Function
What’s next?
• Add-in • Full integration of xlwings and ExcelPython • Make it more feature complete • Someday…add support for – Google Sheets – LibreOffice – OpenOffice
11