Home > OS >  How do I export this pandas array of stock data into an excel spreadsheet?
How do I export this pandas array of stock data into an excel spreadsheet?

Time:12-07

import pandas as pd
import yfinance as yf
import pendulum
from datetime import date

today = str(date.today())
print(today)

pd.options.display.max_rows=390

start = pendulum.parse('2022-12-5 08:30')
end = pendulum.parse('2022-12-5 15:00')

stock = input("Enter a stock ticker symbol: ")
print(stock   " 1 Minute Data")
print(start)

print(yf.download(tickers= stock, interval="1m", start=start, end=end))

Running the code and typing in "TSLA" will load up every tick for the specified date. How would I export this array in a clean fashion to excel?

Side note: I was also trying to put today's date instead of pendulum's manual date '2022-12-5' Is there a way to also use the current date for pendulum.parse instead of manually typing it out every time? I tried making the date a variable but got an error etc.

CodePudding user response:

Well, I suspect yf.download is returning a pandas dataframe, so you could just save it to Excel using panda's to_excel function, unless there is more structure or processing you need to do.

df = yf.download(...)
df.to_excel('ticker_data.xlsx')

CodePudding user response:

Question 1: It returns a dataframe but you need to reset the index to bring Datetime column from index to column. You can chain all the commands together.

Question 2: pendulum.parse() takes a str so you just need to use an fstring.

import pendulum
import yfinance as yf


start = pendulum.parse(f"{pendulum.now().date()} 08:30")
end = pendulum.parse(f"{pendulum.now().date()} 15:00")

stock = input("Enter a stock ticker symbol: ")

(yf
 .download(tickers=stock, interval="1m", start=start, end=end)
 .reset_index()
 .to_excel(f"/path/to/file/{stock.lower()}.xlsx", index=False, sheet_name=stock)
 )
  • Related