I am using YFinance to get some stock historical prices. Trying to convert the data to Json as data for JS Charting. The Yfinance dataframe treat the date column as index. As a result, I don't know how to access/print out the simple 'date' column. (You can tell I am beginner for python).
I've tried to read the dataframe document about to_json() and stuff like reset_index(). But I am so beginner that I cannot understand what they are saying.
All I really want is to generate a Json text from Yfinance dataframe for the javascript app on my web page like the following:
<script>
data = [{"date":"2020-11-20",
"open":"1234",
"high":"1245",
"low":"999",
"close":"1120",
"volume":"1234566"},
{"date":"2020-11-19",......
.......
}]
</script>
I am using a silly for loop to generate the text right now but I am sure there are much more elegant solution out there.
yfinance data is indexed by date, so df.to_dict(orient='records')` will be converted to the desired format.
import yfinance as yf
tickers = yf.Tickers('aapl')
df = tickers.tickers.AAPL.history(period="1mo")
df.reset_index(inplace=True)
df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')
df.drop(['Dividends','Stock Splits'], inplace=True, axis=1)
df.to_dict(orient='records')
[{'Date': '2020-10-21',
'Open': 116.46906393914934,
'High': 118.50555147489459,
'Low': 116.24944161427659,
'Close': 116.6687240600586,
'Volume': 89946000},
{'Date': '2020-10-22',
'Open': 117.24771296653945,
'High': 117.83670077073543,
'Low': 114.39263813163417,
'Close': 115.55064392089844,
'Volume': 101988000},
{'Date': '2020-10-23',
'Open': 116.18954660696212,
'High': 116.34927470261839,
'Low': 114.08317994708769,
'Close': 114.84187316894531,
'Volume': 82572600},
{'Date': '2020-10-26',
'Open': 113.81364269517282,
'High': 116.34926896680302,
'Low': 112.6855840199125,
'Close': 114.85185241699219,
'Volume': 111850700},
...]