yfinanceで金価格の取得
mkdir yfianace vim gold.py
内容を
import yfinance as yf
import datetime
# 金先物のティッカー
ticker = "GC=F"
# 非常に古い日付から現在まで取得
start_date = "1900-01-01" # yfinanceが対応している限界に挑戦
end_date = datetime.datetime.today().strftime('%Y-%m-%d')
# データの取得(日足)
gold_data = yf.download(ticker, start=start_date, end=end_date, interval="1d")
# 結果の表示
print(gold_data.head()) # 最初の5件
print(gold_data.tail()) # 最新の5件
print(f"\n最古のデータ: {gold_data.index[0]}")
print(f"最新のデータ: {gold_data.index[-1]}")
として保存
これを実行
/Users/snowpool/aw10s/yfinance/gold.py:12: FutureWarning: YF.download() has changed argument auto_adjust default to True gold_data = yf.download(ticker, start=start_date, end=end_date, interval="1d") [*********************100%***********************] 1 of 1 completed Price Close High Low Open Volume Ticker GC=F GC=F GC=F GC=F GC=F Date 2000-08-30 273.899994 273.899994 273.899994 273.899994 0 2000-08-31 278.299988 278.299988 274.799988 274.799988 0 2000-09-01 277.000000 277.000000 277.000000 277.000000 0 2000-09-05 275.799988 275.799988 275.799988 275.799988 2 2000-09-06 274.200012 274.200012 274.200012 274.200012 0 Price Close High Low Open Volume Ticker GC=F GC=F GC=F GC=F GC=F Date 2025-07-21 3401.899902 3411.699951 3350.300049 3350.300049 53 2025-07-22 3439.199951 3441.000000 3395.600098 3411.000000 39 2025-07-23 3394.100098 3433.899902 3388.100098 3430.300049 63 2025-07-24 3371.000000 3371.000000 3367.000000 3367.000000 63 2025-07-25 3332.300049 3376.600098 3328.899902 3372.100098 156194 最古のデータ: 2000-08-30 00:00:00 最新のデータ: 2025-07-25 00:00:00
これを他で使えるようにcsvに保存する
import yfinance as yf
import datetime
# 金先物のティッカー
ticker = "GC=F"
# 非常に古い日付から現在まで取得
start_date = "1900-01-01"
end_date = datetime.datetime.today().strftime('%Y-%m-%d')
# データの取得(日足)
gold_data = yf.download(ticker, start=start_date, end=end_date, interval="1d")
# 結果の表示(最初と最後の数件)
print("=== 最初の5行 ===")
print(gold_data.head())
print("\n=== 最後の5行 ===")
print(gold_data.tail())
# 最古と最新のデータ日付
print(f"\n最古のデータ: {gold_data.index[0].date()}")
print(f"最新のデータ: {gold_data.index[-1].date()}")
# CSVに保存
csv_file = "gold_price_gc_f.csv"
gold_data.to_csv(csv_file)
print(f"\n✅ CSVファイルとして保存完了: {csv_file}")
実行すると
python gold_csv.py /Users/snowpool/aw10s/yfinance/gold_csv.py:12: FutureWarning: YF.download() has changed argument auto_adjust default to True gold_data = yf.download(ticker, start=start_date, end=end_date, interval="1d") [*********************100%***********************] 1 of 1 completed === 最初の5行 === Price Close High Low Open Volume Ticker GC=F GC=F GC=F GC=F GC=F Date 2000-08-30 273.899994 273.899994 273.899994 273.899994 0 2000-08-31 278.299988 278.299988 274.799988 274.799988 0 2000-09-01 277.000000 277.000000 277.000000 277.000000 0 2000-09-05 275.799988 275.799988 275.799988 275.799988 2 2000-09-06 274.200012 274.200012 274.200012 274.200012 0 === 最後の5行 === Price Close High Low Open Volume Ticker GC=F GC=F GC=F GC=F GC=F Date 2025-07-21 3401.899902 3411.699951 3350.300049 3350.300049 53 2025-07-22 3439.199951 3441.000000 3395.600098 3411.000000 39 2025-07-23 3394.100098 3433.899902 3388.100098 3430.300049 63 2025-07-24 3371.000000 3371.000000 3367.000000 3367.000000 63 2025-07-25 3328.899902 3376.600098 3328.100098 3372.100098 157705 最古のデータ: 2000-08-30 最新のデータ: 2025-07-25 ✅ CSVファイルとして保存完了: gold_price_gc_f.csv
となってcsvが保存される
次にSqlite へ登録する
しかし
import sqlite3
import pandas as pd
# CSV読み込み
df = pd.read_csv("gold_price_gc_f.csv", parse_dates=["Date"])
# SQLiteに保存
conn = sqlite3.connect("commodity_data.db")
df.to_sql("gold_price_daily", conn, if_exists="replace", index=False)
conn.close()
print("✅ SQLiteに保存完了: gold_price_daily テーブル")
だとエラーになる
Traceback (most recent call last):
File "/Users/snowpool/aw10s/yfinance/add_sqldb.py", line 5, in <module>
df = pd.read_csv("gold_price_gc_f.csv", parse_dates=["Date"])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/snowpool/.pyenv/versions/3.11.0/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 1026, in read_csv
return _read(filepath_or_buffer, kwds)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/snowpool/.pyenv/versions/3.11.0/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 620, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/snowpool/.pyenv/versions/3.11.0/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 1620, in __init__
self._engine = self._make_engine(f, self.engine)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/snowpool/.pyenv/versions/3.11.0/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 1898, in _make_engine
return mapping[engine](f, **self.options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/snowpool/.pyenv/versions/3.11.0/lib/python3.11/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 161, in __init__
self._validate_parse_dates_presence(self.names) # type: ignore[has-type]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/snowpool/.pyenv/versions/3.11.0/lib/python3.11/site-packages/pandas/io/parsers/base_parser.py", line 243, in _validate_parse_dates_presence
raise ValueError(
ValueError: Missing column provided to 'parse_dates': 'Date'
これは
行目にティッカー情報の行が含まれており、本来のヘッダーが1行目 になっていないため、pandas.read_csv()がうまく処理できていないのが原因
このため
2行目スキップして1行目をヘッダーとして読み込むように変更
import sqlite3
import pandas as pd
# 2行目(ティッカー行)をスキップし、1行目をヘッダーとして使用
df = pd.read_csv("gold_price_gc_f.csv", skiprows=[1], parse_dates=["Price"])
df.rename(columns={"Price": "Date"}, inplace=True) # Date列として扱う
# SQLiteに保存
conn = sqlite3.connect("commodity_data.db")
df.to_sql("gold_price_daily", conn, if_exists="replace", index=False)
conn.close()
print("✅ SQLiteに保存完了: gold_price_daily テーブル")
これを実行すると
python add_sqldb.py
/Users/snowpool/aw10s/yfinance/add_sqldb.py:5: UserWarning: Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.
df = pd.read_csv("gold_price_gc_f.csv", skiprows=[1], parse_dates=["Price"])
✅ SQLiteに保存完了: gold_price_daily テーブル
となる
これにより
* Price 列 → Date に名前変更(DateTime型として扱える)
* SQLite テーブル名:gold_price_daily
* 後続のクエリや可視化処理が簡単になります
となる
保存後に確認したいのなら
# 保存したDBの中身を確認(任意)
conn = sqlite3.connect("commodity_data.db")
df_check = pd.read_sql("SELECT * FROM gold_price_daily LIMIT 5", conn)
print(df_check)
conn.close()
を追加すると良い