使用 xlwings 运行 python excel 中的代码

use xlwings to run python code in excel

我在 excel 中 运行ning python xlwings 的代码有问题。我的 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']

在 运行ning excel 之后,我收到如下错误消息:

File "/Users/wenchengwang/PycharmProjects/practice/practice.py", line 7, in

from deribit_api import RestClient

ModuleNotFoundError: No module named 'deribit_api'

我对错误信息感到困惑,这是否意味着我必须将 deribit api 安装到 excel 中?

您似乎正在从 Excel 调用一个 Python 环境,但没有安装 derebit 包。您必须将 Excel 加载项指向安装了该软件包的解释器,或者将软件包的路径添加到您的 PYTHONPATH,请参阅:

http://docs.xlwings.org/en/stable/addin.html#global-settings