numpy 我的代码有什么问题?我一直得到“字符串索引必须是整数”

xriantvc  于 2022-12-18  发布在  其他
关注(0)|答案(1)|浏览(190)
import locale
import numpy as np
import pandas as pd
from pandas_datareader import data as wb
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm

ticker = "BHIL"
data = pd.DataFrame()
data[ticker] = wb.DataReader(ticker, data_source = 'yahoo', start = '2021-2-17')['Adj Close']
#Plot
data.plot(figsize=(15,6))

log_return = np.log(1 + data.pct_change())
#Plot
sns.distplot(log_return.iloc[1:])
plt.xlabel("Daily Return")
plt.ylabel("Frequency")

u = log_return.mean()
var = log_return.var()
drift = u - (0.5*var)

stdev = log_return.std()
days = 50
trials = 10000
Z = norm.ppf(np.random.rand(days, trials)) #days, trials
daily_returns = np.exp(drift.values + stdev.values * Z)

price_paths = np.zeros_like(daily_returns)
price_paths[0] = data.iloc[-1]
for t in range(1, days):
    price_paths[t] = price_paths[t-1]*daily_returns[t]
Traceback (most recent call last):
  File "/Users/gknight/Desktop/Benson Hill CFA/Monte_Carlo.py", line 11, in <module>
    data[ticker] = wb.DataReader(ticker, data_source = 'yahoo', start = '2022-10-10')['Adj Close**']
  File "/Users/gknight/opt/anaconda3/lib/python3.9/site-packages/pandas/util/_decorators.py", line 207, in wrapper
    return func(*args, **kwargs)
  File "/Users/gknight/opt/anaconda3/lib/python3.9/site-packages/pandas_datareader/data.py", line 370, in DataReader
    return YahooDailyReader(
  File "/Users/gknight/opt/anaconda3/lib/python3.9/site-packages/pandas_datareader/base.py", line 253, in read
    df = self._read_one_data(self.url, params=self._get_params(self.symbols))
  File "/Users/gknight/opt/anaconda3/lib/python3.9/site-packages/pandas_datareader/yahoo/daily.py", line 153, in _read_one_data
    data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
TypeError: string indices must be integers
(base) gknight@GK Benson Hill CFA %

我认为这与我的wb.DataReader有关。我已经确保了股票代码和时间的正确性。雅虎财经有“Adj Close”作为“Adj Close**”,我已经尝试了正确的拼写和大写。

jvidinwx

jvidinwx1#

您需要使用y_finance并覆盖``'pdr_override()````。因此,请将代码更改为:

import locale
import numpy as np
import pandas as pd
from pandas_datareader import data as wb
import yfinance as yf
yf.pdr_override()

import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm

ticker = "BHIL"
data = pd.DataFrame()
data[ticker] = pdr.get_data_yahoo(ticker, start = '2021-2-17')['Adj Close']
#Plot
data.plot(figsize=(15,6))

log_return = np.log(1 + data.pct_change())
#Plot
sns.distplot(log_return.iloc[1:])
plt.xlabel("Daily Return")
plt.ylabel("Frequency")

u = log_return.mean()
var = log_return.var()
drift = u - (0.5*var)

stdev = log_return.std()
days = 50
trials = 10000
Z = norm.ppf(np.random.rand(days, trials)) #days, trials
daily_returns = np.exp(drift.values + stdev.values * Z)

price_paths = np.zeros_like(daily_returns)
price_paths[0] = data.iloc[-1]
for t in range(1, days):
    price_paths[t] = price_paths[t-1]*daily_returns[t]

请注意,distplot为is a deprecated function and will be removed in seaborn v0.14.0.,因此请更新您的seaborn版本,或将distplot更改为sns.histplot(log_return.iloc[1:])以获得

相关问题