Call Alpha Vantage API GET Data past it to Monte Carlo.
If you have not set up a flask and deployment follow the previous section.
For our prototype we will need data to be processed or passed to our Machine Learning or Deep Learning Model collecting data, managing data, can be very important
I will use Alpha Vantage as example and you can watch this video to get step by step on API calls
So first we’re going need to install some libraries
pip install alpha-vantagepip install pandas
Write folder called test_code and create python file called api_call_test.py.
now put this code its a small snippet of code that calls the Alpha API with API. Replace the API_KEY variable below where it says INSERT KEY HERE by with your own free API KEY at Alpha Vantage
https://www.alphavantage.co/support/#api-key
from alpha_vantage.timeseries import TimeSeries
import requests
import json
from pandas import json_normalize
import pandas as pd
# must be system path
statement='Invalid API call. Please retry or visit the documentation (https://www.alphavantage.co/documentation/) for TIME_SERIES_MONTHLY_ADJUSTED.'
def time_series_fun_monthly(key, ticker):
"""
key - API key from aplhavantage
list_of_tickers = [] list only
return dataframe
"""
url = 'https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY_ADJUSTED&symbol={}&apikey={}'.format(ticker, key)
print(url)
# url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=IBM&outputsize=full&apikey=demo&datatype=csv'
response = requests.get(url)
if response.status_code == 200:
print ('response worked!')
else:
print ('response failed!')
response_dict = response.json()
# print(response_dict)
try:
if response_dict['Error Message'] == statement:
return "Ticker is invalid said Alpha"
except:
"pass"
## validation code
try:
_, header= response.json()
except:
print("failed")
return "failed"
#Convert to pandas dataframe
df = pd.DataFrame.from_dict(response_dict[header], orient='index')
#Clean up column names
df_cols = [i.split(' ')[1] for i in df.columns]
df.columns = df_cols
df = df.reset_index(0)
df.rename(columns = {'index':'Date'}, inplace = True)
return df
# Calling & testing the function pass in your API_KEY
API_KEY = 'INSERT KEY'
df = time_series_fun_monthly(API_KEY, 'IBM')
print(df)
You should see pandas data frame printed to show stock prices out

Now we going take our test code and generalize it for the flask app by creating a folder called services this where our API call will live.

We create new python script call api_calls.py and place our test code inside
from alpha_vantage.timeseries import TimeSeries
import requests
import json
from pandas import json_normalize
import pandas as pd
def time_series_fun_monthly(key, ticker):
"""
key - API key from aplhavantage
list_of_tickers = [] list only
return dataframe
"""
url = 'https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY_ADJUSTED&symbol={}&apikey={}'.format(ticker, key)
print(url)
# url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=IBM&outputsize=full&apikey=demo&datatype=csv'
response = requests.get(url)
if response.status_code == 200:
print ('response worked!')
else:
print ('response failed!')
response_dict = response.json()
# print(response_dict)
try:
if response_dict['Error Message'] == statement:
return "Ticker is invalid said Alpha"
except:
"pass"
## validation code
try:
_, header= response.json()
except:
print("failed")
return "failed"
#Convert to pandas dataframe
df = pd.DataFrame.from_dict(response_dict[header], orient='index')
#Clean up column names
df_cols = [i.split(' ')[1] for i in df.columns]
df.columns = df_cols
df = df.reset_index(0)
df.rename(columns = {'index':'Date'}, inplace = True)
return df
Now other parts of the application can call this function for specific datasets from the stock market API
We can now pass data to model, machine learning algorithm or statistical algorithm. You can follow the next section to follow that.

[…] After you deployed your app its good idea to make it useful like deploying machine learning algorithm or deep learning model. However one thing ML and DL needs its data! so learn how to pull data from a API in the next section. […]
[…] to utilize our Monte Carlo Simulation were going need data if you skipped that section you can go back and get stock data for this model to […]