简体   繁体   English

如何制作 Pandas 数据框 for 循环(用于股票市场 API)

[英]How to make a pandas dataframe for-loop (for a stock market API)

I'm trying to get a stock data metric from an API into a Pandas Dataframe (Debt/Equity ratio for a company).我正在尝试从 API 获取股票数据指标到 Pandas 数据框(公司的债务/股权比率)。

I've been successful in getting the data for a single company, but would like to do it with several companies at a time.我已经成功地获得了一家公司的数据,但希望一次与几家公司合作。

The code I used for a single company is:我用于单个公司的代码是:

# Variables
ticker  = "AAPL" 
FMP_API = "<api_key_here>"
data    = "balance-sheet-statement"

def get_jsonparsed_data(url):
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)


# Download info from API
url = "https://financialmodelingprep.com/api/v3/"+data+"/"+ticker+"?limit=120&apikey="+FMP_API
results = get_jsonparsed_data(url)
df = json_normalize(results)

# Calculate  Debt/Equity Ratio
df[ticker] = df.totalLiabilities / df.totalStockholdersEquity
df = df[["date", ticker]].round(2)

# Convert the column Date, now in string type to a datetime type
# Make the Date Column the Index
# Creating a new dataframe with the new index and add the Date column name
# Dropp the extra Date Column
datetime_series = pd.to_datetime(df['date'])
datetime_index = pd.DatetimeIndex(datetime_series.values)
df = df.set_index(datetime_index).rename_axis('date', axis=1)
df.drop('date',axis=1,inplace=True)

df.head()

The result I get is:我得到的结果是:

date        AAPL
2020-09-26  3.96
2019-09-28  2.74
2018-09-29  2.41
2017-09-30  1.80
2016-09-24  1.51

date
AAPL    float64
dtype: object

What I would like to get is:我想得到的是:

ticker  = ["AAPL", "FB", "GOOG", "AMZN"]

date        AAPL   FB   GOOG  AMZN
2020-09-26  3.96  0.24  0.44  2.44
2019-09-28  2.74  0.32  0.37  2.63
2018-09-29  2.41  0.16  0.31  2.73
2017-09-30  1.80  0.14  0.29  3.74
2016-09-24  1.51  0.10  0.20  3.32

date
AAPL    float64
FB      float64
GOOG    float64
AMZN    float64
dtype: object

I tried using a for loop, but i keep writing over the same dataframe and can only get the values for the last ticker in the list.我尝试使用 for 循环,但我一直在同一个数据帧上写入数据,并且只能获取列表中最后一个代码的值。

Use pandas merge to merge two of the same dataframes with different tickers by the same index.使用 pandas merge将两个相同的数据帧与相同索引的不同代码合并。

You can also simplify your code where you set the date as the index:您还可以简化将日期设置为索引的代码:

df.date = pd.to_datetime(df['date'])
df = df.set_index(date)

Found the anwser.找到了答案。

The idea is to create an empty list and a for loop.这个想法是创建一个空列表和一个 for 循环。

Each loop gets the data from one ticker and in the end we make a dataframe by concatenating the list.每个循环从一个股票代码中获取数据,最后我们通过连接列表来制作一个数据框。

Here is the code:这是代码:

FMP_API = "<api_code_here>"

data    = "balance-sheet-statement"
tickers = ['AAPL', 'MSFT']
     
df_list = []
     
for ticker in tickers:
    url = "https://financialmodelingprep.com/api/v3/" + data + "/" + ticker + "?limit=120&apikey=" + FMP_API
    df = pd.read_json(url)
    df.set_index('date', inplace=True)
     
    df[ticker] = df.totalLiabilities / df.totalStockholdersEquity
    df_list.append(df[ticker])
     
df_final = pd.concat(df_list, axis=1)
print(df_final)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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