Files
trading_analysis/Yahoo_Finance_DL_COPPER_EXCEL.ipynb
T

10 KiB

In [ ]:
%pip install "yfinance[optional]"=="0.2.37"
In [7]:
import yfinance as yf

hg_f = yf.Ticker("HG=F")
In [8]:
import pandas as pd
import numpy as np

# get historical market data
hist = hg_f.history(period="100y")

# Replace 0 values with NaN in specific columns
hist.replace({'Volume': {0: pd.NA}, 'Open': {0: pd.NA}}, inplace=True)
hist.replace(0, np.nan, inplace=True)  # Replace 0 with NaN

columns = ['Open', 'High', 'Low', 'Close', 'Volume']
In [9]:
hist.head()
Out [9]:
Open High Low Close Volume Dividends Stock Splits
Date
2000-08-30 00:00:00-04:00 0.879 0.887 0.8770 0.8850 2886 NaN NaN
2000-08-31 00:00:00-04:00 0.885 0.888 0.8800 0.8850 1095 NaN NaN
2000-09-01 00:00:00-04:00 0.878 0.889 0.8780 0.8890 3449 NaN NaN
2000-09-05 00:00:00-04:00 0.896 0.907 0.8950 0.9060 1397 NaN NaN
2000-09-06 00:00:00-04:00 0.905 0.906 0.8975 0.9015 1195 NaN NaN
In [11]:
# Convert the index to datetime if it's not already
hist.index = pd.to_datetime(hist.index)

# Strip the time and timezone, keeping only the date for the index
hist.index = hist.index.date

hist.head()
Out [11]:
Open High Low Close Volume Dividends Stock Splits
2000-08-30 0.879 0.887 0.8770 0.8850 2886 NaN NaN
2000-08-31 0.885 0.888 0.8800 0.8850 1095 NaN NaN
2000-09-01 0.878 0.889 0.8780 0.8890 3449 NaN NaN
2000-09-05 0.896 0.907 0.8950 0.9060 1397 NaN NaN
2000-09-06 0.905 0.906 0.8975 0.9015 1195 NaN NaN
In [16]:
from datetime import datetime

# Get the current date in 'YYYY-MM-DD' format
current_date = datetime.now().strftime('%Y-%m-%d')

# Create the file name with the current date
file_name = f'./Data_COPPER_{current_date}.csv'

hist = hist.round(3)

# Save the DataFrame to CSV with the dynamic file name
hist[["Open", "High", "Low", "Close"]].to_csv(file_name)
In [ ]: