简体   繁体   中英

What wrong with my code? I keep getting "string indices must be integers"

I think it has to do something with my wb.DataReader . I've made sure the Ticker is correct and the time. Yahoo finance has "Adj Close" as "Adj Close**" and I've tried both with correct spelling and capitalization.

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 % 

You need to use y_finance and overide ```pdr_override()````. So chage you code to:

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]

Note that ````distplot is a deprecated function and will be removed in seaborn v0.14.0. so update your version of seaborn , or change the distplot to sns.histplot(log_return.iloc[1:]) to get在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM