Loading Stock Prices from Yahoo! Finance¶
xlSlim makes it easy to use the yfinance package to download prices into Excel.
The pandas functionality shown requires a premium licence. See Licensing
We will use this Python code to download the prices.
# example of using yfinance package to source prices and other data for financial instruments # pip install yfinance to get the package import yfinance as yf import pandas as pd def get_historical_prices(ticker_name: str, period: str) -> pd.DataFrame: assert ( len(ticker_name.split(" ")) == 1 ), "get_historica_prices works with one ticker only" tick = yf.Ticker(ticker_name) return tick.history(period)
All the Python code and Excel files shown are available from github in the xlslim-code-samples repo.
Save the Python code as a new file on your PC. I saved the file in my Documents folder.
Open Excel and enter this
RegisterPyModule() formula (amending the location to match where you saved the file):
yfinance is not available in the Python installation bundled with xlSlim. The Python module must be registered with an existing Python installation that has yfinance installed. See yfinance for installation details.
You should see a message similar to this confirming the module registration:
The get_historical_prices() function is now available in Excel. Let’s load the last 30 days of MSFT prices:
A cache object handle is returned to Excel. Internally xlSlim has put the pandas DataFrame into an in-memory cache.
ViewPyObject() can be used to view the data in Excel:
This example shows how neatly xlSlim handles pandas DataFrames.