我在Excel中通过xlwings运行python代码时遇到问题。我的vba代码是:
Sub Practice()
RunPython ("import practice; practice.getdata()")
End Sub
我的python代码是pycharm中的Practice.py。我使用python代码连接到deribit api,然后使用excel运行python代码以将数据从deribit api下载到excel。我的python代码如下:
import pprint
import xlwings as xw
import pandas as pd
import numpy as np
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl import Workbook
from deribit_api import RestClient
def getdata():
access_key = "6wvUvxmVSoJq"
access_secret = "HQQ7ZTU2ZESOR2UELLVSHCRWSHPP2VYE"
url = "https://test.deribit.com"
client = RestClient(access_key, access_secret, url)
client.index()
positions = client.positions()
account = client.account()
dfp = pd.DataFrame(columns=['Kind', 'Expiry Date', 'Direction', 'Underlying', 'Delta', 'Size', 'P&L'], index=range(len(positions)))
for i in range(len(positions)):
dfp.loc[i]['Kind'] = positions[i]['kind']
dfp.loc[i]['Expiry Date'] = positions[i]['instrument']
dfp.loc[i]['Direction'] = positions[i]['direction']
dfp.loc[i]['Underlying'] = positions[i]['indexPrice']
dfp.loc[i]['Delta'] = positions[i]['delta']
dfp.loc[i]['Size'] = positions[i]['size']
dfp.loc[i]['P&L'] = positions[i]['profitLoss']
wb = xw.Book.caller()
ws = wb.active
for r in dataframe_to_rows(dfp, index=False, header=True):
ws.append(r)
ws.cell(row=15, column=1).value = 'Total Delta'
ws.cell(row=15, column=2).value = 'Options Delta'
ws.cell(row=15, column=3).value = 'Options Gamma'
ws.cell(row=15, column=4).value = 'Options Theta'
ws.cell(row=15, column=5).value = 'Options Vega'
ws.cell(row=16, column=1).value = account['deltaTotal']
ws.cell(row=16, column=2).value = account['optionsD']
ws.cell(row=16, column=3).value = account['optionsG']
ws.cell(row=16, column=4).value = account['optionsTh']
ws.cell(row=16, column=5).value = account['optionsV']
运行excel后,出现如下错误消息:
文件“ /Users/wenchengwang/PycharmProjects/practice/practice.py”,行 7,在
从deribit_api导入RestClient
ModuleNotFoundError:没有名为“ deribit_api”的模块
我对错误消息感到困惑,是否意味着我必须将德里比特api安装到excel中?
答案 0 :(得分:0)
您似乎正在从Excel中调用未安装derebit软件包的Python环境。您必须将Excel加载项指向已安装软件包的解释器,或者将软件包的路径添加到PYTHONPATH,请参见:
http://docs.xlwings.org/en/stable/addin.html#global-settings