我刚刚开始在 Jupyter 上编写 python 代码,但似乎无法解决这个问题。 我试图从雅虎财经导入数据,但它不允许我这样做。我不知道是否必须安装新版本的 Pandas,因为我已经安装了。也许和功能老旧有关,我不知道。
这是代码和错误消息:
import numpy as np
import pandas as pd
from pandas_datareader import data as wb
PG = wb.DataReader('Pg', data_source='yahoo', start='1995-1-1')
上面代码行的错误:
TypeError Traceback (most recent call last)
Cell In[3], line 1
----> 1 PG = wb.DataReader('Pg', data_source='yahoo', start='1995-1-1')
File ~/anaconda3/lib/python3.11/site-packages/pandas/util/_decorators.py:213, in deprecate_kwarg.<locals>._deprecate_kwarg.<locals>.wrapper(*args, **kwargs)
211 raise TypeError(msg)
212 kwargs[new_arg_name] = new_arg_value
--> 213 return func(*args, **kwargs)
File ~/anaconda3/lib/python3.11/site-packages/pandas_datareader/data.py:379, 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 ~/anaconda3/lib/python3.11/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 ~/anaconda3/lib/python3.11/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, not 'str'
一般来说,我使用
yfinance
雅虎财经模块,可以在这里找到:https://pypi.org/project/yfinance
我发现API更方便。
这是我开始的一些样板:
import yfinance as yf
import pprint
def main():
yhoo_object = yf.Ticker("MSFT")
print(yhoo_object.dividends)
pprint.pp(yhoo_object.info['longName'])
print('the sum of the dividends are: ', sum(yhoo_object.dividends))
last_price = round(yhoo_object.history(period='1m')['Close'][0] , 1)
print('the last price: ', last_price)
print(type(last_price))
tickers = yf.Tickers('msft aapl goog')
print(tickers.tickers)
# for i in tickers.tickers:
# last_price = round(i.history(period='1m')['Close'][0] , 1)
# print(f'the mast price for {i} is {last_price} ')
# pass
# return
def get_data_from_yhoo(yhoo_object):
'''
example of things that the user can get back from yahoo.
A lot of the values return type is pandas data series.
inputs:
yhoo_object (yfinance.ticker.Ticker):
'''
# get stock info
yhoo_object.info
# get historical market data
hist = yhoo_object.history(period="max")
# show actions (dividends, splits)
yhoo_object.actions
# show dividends
yhoo_object.dividends
# show splits
yhoo_object.splits
# show financials
yhoo_object.financials
yhoo_object.quarterly_financials
# show major holders
yhoo_object.major_holders
# show institutional holders
yhoo_object.institutional_holders
# show balance sheet
yhoo_object.balance_sheet
yhoo_object.quarterly_balance_sheet
# show cashflow
yhoo_object.cashflow
yhoo_object.quarterly_cashflow
# show earnings
yhoo_object.earnings
yhoo_object.quarterly_earnings
# show sustainability
yhoo_object.sustainability
# show analysts recommendations
yhoo_object.recommendations
# show next event (earnings, etc)
yhoo_object.calendar
# show ISIN code - *experimental*
# ISIN = International Securities Identification Number
yhoo_object.isin
# show options expirations
yhoo_object.options
# get option chain for specific expiration
# opt = yhoo_object.option_chain('YYYY-MM-DD')
# data available via: opt.calls, opt.puts
if __name__=='__main__':
''' This is executed when run from the command line '''
main()
但是我们还可以做很多其他事情。