0
   import pandas as pd
import datetime as dt
from pandas_datareader import data as web
import yfinance as yf
yf.pdr_override()

文件名=r'C:\Users\User\Desktop\from_python\data_from_python.xlsx'

yeah = pd.read_excel(filename, sheet_name='entry')
stock = []

stock = list(yeah['name'])
stock = [ s.replace('\xa0', '') for s in stock if not pd.isna(s) ]


adj_close=pd.DataFrame([])
high_price=pd.DataFrame([])
low_price=pd.DataFrame([])
volume=pd.DataFrame([])

print(stock)


['^GSPC', 'NQ=F', 'AAU', 'ALB', 'AOS', 'APPS', 'AQB', 'ASPN', 'ATHM', 'AZRE', 'BCYC', 'BGNE', 'CAT', 'CC', 'CLAR', 'CLCT', 'CMBM', 'CMT', 'CRDF', 'CYD', 'DE', 'DKNG', 'EARN', 'EMN', 'FBIO', 'FBRX', 'FCX', 'FLXS', 'FMC', 'FMCI', 'GME', 'GRVY', 'HAIN', 'HBM', 'HIBB', 'IEX', 'IOR', 'KFS', 'MAXR', 'MPX', 'MRTX', 'NSTG', 'NVCR', 'NVO', 'OESX', 'PENN', 'PLL', 'PRTK', 'RDY', 'REGI', 'REKR', 'SBE', 'SQM', 'TCON', 'TCS', 'TGB', 'TPTX', 'TRIL', 'UEC', 'VCEL', 'VOXX', 'WIT', 'WKHS', 'XNCR']

for symbol in stock:
    adj_close[symbol] = web.get_data_yahoo([symbol],start,end)['Adj Close']

我有一个股票代码列表,我有调整收盘价,如何获得这些股票代码名称和行业?

对于我在网上找到的单个股票代码,可以像下面这样完成

sbux = yf.Ticker("SBUX")
tlry = yf.Ticker("TLRY")

print(sbux.info['sector'])
print(tlry.info['sector'])

我怎样才能做到这一点,dataframe因为我可以将数据放入 excel 中,就像我为adj价格所做的那样。

非常感谢!

4

2 回答 2

0

它同时处理股票和行业。但是,有些股票没有板块,所以增加了错误对策。由于问题列名称由部门和问题名称组成,我们将其更改为分层列并更新检索到的数据框。最后,我将其保存为 CSV 格式以将其导入 Excel。由于股票数量较多,我只尝试了一些股票,因此可能存在一些问题。

import datetime

import pandas as pd
import yfinance as yf
import pandas_datareader.data as web

yf.pdr_override()

start = "2018-01-01"
end = "2019-01-01"

# symbol = ['^GSPC', 'NQ=F', 'AAU', 'ALB', 'AOS', 'APPS', 'AQB', 'ASPN', 'ATHM', 'AZRE', 'BCYC', 'BGNE', 'CAT', 
#'CC', 'CLAR', 'CLCT', 'CMBM', 'CMT', 'CRDF', 'CYD', 'DE', 'DKNG', 'EARN', 'EMN', 'FBIO', 'FBRX', 'FCX', 'FLXS', 
#'FMC', 'FMCI', 'GME', 'GRVY', 'HAIN', 'HBM', 'HIBB', 'IEX', 'IOR', 'KFS', 'MAXR', 'MPX', 'MRTX', 'NSTG', 'NVCR',
#'NVO', 'OESX', 'PENN', 'PLL', 'PRTK', 'RDY', 'REGI', 'REKR', 'SBE', 'SQM', 'TCON', 'TCS', 'TGB', 'TPTX', 'TRIL', 
#'UEC', 'VCEL', 'VOXX', 'WIT', 'WKHS', 'XNCR']
stock = ['^GSPC', 'NQ=F', 'AAU', 'ALB', 'AOS', 'APPS']

adj_close = pd.DataFrame([])

for symbol in stock:
    try:
        sector = yf.Ticker(symbol).info['sector']
        name = yf.Ticker(symbol).info['shortName']
    except:
        sector = 'None'
        name = 'None'
    adj_close[sector, symbol] = web.get_data_yahoo(symbol, start=start, end=end)['Adj Close']
idx = pd.MultiIndex.from_tuples(adj_close.columns)
adj_close.columns = idx
adj_close.head()

                    None    Basic Materials Industrials Technology
            ^GSPC_None  NQ=F_None   AAU_None    ALB_Albemarle Corporation   AOS_A.O. Smith Corporation  APPS_Digital Turbine, Inc.
2018-01-02  2695.810059 6514.75 1.03    125.321663  58.657742   1.79
2018-01-03  2713.060059 6584.50 1.00    125.569397  59.010468   1.87
2018-01-04  2723.989990 6603.50 0.98    124.073502  59.286930   1.86
2018-01-05  2743.149902 6667.75 1.00    125.502716  60.049587   1.96
2018-01-08  2747.709961 6688.00 0.95    130.962250  60.335583   1.96


# for excel 
adj_close.to_csv('stock.csv', sep=',')
于 2020-09-19T09:32:08.180 回答
0

您可以使用名为yahooquery的包尝试此答案。免责声明:我是包的作者。

from yahooquery import Ticker
import pandas as pd

symbols = ['^GSPC', 'NQ=F', 'AAU', 'ALB', 'AOS', 'APPS', 'AQB', 'ASPN', 'ATHM', 'AZRE', 'BCYC', 'BGNE', 'CAT', 'CC', 'CLAR', 'CLCT', 'CMBM', 'CMT', 'CRDF', 'CYD', 'DE', 'DKNG', 'EARN', 'EMN', 'FBIO', 'FBRX', 'FCX', 'FLXS', 'FMC', 'FMCI', 'GME', 'GRVY', 'HAIN', 'HBM', 'HIBB', 'IEX', 'IOR', 'KFS', 'MAXR', 'MPX', 'MRTX', 'NSTG', 'NVCR', 'NVO', 'OESX', 'PENN', 'PLL', 'PRTK', 'RDY', 'REGI', 'REKR', 'SBE', 'SQM', 'TCON', 'TCS', 'TGB', 'TPTX', 'TRIL', 'UEC', 'VCEL', 'VOXX', 'WIT', 'WKHS', 'XNCR']

# Create Ticker instance, passing symbols as first argument
# Optional asynchronous argument allows for asynchronous requests
tickers = Ticker(symbols, asynchronous=True)

data = tickers.get_modules("summaryProfile quoteType")
df = pd.DataFrame.from_dict(data).T

# flatten dicts within each column, creating new dataframes
dataframes = [pd.json_normalize([x for x in df[module] if isinstance(x, dict)]) for module in ['summaryProfile', 'quoteType']]

# concat dataframes from previous step
df = pd.concat(dataframes, axis=1)

# View columns
df.columns
Index(['address1', 'address2', 'city', 'state', 'zip', 'country', 'phone',
       'fax', 'website', 'industry', 'sector', 'longBusinessSummary',
       'fullTimeEmployees', 'companyOfficers', 'maxAge', 'exchange',
       'quoteType', 'symbol', 'underlyingSymbol', 'shortName', 'longName',
       'firstTradeDateEpochUtc', 'timeZoneFullName', 'timeZoneShortName',
       'uuid', 'messageBoardId', 'gmtOffSetMilliseconds', 'maxAge'],
      dtype='object')

# Data you're looking for
df[['symbol', 'shortName', 'sector']].head(10)
      symbol                      shortName                  sector
0  NQZ20.CME              Nasdaq 100 Dec 20                     NaN
1        ALB          Albemarle Corporation         Basic Materials
2        AOS         A.O. Smith Corporation             Industrials
3       ASPN           Aspen Aerogels, Inc.             Industrials
4        AAU         Almaden Minerals, Ltd.         Basic Materials
5      ^GSPC                        S&P 500                     NaN
6       ATHM                  Autohome Inc.  Communication Services
7        AQB  AquaBounty Technologies, Inc.      Consumer Defensive
8       APPS          Digital Turbine, Inc.              Technology
9       BCYC       Bicycle Therapeutics plc              Healthcare

于 2020-09-19T14:59:37.253 回答