-1

I'm trying to define a function to allow me to extract information on stocks over the past 12 months and export it to a CSV file. I'm not sure where it's going wrong as it prints 'bad'. Any thoughts? Thanks.

import pandas as py
import numpy as np
import yfinance as yf
import datetime as dt
from pandas_datareader import data as pdr
from yahoofinancials import YahooFinancials

yf.pdr_override()


now_time=dt.datetime.now()
start_time = dt.datetime(now_time.year - 1, now_time.month , now_time.day)

bad_names=[]

def download_stock(stock):
    try:
        print(stock)
        stock_df = pdr.get_yahoo_data(stock, start_time, now_time)
        stock_df['Name'] = stock
        output_name = stock + '_data.csv'
        stock_df.to_csv("./stocks/"+output_name)
    except:
        bad_names.append(stock)
        print('bad: %s' % (stock))

download_stock('AAPL')
Reid
  • 1
  • 1
  • [`pdr.get_data_yahoo`](https://github.com/pydata/pandas-datareader/blob/main/pandas_datareader/data.py#L79) not `pdr.get_yahoo_data`. I'm voting to close the question as caused by a typo. – Trenton McKinney Oct 04 '22 at 18:30

1 Answers1

0

A try - except block will handle any exception and simply execute what follows after except.

You could try running the code without the try-except block and see what the error is.

Alternatively, you could use

except Exception as e:
    print(e)

So you can know what is going wrong exactly. Looking at it now, I would guess that you are missing one dot in the filepath "../stocks/"+output_name

jinx
  • 173
  • 2
  • 12