pythonyahoofinance

reading commodities into python with yahoo finance


I am reading stock data into python using the yahoo finance. It works with stocks, however, it giving errors with commodities.

The code below works perfectly:

import pandas as pd
import numpy as np
import pandas.io.data as web
import datetime

# We will look at stock prices over the past year, starting at January 1, 2016
start = datetime.datetime(2016,1,1)
end = datetime.date.today()

stock = "AAPL"

# get stock data, from yahoo finance within the dates specified
stock = web.DataReader(stock, "yahoo", start, end)

stock.head(n=3)

However, if you change the handle to a commodity instead of a stock you get this error:

import pandas as pd
import numpy as np
import pandas.io.data as web
import datetime

# We will look at stock prices over the past year, starting at January 1, 2016
start = datetime.datetime(2016,1,1)
end = datetime.date.today()

stock = "GCG17.CMX"

# get stock data, from yahoo finance within the dates specified
stock = web.DataReader(stock, "yahoo", start, end)

stock.head(n=3)

OSError: after 3 tries, Yahoo! did not return a 200 for url 'http://ichart.finance.yahoo.com/table.csv?s=GCG17.CMX&a=0&b=1&c=1970&d=0&e=22&f=2017&g=d&ignore=.csv'

Can anyone help me?


Solution

  • Instead use the eminent yfinance. Here for sugar futures:

    import yfinance as yf
    df = yf.download('SB=F', '2020-03-23')
    

    If you instead want gold futures, simply use the symbol GC=F instead. Should you wish to plot it:

    import finplot as fplt
    fplt.candlestick_ochl(df[['Open','Close','High','Low']])
    fplt.show()
    

    plot