[英]Alpha Vantage API with Django - Parsing data
我正在使用 django 框架構建某種股票市場 Web 應用程序。 我從 Alpha Vantage API 獲取數據,但在解析所需數據時卡住了。
1 - 我可以成功調用 API 但在嘗試獲取所需數據時總是出錯,請查看我在views.py
上使用的代碼:
def home(request):
import requests
import json
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=B3SA3.SA&outputsize=compact&apikey=XXX"
api_request = requests.post("GET", url)
try:
api = api_request.content.json()
except Exception as e:
api="Erro, tente novamente"
return render(request,'home.html', {'api': api})
在home.html
,我使用此代碼來顯示信息還是錯誤:
{% if api %}
{% if api == "Erro, tente novamente."%}
Houve um problema com a busca da ação, tente novamente.
{% else %}
{% for key,value in api.items %}
{{key}}: {{value}}<br/>
{%endfor%}
{% endif %}
{% endif %}
使用此代碼,我得到以下信息,您可以看到有兩個單獨的字典Meta Data和Time Series (Daily) :
{ '元數據' :{'1. 信息”:“帶有拆分和股息事件的每日時間序列”,“2。 符號':'B3SA3.SA','3. 最后刷新':'2020-07-10','4。 Output 尺寸':'緊湊','5。 時區':'美國/東部'}, '時間序列(每日)' :{'2020-07-10':{'1. 打開':'58.8000','2。 高':'59.9800','3。 低':'57.6000','4。 關閉':'59.9500','5。 調整后的收盤價': '59.9500', '6. 卷':'7989500','7。 分紅金額': '0.0000', '8. 分裂系數': '1.0000'}, '2020-07-09': {'1. 打開':'60.9700','2。 高':'60.9700','3。 低':'58.4400','4。 關閉':'58.8900','5。 調整后的收盤價':'58.8900','6。 卷':'13494000','7。 分紅金額': '0.0000', '8. 分裂系數': '1.0000'}, '2020-07-08': {'1. 打開':'57.6100','2。 高':'60.8900','3。 低':'57.2300','4。 關閉':'60.6500','5。 調整后的收盤價':'60.6500','6。 卷':'13847100','7。 分紅金額': '0.0000', '8. 分裂系數': '1.0000'}, '2020-07-07': {'1. 打開':'56.5500','2。 高':'57.6000','3。 低':'56.2500','4。 關閉':'57.1700','5。 調整后的收盤價':'57.1700','6。 卷':'9038800','7。 分紅金額': '0.0000', '8. 分裂系數':'1.0000'}
我只是想獲取“時間序列(每日)”並將其解析為 dataframe 但在嘗試調用“時間序列(每日)”字典時總是出錯。
你們有什么線索我可能做錯了嗎? 提前謝謝各位!
由於您沒有訪問“Time Series Daily()”鍵,因此導致了您的錯誤。
### This is data you would receive from your API call
api = {'Meta Data': {'1. Information': 'Daily Time Series with Splits and Dividend Events', '2. Symbol': 'B3SA3.SA', '3. Last Refreshed': '2020-07-10', '4. Output Size': 'Compact', '5. Time Zone': 'US/Eastern'}, 'Time Series (Daily)': {'2020-07-10': {'1. open': '58.8000', '2. high': '59.9800', '3. low': '57.6000', '4. close': '59.9500', '5. adjusted close': '59.9500', '6. volume': '7989500', '7. dividend amount': '0.0000', '8. split coefficient': '1.0000'}, '2020-07-09': {'1. open': '60.9700', '2. high': '60.9700', '3. low': '58.4400', '4. close': '58.8900', '5. adjusted close': '58.8900', '6. volume': '13494000', '7. dividend amount': '0.0000', '8. split coefficient': '1.0000'}, '2020-07-08': {'1. open': '57.6100', '2. high': '60.8900', '3. low': '57.2300', '4. close': '60.6500', '5. adjusted close': '60.6500', '6. volume': '13847100', '7. dividend amount': '0.0000', '8. split coefficient': '1.0000'}, '2020-07-07': {'1. open': '56.5500', '2. high': '57.6000', '3. low': '56.2500', '4. close': '57.1700', '5. adjusted close': '57.1700', '6. volume': '9038800', '7. dividend amount': '0.0000', '8. split coefficient': '1.0000'}}}
# We access the Time Series dictionary from the api call.
time_series = api["Time Series (Daily)"]
# If you want to print all columns
for time, prices in time_series.items():
print(f"{time}: {prices}")
# If you want to print a specific column i.e. close prices.
for time, prices in time_series.items():
print(f"{time}: {prices['4. close']}")
現在,如果您想將此數據解析為 pandas,您可以使用 DataFrame class 中的 from_dict 方法。 請看下面的例子。
import pandas as pd
api = {'Meta Data': {'1. Information': 'Daily Time Series with Splits and Dividend Events', '2. Symbol': 'B3SA3.SA', '3. Last Refreshed': '2020-07-10', '4. Output Size': 'Compact', '5. Time Zone': 'US/Eastern'}, 'Time Series (Daily)': {'2020-07-10': {'1. open': '58.8000', '2. high': '59.9800', '3. low': '57.6000', '4. close': '59.9500', '5. adjusted close': '59.9500', '6. volume': '7989500', '7. dividend amount': '0.0000', '8. split coefficient': '1.0000'}, '2020-07-09': {'1. open': '60.9700', '2. high': '60.9700', '3. low': '58.4400', '4. close': '58.8900', '5. adjusted close': '58.8900', '6. volume': '13494000', '7. dividend amount': '0.0000', '8. split coefficient': '1.0000'}, '2020-07-08': {'1. open': '57.6100', '2. high': '60.8900', '3. low': '57.2300', '4. close': '60.6500', '5. adjusted close': '60.6500', '6. volume': '13847100', '7. dividend amount': '0.0000', '8. split coefficient': '1.0000'}, '2020-07-07': {'1. open': '56.5500', '2. high': '57.6000', '3. low': '56.2500', '4. close': '57.1700', '5. adjusted close': '57.1700', '6. volume': '9038800', '7. dividend amount': '0.0000', '8. split coefficient': '1.0000'}}}
time_series = api["Time Series (Daily)"]
# this will create a dataframe with the Dates and close prices.
# it first sets the date as the index then resets the index so that the date becomes its own column
df = pd.DataFrame.from_dict(time_series, orient="index", columns=["4. close"]).reset_index()
renamed_headers = {"index": "Date", "4. close": "Close Price"}
df = df.rename(columns=renamed_headers)
# this makes sure that your close prices are numeric.
df["Close Price"] = pd.to_numeric(df["Close Price"])
print(df)
編輯您的問題的解決方案如下:
DJANGO
# Its good practice to have imports at the top of script.
import requests
import json
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
# We will create an object and store data from alpha vantage inside this object
from collections import namedtuple
def home(request):
url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=B3SA3.SA&outputsize=compact&apikey=XXX"
api_request = requests.post("GET", url)
# this is our object that will contain the date and close price data
Security_Data = namedtuple("SecurityData", ["Date", "ClosePrice"])
# this is a list of Security_Data objects.
all_data = []
try:
api = api_request.content.json()
except Exception as e: # It's bad practice to capture a bare exception
api = None
if api is not None:
time_series = api["Time Series (Daily)"]
for time, prices in time_series.items():
data = Security_Data(time, prices["4. close"])
all_data.append(data)
return render(request, 'home.html', {'all_data': all_data})
在國內。html
{% if len(all_data) == 0 %}
Houve um problema com a busca da ação, tente novamente.
{% else %}
{% for data in all_data %}
{{data.Date}}: {{data.ClosePrice}}<br/>
{%endfor%}
{% endif %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.