我目前正在尝试使用pandas从yfinance获取数据,这是我下面的代码:
import pandas as pd
import numpy as np
from pyhhmm.gaussian import GaussianHMM
from pandas_datareader.data import DataReader
import matplotlib.pyplot as plt
start_date = "2017-01-01"
end_date = "2023-01-04"
symbol = "SPY"
data = DataReader(name=symbol, data_source= "yahoo", start=start_date, end=end_date)
data
我已经使用pip安装了所有的包,但是当我调用data变量时,它会抛出一个错误和异常。
我很感激你的帮助。
抛出的错误如下:
TypeError Traceback (most recent call last)
Input In [4], in <cell line: 8>()
6 api = ""
7 session = ""
----> 8 data = DataReader(name=symbol, data_source= "yahoo", start=start_date, end=end_date)
9 data.head()
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas/util/_decorators.py:207, in deprecate_kwarg.<locals>._deprecate_kwarg.<locals>.wrapper(*args, **kwargs)
205 else:
206 kwargs[new_arg_name] = new_arg_value
--> 207 return func(*args, **kwargs)
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas_datareader/data.py:370, in DataReader(name, data_source, start, end, retry_count, pause, session, api_key)
367 raise NotImplementedError(msg)
369 if data_source == "yahoo":
--> 370 return YahooDailyReader(
371 symbols=name,
372 start=start,
373 end=end,
374 adjust_price=False,
375 chunksize=25,
376 retry_count=retry_count,
377 pause=pause,
378 session=session,
379 ).read()
381 elif data_source == "iex":
382 return IEXDailyReader(
383 symbols=name,
384 start=start,
(...)
390 session=session,
391 ).read()
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas_datareader/base.py:253, in _DailyBaseReader.read(self)
251 # If a single symbol, (e.g., 'GOOG')
252 if isinstance(self.symbols, (string_types, int)):
--> 253 df = self._read_one_data(self.url, params=self._get_params(self.symbols))
254 # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
255 elif isinstance(self.symbols, DataFrame):
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas_datareader/yahoo/daily.py:153, in YahooDailyReader._read_one_data(self, url, params)
151 try:
152 j = json.loads(re.search(ptrn, resp.text, re.DOTALL).group(1))
--> 153 data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
154 except KeyError:
155 msg = "No data fetched for symbol {} using {}"
TypeError: string indices must be integers
def wordInSymbs(str):
list = []
for i in range(len(str)):
list.append(str[i])
return list
n = int(input())
parts = []
numbers = []
listOfCounts = [0]
for i in range(n):
parts.append(wordInSymbs(input()))
m = int(input())
listOfCounts = [0]*m
for i in range(m):
numbers.append(wordInSymbs(input()))
for j in range(len(parts)):
if set(parts[j]) <= set(numbers[i]):
listOfCounts[i] += 1
for i in range(m):
if listOfCounts[i] == max(listOfCounts):
print(''.join(numbers[i]))
n = int(input())
str = ''
for i in range(n):
str += 'r, y, g'
if (i + 1) != n:
str += ', y, '
print(str.count('r'), str.count('y'))
'cut'
from sys import stdin
option = input()
list = []
for line in stdin:
if line.rstrip() == 'Exit':
break
newline = line.split()
list.append(newline)
if option[:-1] == '-c':
s = int(option[-1])-1
for i in range(len(list)):
print(list[i][s])
else:
for i in range(len(list)):
print('t'.join(list[i]), end='n')
正如评论中所述,雅虎财经分享历史数据的方式发生了变化(它被加密了),这破坏了panda_datareader
软件包试图访问这些数据的方式。这导致了OP看到的问题。这个变化已经在这个Pull Request中修复了,尽管它还没有被合并并作为pandas_datareader
的新版本发布。目前,可以使用带有修复程序的a版本,并通过以下命令直接安装:
pip install git+https://github.com/hellc/pandas-datareader.git@87dda3f297df8f4b3253c6f2d5006b5ac43a9150