简体   繁体   中英

Python 3: How to fix FileNotFoundError: [Errno 2] No such file or directory

Disclaimer: I am fairly new to python so sorry in advance for lack of coding knowledge. I am pulling historical data from Yahoo Finance and want to run a trading strategy through it. I got the backtest to work for the most part, but for efficiency and readability I decided to try to create a class with more explicitly defined variables. When I fetch the data, I want to download it as a csv file so I don't have to re-fetch the data every time I run it. That being said, when I try to use my variables in the creation of the file name of the csv, I get the FileNotFoundError. But if I just hard code in the name, it works creates the csv no problem. I have tried multiple different ways of using my variables for the file name but none work except hard coding. Can someone help me understand what is going on?

##Working Code:
class backtest:

    def __init__(self, ticker):

        start = '1/3/2000'
        end = '1/3/2019'
        sdate = pd.to_datetime(start)
        edate = pd.to_datetime(end)


        if os.path.islink('{}_{}_to_{}.csv'.format(ticker, start, end)) == True:
            self.df = pd.read_csv('{}_{}_to_{}.csv'.format(ticker, start, end), parse_dates=True)

        else:
            ##Failed attempt 1
            ##self.filename = '{}_{}_to_{}.csv'.format(ticker, start, end)
            ##self.df.to_csv(self.filename)

            ##Failed attempt 2
            ##self.filename = str(ticker) + '_' + start + '_to_' + end + '.csv'            
            ##self.df.to_csv(self.filename)

            self.df = web.DataReader(ticker, 'yahoo', sdate, edate)
            self.df.to_csv('amzn_1/3/2000_to_1/3/19.csv')



amzn = backtest('amzn')
print(amzn.df.head(1))

For making the file name try:

self.filename = str(ticker) + '_' + str(sdate) + '_to_' + str(edate) + '.csv'

here, sdate and edate are class 'pandas._libs.tslibs.timestamps.Timestamp' . So they have to be converted to string while appending.

The result in the console would be:

High ... Adj Close Date ... 2000-01-03 89.5625 ... 89.375

And the file name would be amzn_2000-01-03 00:00:00_to_2019-01-0300:00:00.csv . As mentioned in the comments above, filename not supposed to contain special char '/'. So using sdate instead of strat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM