Wall Street Soars as Earnings Season Kickstarts: Dow Hits Record High Amid GM and Netflix Showstoppers
# Importing required libraries
from datetime import datetime as dt
import yfinance as yf
from yfinancetools import *
import time
# Function to fetch data from Yahoo Finance API
def get_yahoo_fin_data(func, *args):
tickers = args[0]
start = args[1]
end = args[2]
if isinstance(tickers, str):
ticker = (tickers,)
else:
ticker = tickers
# Fetching data from Yahoo Finance API
df = pd.DataFrame()
for tic in ticker:
temp = yf.download(tic, start=start, end=end)['Adj Close']
df[tic] = temp
if func == 'sma':
sma_func(df)
elif func == 'ema':
ema_func(df)
# SMA function to calculate Simple Moving Average
def sma_func(df):
global df_sma
# Calculate the simple moving average over 50 and 200 days
df_sma['SMA_50'] = df.iloc[:,0].rolling(window=50).mean()
df_sma['SMA_200'] = df.iloc[:,0].rolling(window=200).mean()
# EMA function to calculate Exponential Moving Average
def ema_func(df):
global df_ema
# Calculate the exponential moving average over 20 and 100 days
df_ema['EMA_20'] = df.iloc[:,0].ewm(span=15, adjust=False).mean()
df_ema['EMA_100']= df.iloc[:,0].ewm(span=75, adjust=False).mean()
## Creating plot of moving averages
# Define the figure and axis
plt.figure(figsize=(16,8))
ax = plt.subplot(1, 1, 1)
data={'date': df_sma.index,
'50_day_Moving_average': df_sma['SMA_50'].values,
'100_day_Moving_average':df_sma['SMA_200'].values,}
df2=pd.DataFrame(data)
plt.plot(df2.date[0:5],df2['50_day_Moving_average'][0:5],'o-',label='30 day')
plt.plot(df2.date[0:5],df2['100_day_Moving_average'][0:5],'^--',label='200 day')
### Add title and labels
plt.title('Moving Averages',fontsize=20,color='black')
plt.xlabel('Date', fontsize = 16, color ='black')
plt.ylabel ('Value',fontsize = 16, color ='black')
### Add legends
plt.legend(loc="upper left", ncol=2)
plt.grid(True)
plt.show()
## Function to plot the closing price graph
# Define the function to plot the closing price graph
def plot_closing_price(start,end,*args):
stock_code=args[0]
# Fetching data from Yahoo Finance API
ticker_df = yf.download(stock_code, start=start, end=end)
fig, ax = plt.subplots()
ax.plot(ticker_df.index, ticker_df['Close'], marker='o', color='b')
ax.set_title(f'Closing Price of {stock_code}')
ax.set_xlabel('Date')
ax.set_ylabel('Price (USD)')
# Show the plot
plt.show()
## Function to get company data
# Define the function to get company data
def get_company_data(code):
ticker = yf.Ticker(code)
info = ticker.info
info['code'] = code
print(info)
## Main execution
if __name__ == "__main__":
# Define the stock codes
stock_codes = ['AAPL', 'GOOG', 'MSFT']
for code in stock_codes:
get_company_data(code)
This code has three primary functions: get_yahoo_fin_data, sma_func, and ema_func. The get_yahoo_fin_data function fetches historical data from the Yahoo Finance API based on a given ticker or list of tickers, start date and end date. It then calculates the simple moving averages (SMA) for 50 and 200 days using the SMA function. Finally, it creates a plot of these moving averages.
The SMA function takes in a pandas DataFrame and calculates the SMA over 50 and 200 days. This is saved as df_sma.
The EMA function does something similar to SMA but instead uses exponential smoothing and calculates the EMA over 20 and 100 days.
The plot_closing_price function plots the closing price graph of a given stock over a specified time period using its code as an argument.
The get_company_data function fetches company data from Yahoo Finance API for a given stock code. This includes details about the company such as its current market capitalization, sector, market cap rank etc.
Example Code Usage
# Fetching historical data
start_date='2021-01-01'
end_date='2022-12-31'
df = get_yahoo_fin_data('AAPL', start=start_date, end=end_date)
plot_closing_price(end_date,'GOOG')
get_company_data("AAPL")
This code can be used to fetch the historical data of Apple (AAPL) from Yahoo Finance API for a specified time period and then plot its closing price. This is followed by fetching company data for Apple and plotting its closing price.
Each function in this script acts independently but collectively they fetch stock prices, their moving average, create some plots etc which can be used to gain insight on financial market movements.