Preface: In this video series Matt shows how to use the EODHD Financial APIs for the Stock Analysis with Python.

Don’t forget to explore other 2 Parts to learn more:
Part 1 Obtaining Stocks Data for the Analysis in Python
Part 2 Processing Stocks Data in Python for the Analysis
Part 3 Filtering and visualizing the Stocks Data Analysis results in Python

Register & Get Data

import datetime as dt
from eod import EodHistoricalData
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import requests

DEFAULT_DATE = dt.date.today() - dt.timedelta(396)
TODAY =dt.date.today()

def plot_performance(folder):
    """
    returns figure containing relative performance of all securities in folder
    """
    files = [file for file in os.listdir(folder) if not file.startswith('0')]
    fig, ax = plt.subplots(math.ceil(len(files)/ 4), 4, figsize=(16,16))
    count = 0
    for row in range(math.ceil(len(files)/ 4)):
        for column in range(4):
            try:
                data = pd.read_csv(f"{folder}/{files[count]}")['close']
                data = (data/data[0] -1) * 100
                ax[row,column].plot(data, label= files[count][:-4])
                ax[row,column].legend()
                ax[row,column].yaxis.set_major_formatter(mtick.PercentFormatter())
                ax[row,column].axhline(0, c='r', ls='--')
            except:
                pass
            count +=1
    plt.show()  

def main():
    key = open('api_token.txt').read()
    plot_performance('energy')

if __name__ == '__main__':
    main()
import datetime as dt
from eod import EodHistoricalData
import json
import math
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
import os
import pandas as pd
import requests

DEFAULT_DATE = dt.date.today() - dt.timedelta(396)
TODAY =dt.date.today()

def get_earnings(key):
    """
    returns list of tickers for companies reporting in the next week
    """
    client =EodHistoricalData(key)
    eps = pd.DataFrame(client.get_calendar_earnings())
    symbols =[]

    for row in range(len(eps)):
        if eps.earnings.iloc[row]['code'].endswith('US'):
            symbols.append(eps.earnings[row]['code'][:-3])
    print(f"There are {len(symbols)} companies reporting this week")
    return symbols        


def get_dividends(key, exchange ='US', date= dt.date.today()):
    """
    returns securities with specific ex-date
    """
    client = EodHistoricalData(key)
    data = pd.DataFrame(client.get_bulk_markets(exchange= exchange,
                        date= date, type_='dividends'))
    return data                    

def main():
    key = open('api_token.txt').read()
    print(get_earnings(key))
    print(get_dividends(key ))

if __name__ == '__main__':
    main()
import datetime as dt
from eod import EodHistoricalData
import json
import math
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
import os
import pandas as pd
import requests

DEFAULT_DATE = dt.date.today() - dt.timedelta(396)
TODAY =dt.date.today()

def screen_example(symbols, key):
    """
    Returns DataFrame with current price, 52-week high and ratio 
    of high to current price. Symbols is list-like
    """
    high = {}
    call = f"https://eodhistoricaldata.com/api/eod-bulk-last-day/US?api_token={key}&fmt=json"
    data = pd.DataFrame(requests.get(call).json())
    data.reset_index(drop=True)

    client = EodHistoricalData(key)
    for ticker in symbols:
        try:
            high[ticker] = client.get_fundamental_equity(f"{ticker}.US")['Technicals']['52WeekHigh']
            print(f"fetching {ticker}")
        except:
            print(f"{ticker} not available skipping")
        finally:
            print(f"All available data downloaded")
    mask = data.code.isin(symbols)
    prices = data[['code', 'close']][mask]
    high = pd.Series(high, name='high')
    prices = prices.merge(high, right_on=high.index, left_on ='code')
    prices['ratio'] = prices['close'] / prices['high']
    return prices            

def main():
    key = open('api_token.txt').read()
    sp = get_sp()[:10]
    print(screen_example(sp,key))

if __name__ == '__main__':
    main()
from eod import EodHistoricalData
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
import os
import pandas as pd
import seaborn as sb
sb.set_theme()

DEFAULT_DATE = dt.date.isoformat(dt.date.today() - dt.timedelta(396))


class Stock:
    def __init__(self, symbol, key, date =DEFAULT_DATE, folder=None):
        self.symbol = symbol
        self.key = key
        self.date = date
        self.folder = folder
        self.data = self.get_data()


    def get_data(self):
        available_data = [filename[:-4] 
        for filename in os.listdir(self.folder) if not filename.startswith('0')]
        if self.symbol in available_data:
            data = pd.read_csv(f"{self.folder}/{self.symbol}.csv", 
                                index_col='date').round(2)
        else:
            client = EodHistoricalData(self.key)
            data = pd.DataFrame(client.get_prices_eod(self.symbol,
                                from_=self.date)).round(2)
            data.index = pd.DatetimeIndex(data.date).date
            data.drop(columns=['date'], inplace = True)

        return data   

def main():
    KEY = open('api_token.txt').read()
    test = Stock(symbol='AAPL', key=KEY)
    print(test.data)

if __name__ == '__main__':
    main()
from eod import EodHistoricalData
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
import os
import pandas as pd
import seaborn as sb
sb.set_theme()

DEFAULT_DATE = dt.date.isoformat(dt.date.today() - dt.timedelta(396))

class Stock:
    def __init__(self, symbol, key, date =DEFAULT_DATE, folder=None):
        self.symbol = symbol
        self.key = key
        self.date = date
        self.folder = folder
        self.data = self.get_data()


    def get_data(self):
        available_data = [filename[:-4] 
        for filename in os.listdir(self.folder) if not filename.startswith('0')]
        if self.symbol in available_data:
            data = pd.read_csv(f"{self.folder}/{self.symbol}.csv", 
                                index_col='date').round(2)
        else:
            client = EodHistoricalData(self.key)
            data = pd.DataFrame(client.get_prices_eod(self.symbol,
                                from_=self.date)).round(2)
            data.index = pd.DatetimeIndex(data.date).date
            data.drop(columns=['date'], inplace = True)
            self.calc_vol(data)
        return data

def calc_vol(self, df):
        df['returns'] = np.log(df.close).diff().round(4)
        df['volatility'] = df.returns.rolling(21).std().round(4)
        df['change'] = df['close'].diff()
        df['hi_low_spread'] = ((df['high'] -df['low']) / df['open']).round(2)
        df['exp_change'] = (df.volatility * df.close.shift(1)).round(2)
        df['magnitude'] = (df.change / df.exp_change).round(2)
        df['abs_magnitude'] = np.abs(df.magnitude)
        df.dropna(inplace= True)

    def plot_return_dist(self):
        start = self.data.index[0]
        end  = self.data.index[-1]
        plt.hist(self.data['returns'], bins=20, edgecolor='w')
        plt.suptitle(f"Distribution of returns for {self.symbol}", fontsize=14)
        plt.title(f"From {start} to {end}", fontsize=12)
        plt.show()  

def main():
    KEY = open('api_token.txt').read()
    test = Stock(symbol='AAPL', key=KEY)
    print(test.data)
    test.plot_return_dist()

if __name__ == '__main__':
    main()
from eod import EodHistoricalData
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
import os
import pandas as pd
import seaborn as sb
sb.set_theme()

DEFAULT_DATE = dt.date.isoformat(dt.date.today() - dt.timedelta(396))

class Stock:
    def __init__(self, symbol, key, date =DEFAULT_DATE, folder=None):
        self.symbol = symbol
        self.key = key
        self.date = date
        self.folder = folder
        self.data = self.get_data()


    def get_data(self):
        available_data = [filename[:-4] 
        for filename in os.listdir(self.folder) if not filename.startswith('0')]
        if self.symbol in available_data:
            data = pd.read_csv(f"{self.folder}/{self.symbol}.csv", 
                                index_col='date').round(2)
        else:
            client = EodHistoricalData(self.key)
            data = pd.DataFrame(client.get_prices_eod(self.symbol,
                                from_=self.date)).round(2)
            data.index = pd.DatetimeIndex(data.date).date
            data.drop(columns=['date'], inplace = True)
            self.calc_vol(data)
        return data

    def calc_vol(self, df):
        df['returns'] = np.log(df.close).diff().round(4)
        df['volatility'] = df.returns.rolling(21).std().round(4)
        df['change'] = df['close'].diff()
        df['hi_low_spread'] = ((df['high'] -df['low']) / df['open']).round(2)
        df['exp_change'] = (df.volatility * df.close.shift(1)).round(2)
        df['magnitude'] = (df.change / df.exp_change).round(2)
        df['abs_magnitude'] = np.abs(df.magnitude)
        df.dropna(inplace= True)

    def plot_return_dist(self):
        start = self.data.index[0]
        end  = self.data.index[-1]
        plt.hist(self.data['returns'], bins=20, edgecolor='w')
        plt.suptitle(f"Distribution of returns for {self.symbol}", fontsize=14)
        plt.title(f"From {start} to {end}", fontsize=12)
        plt.show()

    def plot_volatility(self):
        start = self.data.index[0]
        end  = self.data.index[-1]
        plt.scatter(self.data['returns'], self.data['abs_magnitude'])
        plt.axhline(0, c='r', ls='--')
        plt.axvline(0, c='r', ls='--')
        plt.suptitle(f"Volatility of returns for {self.symbol}", fontsize=14)
        plt.title(f"From {start} to {end}", fontsize=12)
        plt.show()

    def plot_performance(self):
        start = self.data.index[0]
        end  = self.data.index[-1]
        plt.plot((self.data.close / self.data.close[0] - 1) * 100)
        plt.axhline(0, c='r', ls='--')
        plt.suptitle(f"Volatility of returns for {self.symbol}", fontsize=14)
        plt.title(f"From {start} to {end}", fontsize=12)
        plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter())
        plt.show()    

def main():
    KEY = open('api_token.txt').read()
    test = Stock(symbol='AAPL', key=KEY)
    test.plot_volatility()
    test.plot_performance()

if __name__ == '__main__':
    main()

Register & Get Data

Do you enjoy our articles?

We can send new ones right to your email box