Skip to content

Instantly share code, notes, and snippets.

View intandeay's full-sized avatar

Intan Dea Yutami intandeay

View GitHub Profile
@intandeay
intandeay / SA_returnFunctions.py
Created October 11, 2020 22:03
Stock Analysis - Return Functions
def nearest(dates, dateRef):
# Get the previous days before the reference date (dateRef)
prevDate = dates[dates < dateRef]
return prevDate[-1] # return the last date
def getReturn(period, number, ticker, dt, val):
# Subset the dataset by stock index
df = msi.loc[msi.ticker == ticker].reset_index()
# Get all business days
existingDates = df['Date'].unique()
@intandeay
intandeay / SA_getLastDate.py
Created October 11, 2020 22:01
Stock Analysis - Get Last date (30 Sep)
lastDate = msi.loc[msi.Date == '2020-09-30'].reset_index().drop(['index'],axis=1)
@intandeay
intandeay / SA_plotChBegin.py
Created October 11, 2020 22:00
Stock Analysis - Plot Change to 4 Jan 10
fig, axes = plt.subplots(3,2, figsize=(12, 8),sharex=True)
pagoda = ["#965757", "#D67469", "#4E5A44", "#A1B482", '#EFE482', "#99BFCF"] # for coloring
for i, k in enumerate(region_idx.keys()):
# Iterate for each region
ax = axes[int(i/2), int(i%2)]
for j,t in enumerate(region_idx[k]):
# Iterate and plot for each stock index in this region
ax.plot(chBegin.index, chBegin[t], marker='', linewidth=1, color = pagoda[j])
ax.legend([ticker[t] for t in region_idx[k]], loc='upper left', fontsize=7)
ax.set_title(k, fontweight='bold')
@intandeay
intandeay / SA_chBeginColumn.py
Created October 11, 2020 21:59
Stock Analysis - Change Begin Columnwise
# Transform the data to be ticker column-wise
chBegin = msi.groupby(['Date', 'ticker'])['chBegin'].first().unstack()
# Fill null values with the values on the row before
chBegin = chBegin.fillna(method='bfill')
@intandeay
intandeay / SA_priceChangeBegin.py
Last active October 11, 2020 21:58
Stock Analysis - Get Price Change to 4 Jan 2010
# Get the data for 4 Jan 2010
begRef = msi.loc[msi.Date == '2010-01-04']
def retBegin(ticker, val):
start_val = begRef.loc[begRef.ticker == ticker, 'Close'].values[0]
return (val/start_val - 1) * 100
msi['chBegin'] = msi.apply(lambda x: retBegin(x.ticker, x.Close), axis = 1)
@intandeay
intandeay / SA_regionIdx.py
Created October 11, 2020 21:56
Stock Analysis - Region Index
region_idx=
{ 'US & Canada' : ['^GSPC', '^DJI', '^IXIC', '^RUT','^GSPTSE'],
'Latin America' : ['^BVSP', '^MXX', '^IPSA'],
'East Asia' : ['^N225', '^HSI', '000001.SS', '399001.SZ', '^TWII', '^KS11'],
'ASEAN & Oceania' : ['^STI', '^JKSE', '^KLSE','^AXJO', '^NZ50'],
'South & West Asia' : ['^BSESN', '^TA125.TA'],
'Europe' : ['^FTSE', '^GDAXI', '^FCHI', '^STOXX50E','^N100', '^BFX']
}
@intandeay
intandeay / SA_getHistoricalData.py
Created October 11, 2020 21:54
Stock Analysis - Retrieve Historical Data
stock_list = []
for s in majorStockIdx.Symbol: # iterate for every stock indices
# Retrieve data from Yahoo! Finance
tickerData = yf.Ticker(s)
tickerDf1 = tickerData.history(period='1d', start='2010-1-1', end='2020-9-30')
# Save historical data
tickerDf1['ticker'] = s # don't forget to specify the index
stock_list.append(tickerDf1)
# Concatenate all data
msi = pd.concat(stock_list, axis = 0)
@intandeay
intandeay / SA_getMajorStockIdxs.py
Created October 11, 2020 21:52
Stock Analysis - Get World Major Stock Indices
# Retrieving List of World Major Stock Indices from Yahoo! Finance
df_list = pd.read_html('https://finance.yahoo.com/world-indices/')
majorStockIdx = df_list[0]
majorStockIdx.head()
@intandeay
intandeay / stockAnalysis_import.py
Created October 11, 2020 21:49
Stock Analysis - Importing Modules
!pip install yfinance # install yfinance
# importing needed libraries/modules
import numpy as np
import pandas as pd
import yfinance as yf