xlwings图表模拟器 – 无法用模拟图表复制macros表

  1. 我从xlwings下载了模拟图表,以及excel调用来运行模拟的.py Python脚本。
  2. 复制Excel工作簿上的工作表。
  3. 保存附加的.py脚本并重新链接所有对复制表单的引用。
  4. 在Alt + F11上用新名称创build新函数,调用复制的.py脚本。
  5. 检查引用错误,除了复制的Excel选项卡由于.py脚本中的错误行而无法为图表运行模拟外,

set_source_data(sht.range((1,15),(num_timesteps + 2,19)))

具体来说,似乎突出了“图5”的问题。 我不知道一个解决方法,而不做重大的代码更改。 以下完整的错误描述:


错误

回溯(最近一次通话最后):

文件“”,第1行,

文件“GBM_2.py”,第26行,在主sht.charts ['Chart 5']。set_source_data(sht.range((1,15),(num_timesteps + 2,19)))

文件“C:\ Users \ Darius \ Miniconda2 \ lib \ site-packages \ xlwings \ main.py”,第78行,在getitem return self(key)

文件“C:\ Users \ Darius \ Miniconda2 \ lib \ site-packages \ xlwings \ main.py”,第49行, 调用 return self._wrap(impl = self.impl(name_or_index))

文件“C:\ Users \ Darius \ Miniconda2 \ lib \ site-packages \ xlwings_xlwindows.py”,行1122,在调用引发KeyError(key)

KeyError:“图表5”

实际的.py脚本:

from __future__ import division import sys import numpy as np import xlwings as xw def main(): sht = xw.Book.caller().sheets('GBM2') # User Inputs num_simulations = sht.range('E3').options(numbers=int).value time = sht.range('E4').value num_timesteps = sht.range('E5').options(numbers=int).value dt = time/num_timesteps # Length of time period sig = sht.range('E7').value mu = np.log(1 + sht.range('E6').value) # Drift starting_price = sht.range('E8').value perc_selection = [1, 50, 99] # percentiles (hardcoded for now) # Animation animate = sht.range('E9').value.lower() == 'yes' # On Excel: clear output, write out initial values of percentiles/sample path and set chart source # and x-axis values sht.range('O2').expand().clear_contents() sht.range('P2').value = [starting_price, starting_price, starting_price, starting_price] sht.charts['Chart 5'].set_source_data(sht.range((1, 15), (num_timesteps + 2, 19))) sht.range('O2').value = np.round(np.linspace(0, time, num_timesteps + 1).reshape(-1, 1), 2) # Preallocation price = np.zeros((num_timesteps + 1, num_simulations)) percentiles = np.zeros((num_timesteps + 1, 3)) # Set initial values price[0,:] = starting_price percentiles[0,:] = starting_price # Simulation at each time step for t in range(1, num_timesteps + 1): rand_nums = np.random.randn(num_simulations) price[t,:] = price[t-1,:] * np.exp((mu - 0.5 * sig**2) * dt + sig * rand_nums * np.sqrt(dt)) percentiles[t, :] = np.percentile(price[t, :], perc_selection) if animate: sht.range((t+2, 16)).value = percentiles[t, :] sht.range((t+2, 19)).value = price[t, 0] # Sample path if sys.platform.startswith('win'): sht.book.app.screen_updating = True if not animate: sht.range('P2').value = percentiles sht.range('S2').value = price[:, :1] # Sample path