Yahoo Finance Data

Overview

The yahoo data library provides a script for using the yahoo finance python library to download financial price data from yahoo finance, and to cache the files locally for quicker retrieval.

Example Usage

import yahoo as yh data = yh.history('AAPL')

Configuration

The yahoo library can be configured by adding entries to your .env file. The following keys will configure its behaviour.



cache-yahoo="cache/yahoo" expires-yahoo=86400 format=pandas

Full Script

import yfinance as yf import os from pathlib import Path import pandas as pd from datetime import datetime, timedelta, date from dotenv import load_dotenv from davinci.python import cache load_dotenv() root = os.getenv('cache-yahoo') if root == None:root = 'cache' expires = os.getenv('cache-yahoo-expires') if expires != None:expires=int(expires) start = os.getenv('yahoo-start') if start == None:start = '1990-01-01' end = os.getenv('yahoo-end') if end == None : end = date.today().isoformat() format = os.getenv('yahoo-format') ''' Currencies data = yf.download("EURUSD=X", start="2025-06-01", end="2026-06-04") ''' def to_list(data): list1 = data.to_dict(orient='records') list2 = [] for item in list1: nitem = {} list2.append(nitem) for key in item: key_str = str(key) value = item[key] if key[0] == 'Date': iso_string = value.isoformat() split1 = iso_string.split('T') value = split1[0] nitem[key_str] = value pass pass def read(filename): file_path = Path(filename) if file_path.is_file(): df = pd.read_csv(filename) if(format == 'pandas'): return df return df.to_dict(orient='records') pass def saveTicker(ticker_symbol,start, end): global root filename = ticker_symbol.replace(' ', '_')+'.csv' data = yf.download(ticker_symbol, start=start, end=end) data = data.reset_index() #flatten the multi head columns data.columns = [":".join(reversed(col)).strip() for col in data.columns.values] data = data.rename(columns={':Date': 'Date'}) data.to_csv(root+'/' + filename, index=False) pass def history(ticker_symbol): global root global start global end data = None filename = ticker_symbol.replace(' ', '_')+'.csv' file_path = Path(root+'/'+filename) last_date = None # Check if it exists and is a regular file if file_path.is_file(): # Get the modification time timestamp timestamp = file_path.stat().st_mtime # Convert timestamp to a readable datetime object last_date = datetime.fromtimestamp(timestamp) pass if last_date == None: saveTicker(ticker_symbol, start, end) else: difference = abs(datetime.now() - last_date) # 2. Check if the absolute difference is less than 24 hours if expires != None and difference > timedelta(days=expires): saveTicker(ticker_symbol, start, end) data = read(root+'/' + filename ) return data