Skip to content

Instantly share code, notes, and snippets.

@debpu06
Created September 26, 2023 00:24
Show Gist options
  • Save debpu06/efa809ffabbe03d34838bbad21f808a5 to your computer and use it in GitHub Desktop.
Save debpu06/efa809ffabbe03d34838bbad21f808a5 to your computer and use it in GitHub Desktop.
import pandas as pd
import os
# Sample code to calculate the Beta coefficient; Assume we have the following 9 weeks prices for a stock and the market index
Stock_WeeklyPrice = [20,35,40,37,22,34,55,35,42]
Market_WeeklyPrice = [300, 340, 400, 320, 200, 300, 500, 380, 400]
def calculate_beta(stock_weekly_price, market_weekly_price):
# A useful code to calculate the percentage change within a series is called np.Series.pct_change()
# It returns the percentage change between the current and a prior element, which can be seen as (P_t / P_(t-1))-100%
PC_stock = pd.Series(stock_weekly_price).pct_change().dropna()
PC_market = pd.Series(market_weekly_price).pct_change().dropna()
Return_stock = np.log(PC_stock+1)
Return_market = np.log(PC_market+1)
# Calculate the first month's beta coefficient (use the first 4 weekly price changes )
# You can use the command np.cov to obtain the covariance and the variance for these two stocks
cov_matrix = np.cov(Return_stock[0:4], Return_market[0:4])
beta_month1 = cov_matrix[0,1] / cov_matrix[1,1]
return beta_month1
def to_float_list(series):
result = []
for value in series:
if isinstance(value, float) or isinstance(value, int):
result.append(value)
else:
result.append(float(value.replace(',', '')))
return result
def q4():
df = pd.read_csv("StockPrice_5Year_Weekly.csv")
index = 0
end_index = 4
johnson_betas = []
pfizer_betas = []
while end_index <= len(df['Pfizer']):
pfizer_weekly = df['Pfizer'][index:end_index]
johnson_weekly = df['Johnson'][index:end_index]
sp_500_weekly = df['S&P 500'][index:end_index]
pfizer_monthly_beta = calculate_beta(to_float_list(pfizer_weekly), to_float_list(sp_500_weekly))
johnson_monthly_beta = calculate_beta(to_float_list(johnson_weekly), to_float_list(sp_500_weekly))
pfizer_betas.append(pfizer_monthly_beta)
johnson_betas.append(johnson_monthly_beta)
index = end_index
end_index += 4
diff = np.median(pfizer_betas) - np.median(johnson_betas)
#print(pfizer_betas)
#print(johnson_betas)
pfizer_random_sample = []
johnson_random_sample = []
for index in range(10000): # run 10000 times
pfizer_random_index = np.random.randint(low = 0, high = len(pfizer_betas))
johnson_random_index = np.random.randint(low = 0, high = len(johnson_betas))
pfizer_random_sample.append(pfizer_betas[pfizer_random_index])
johnson_random_sample.append(pfizer_betas[johnson_random_index])
pfizer_seventy_five = np.percentile(pfizer_random_sample,75)
johnson_seventy_five = np.percentile(johnson_random_sample,75)
print("75 percentile difference pfizer ("+str(pfizer_seventy_five)+") - johnsonn("+str(johnson_seventy_five)+") ", str(np.percentile(pfizer_random_sample,75) - np.percentile(johnson_random_sample,75)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment