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
import datetime as dt
from eod import EodHistoricalData
import json
import os
import pandas as pd
import requests
DEFAULT_DATE = dt.date.today() - dt.timedelta(396)
TODAY =dt.date.today()
def get_closing_prices(folder= 'data_files', adj_close= False):
"""
returns file with closing prices for selected securities
"""
files = [file for file in os.listdir(folder) if not file.startswith('0')]
closes = pd.DataFrame()
for file in files:
if adj_close:
df = pd.DataFrame(pd.read_csv(f"{folder}/{file}",
index_col = 'date')['adjusted_close'])
df.rename(columns={'adjusted_close': file[:-4]}, inplace=True)
else:
df = pd.DataFrame(pd.read_csv(f"{folder}/{file}",
index_col = 'date')['close'])
df.rename(columns={'close': file[:-4]}, inplace=True)
if closes.empty:
closes = df
else:
closes = pd.concat([closes, df], axis = 1)
closes.to_csv(f"{folder}/0-closes.csv")
return closes
def main():
key = open('api_token.txt').read()
get_closing_prices(folder='energy')
if __name__ == '__main__':
main()
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 returns_from_closes(folder, filename):
"""
returns instantaneous returns for selected securities
"""
try:
data = pd.read_csv(f"{folder}/{filename}", index_col=['date'])
except Exception as e:
print(f"There was a problem: {e}")
return np.log(data).diff().dropna()
def get_corr(data):
"""
returns correl from securities
"""
return data.corr()
def plot_closes(closes, relative=False):
"""
plot absolute or relative closes for securities
"""
if closes.endswith('.csv'):
closes = pd.read_csv(closes, index_col=['date'])
else:
closes = pd.read_excel(closes, index_col=['date'])
if relative:
relative_change = closes / closes.iloc[0] - 1
relative_change.plot()
plt.axhline(0, c='r', ls='--')
plt.grid(axis='y')
plt.show()
else:
closes.plot()
plt.grid(axis='y')
plt.show()
def main():
key = open('api_token.txt').read()
print(returns_from_closes('energy', '0-closes.csv'))
print(get_corr(returns_from_closes('energy','0-closes.csv')))
plot_closes(closes='mine/0-closes.csv',relative=True)
if __name__ == '__main__':
main()
def get_return_data(*tickers, date=DEFAULT_DATE, adj_close=False, key):
"""
saves closes and returns out to excel file named returns
"""
client = EodHistoricalData(key)
temp = pd.DataFrame()
for ticker in tickers:
try:
if adj_close:
temp[ticker] = pd.DataFrame(client.get_prices_eod(ticker,
from_=date))['adjusted_close']
else:
temp[ticker] = pd.DataFrame(client.get_prices_eod(ticker,
from_=date))['close']
except Exception as e:
print(f"{ticker} had a problem: {e}")
data = temp
data_instanteous = np.log(data).diff().dropna()
data_pct = data.pct_change()
with pd.ExcelWriter('returns.xlsx', datetime_format='yyyy-mm-dd') as writer:
data.to_excel(writer, sheet_name='closes')
data_instanteous.to_excel(writer, sheet_name='returns')
data_pct.to_excel(writer, sheet_name='pct change')
print(f"Data retrieved and saved to returns.xlsx in {os.getcwd()}")
return data, data_instanteous, data_pct
def main():
key = open('api_token.txt').read()
tickers = "AAPL AMZN GOOG NVDA".split()
returns = get_return_data(*tickers, key=key)
print(returns[0])
if __name__ == '__main__':
main()