intelligent-trading-bot/scripts/download_yahoo.py

91 lines
2.8 KiB
Python
Raw Permalink Normal View History

2022-07-10 11:14:47 +02:00
from datetime import datetime, date, timedelta
import click
2022-07-10 12:17:16 +02:00
import yfinance as yf
2022-07-10 11:14:47 +02:00
from service.App import *
"""
Download quotes from Yahoo
"""
@click.command()
@click.option('--config_file', '-c', type=click.Path(), default='', help='Configuration file name')
def main(config_file):
"""
"""
load_config(config_file)
time_column = App.config["time_column"]
2022-07-10 11:14:47 +02:00
data_path = Path(App.config["data_folder"])
if not data_path.is_dir():
print(f"Data folder does not exist: {data_path}")
return
now = datetime.now()
data_sources = App.config["data_sources"]
for ds in data_sources:
2022-07-10 11:14:47 +02:00
# Assumption: folder name is equal to the symbol name we want to download
quote = ds.get("folder")
2022-07-10 11:14:47 +02:00
if not quote:
print(f"ERROR. Folder is not specified.")
continue
# If file name is not specified then use symbol name as file name
file = ds.get("file", quote)
2022-07-10 11:14:47 +02:00
if not file:
file = quote
print(f"Start downloading '{quote}' ...")
in_file_path = (data_path / quote / file).with_suffix(".csv")
2022-07-10 11:14:47 +02:00
if in_file_path.is_file():
2022-07-31 11:55:54 +02:00
df = pd.read_csv(in_file_path, parse_dates=[time_column])
2022-07-10 11:14:47 +02:00
#df['Date'] = pd.to_datetime(df['Date']) # "2022-06-07" iso format
2022-07-31 11:55:54 +02:00
df[time_column] = df[time_column].dt.date
last_date = df.iloc[-1][time_column]
2022-07-10 11:14:47 +02:00
# === Download from the remote server
2022-07-10 12:17:16 +02:00
new_df = yf.download(quote, last_date - timedelta(days=5)) # Download somewhat more than we need
2022-07-10 11:14:47 +02:00
new_df = new_df.reset_index()
new_df['Date'] = pd.to_datetime(new_df['Date']).dt.date
2022-07-10 12:17:16 +02:00
del new_df['Close']
new_df.rename({'Adj Close': 'Close', 'Date': time_column}, axis=1, inplace=True)
2022-07-10 12:17:16 +02:00
new_df.columns = new_df.columns.str.lower()
2022-07-10 11:14:47 +02:00
df = pd.concat([df, new_df])
df = df.drop_duplicates(subset=[time_column], keep="last")
2022-07-10 11:14:47 +02:00
else:
print(f"File not found. Full fetch...")
2022-07-10 12:17:16 +02:00
# === Download from the remote server
df = yf.download(quote, date(1990, 1, 1))
2022-07-10 11:14:47 +02:00
df = df.reset_index()
df['Date'] = pd.to_datetime(df['Date']).dt.date
2022-07-10 12:17:16 +02:00
del df['Close']
df.rename({'Adj Close': 'Close', 'Date': time_column}, axis=1, inplace=True)
2022-07-10 12:17:16 +02:00
df.columns = df.columns.str.lower()
2022-07-10 11:14:47 +02:00
print(f"Full fetch finished.")
df = df.sort_values(by=time_column)
2022-07-10 11:14:47 +02:00
in_file_path.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(in_file_path, index=False)
2022-07-10 11:14:47 +02:00
print(f"Stored in '{in_file_path}'")
elapsed = datetime.now() - now
print(f"Finished downloading data in {str(elapsed).split('.')[0]}")
return df
if __name__ == '__main__':
main()