I have a problem with getting the dates from yfinance into my matplotlib graph can somebody help/show me how to get the dates from yfinance into my matplotlib graph
JavaScript
x
22
22
1
import numpy as np
2
import yfinance as yf
3
import matplotlib.pyplot as plt
4
import pandas as pd
5
6
# function getting data for the last x years with x weeks space from checking data and specific
7
observation.
8
def stock_data(ticker, period, interval, observation):
9
ticker = yf.Ticker(ticker)
10
ticker_history = ticker.history(period, interval)
11
print(ticker_history[observation]) #is here to show you the data that we get
12
date = pd.date_range(ticker_history[period])
13
x = date
14
y = np.array(ticker_history[observation])
15
plt.style.use('dark_background')
16
plt.plot(x,y)
17
plt.ylabel('Price($)')
18
plt.xlabel('Date', rotation=0)
19
plt.show()
20
21
stock_data('GOOGL', '6mo', '1wk', 'Open')
22
Advertisement
Answer
Tested ✅
🔰You could extract the date from ticker_history[observation]
🔰 It is a Pandas Series object, so here’s how I’d do it:
JavaScript
1
27
27
1
import numpy as np
2
import yfinance as yf
3
import matplotlib.pyplot as plt
4
import pandas as pd
5
6
# function getting data for the last x years with x weeks space
7
# from checking data and specific observation.
8
def stock_data(ticker, period, interval, observation):
9
ticker = yf.Ticker(ticker)
10
ticker_history = ticker.history(period, interval)
11
print((ticker_history[observation]))
12
13
sf = ticker_history[observation]
14
df = pd.DataFrame({'Date':sf.index, 'Values':sf.values})
15
16
x = df['Date'].tolist()
17
y = df['Values'].tolist()
18
19
plt.style.use('dark_background')
20
plt.plot(x,y)
21
plt.ylabel('Price($)')
22
plt.xlabel('Date', rotation=0)
23
plt.show()
24
25
if __name__ == '__main__':
26
stock_data('GOOGL', '6mo', '1wk', 'Open')
27