Skip to content
Gold Market Price Exploration
Import Stock Market Data and Manipulation DataFrame
# import nessccesay library
import pandas as pd
import numpy as np
import yfinance as yf
import datetime
from datetime import date, timedelta
today = date.today()# download 1month period each hour from a ticker list
tickers = ['GC=F', '^IXIC','^GSPC','DX-Y.NYB','^TNX']
df = yf.download(tickers, period='12mo',interval = '1d',progress = False)
data = df.reset_index()
data = data.fillna(method='ffill')data# Flatten the multi-index columns by joining the two levels
data.columns = ['_'.join(col).strip() if col[1] else col[0] for col in data.columns.values]
# Now the columns are flat, so we can melt the DataFrame
data_melted = data.melt(id_vars=['Date'], var_name='Attribute', value_name='value')
# Split 'Attribute' column into 'Price' and 'Ticker' columns
data_melted[['Price', 'Ticker']] = data_melted['Attribute'].str.split('_', expand=True)
# Drop the 'Attribute' column as it's no longer needed
data_melted = data_melted.drop(columns=['Attribute'])
# Pivot the melted DataFrame to have the attributes (Open, High, Low, etc.) as columns
data_pivoted = data_melted.pivot_table(index=['Date', 'Ticker'], columns='Price', values='value', aggfunc='first')
# Reset the index to turn multi-index into columns
stock_data = data_pivoted.reset_index()
# Display the resulting data
print(stock_data.head())
# Manipulation Ticker and Drop level columns
stock_data_man = stock_data[stock_data['Ticker']!= '0']
stock_data_man
print(stock_data_man.isna().sum())stock_data_man# replace ticker to standard name
ticker_mapping = {
'GC=F': 'Gold',
'^GSPC': 'S&P 500',
'^IXIC': 'NASDAQ',
'DX-Y.NYB': 'DXY',
'^TNX' : '10Y Bond'
}
# Correctly replace the 'Ticker' column using the mapping
stock_data_man['Ticker'] = stock_data_man['Ticker'].replace(ticker_mapping)stock_data_manCreate Plotting and EDA
# import Chart Plotting Library
import matplotlib.pyplot as plt
import seaborn as sns# Normalize the adjusted close prices by dividing by the first value
stock_data_man['Adj Close Norm'] = stock_data_man.groupby('Ticker')['Adj Close'].transform(lambda x: x / x.iloc[0] * 100)
# Plot normalized prices
plt.figure(figsize=(14, 7))
sns.lineplot(data=stock_data_man, x='Date', y='Adj Close Norm', hue='Ticker')
# Set labels and title
plt.title('Normalized Adjusted Close Price Over Time')
plt.ylabel('Normalized Adjusted Close Price (Starting at 100)')
plt.xlabel('Date')
plt.xticks(rotation=45)
plt.show()
short_window = 50
long_window = 200
stock_data_man.set_index('Date', inplace=True)
unique_tickers = stock_data_man['Ticker'].unique()for ticker in unique_tickers:
ticker_data = stock_data_man[stock_data_man['Ticker'] == ticker].copy()
ticker_data['50_MA'] = ticker_data['Adj Close'].rolling(window=short_window).mean()
ticker_data['200_MA'] = ticker_data['Adj Close'].rolling(window=long_window).mean()
plt.figure(figsize=(14, 7))
plt.plot(ticker_data.index, ticker_data['Adj Close'], label='Adj Close')
plt.plot(ticker_data.index, ticker_data['50_MA'], label='50-Day MA')
plt.plot(ticker_data.index, ticker_data['200_MA'], label='200-Day MA')
plt.title(f'{ticker} - Adjusted Close and Moving Averages')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
stock_data_man['Daily Close'] = stock_data_man.groupby('Ticker')['Adj Close Norm'].pct_change()
price_corr = stock_data_man.pivot_table(index='Date', columns='Ticker', values='Adj Close')
correlation_matrix = price_corr.corr()
plt.figure(figsize=(7, 5))
sns.set(style='whitegrid')
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', linewidths=.5, fmt='.2f', annot_kws={"size": 10})
plt.title('Correlation Matrix of Daily Returns', fontsize=16)
plt.xticks(rotation=90)
plt.yticks(rotation=0)
plt.tight_layout()
plt.show()