How to call Alpha Vantage API Data 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-vantage
pip 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

dataframes

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.

services_folder

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.

Discover more from lesliemwubbel

Subscribe now to keep reading and get access to the full archive.

Continue reading