Repository: ranaroussi/yfinance

Issue:
Name Error
```
import yfinance as yf
import matplotlib.pyplot as plt

# Define the ticker symbol
symbol = "NQ=F"
plt.style.use('dark_background')

# Create the object representing the symbol of interest
equity = yf.Ticker(symbol)
info = equity.fast_info

# Get the data for the ticker
ticker = yf.Ticker(symbol)

# Set the time frame to 2 days with 1-minute intervals
df = ticker.history(period="2d", interval="1m")

# Set the x-axis limits to cover the entire time frame
plt.xlim(df.index[0], df.index[-1])

# Get the stock's current price
price = round(equity.fast_info["last_price"], 2)

# Get the stock's closing price
close_price = round(equity.fast_info["regular_market_previous_close"], 2)

# Calculate the difference between the current price and the closing price in points and percentage terms
points_diff = round((price - close_price), 2)
percent_diff = round((price - close_price) / close_price * 100, 2)

# Loop through each day in the data
for i, day in df.groupby(df.index.date):
	# Plot the close price for the first day in white color
	if i == df.index.date[0]:
		plt.plot(day.index, day['Close'], color='white')
	else:
		# Set the baseline to the final closing price of the first day
		baseline = df[df.index.date == df.index.date[0]]['Close'][-1]

		# Add a vertical dotted line at the open price for the second day
		plt.axvline(x=day.index[0], color='white', linestyle='dotted')

		# Loop through each point in the day
		for j in range(len(day)):
			if day['Close'][j] > baseline:
				plt.plot(day.index[j], day['Close'][j], 'gd',markersize=1)  # green circle and line
			else:
				plt.plot(day.index[j], day['Close'][j], 'rd',markersize=1)  # red circle and line

		# Add a horizontal line at the baseline for the second day
		plt.axhline(y=baseline, color='none', linestyle='--')

# Make the price annotation white
plt.annotate(f"{symbol}\n{price}", xy=(df.index[-1], price), fontsize=8,weight='bold',
			xytext=(5, 5), textcoords='offset points',
			ha='left', va='bottom', color='white')
if points_diff > 0:
	color = 'limegreen'
else:
	color = 'red'
plt.annotate(f"{points_diff}\n{percent_diff}%", xy=(df.index[-1], price), fontsize=8,weight='bold',
             xytext=(5, 5), textcoords='offset points',
             ha='left', va='top', color=color)

plt.xlabel('Date')
plt.xticks(fontsize=6)
plt.ylabel('Price')
plt.title(f'{symbol} Price',color='orange')
plt.show()
```






Discussion:
Easy to fix. But first: did you see this print?
> Note: 'info' dict is now fixed & improved, 'fast_info' no longer faster
Thanks for the quick response. Yes, I saw that print. However, I seem to be getting  inconsistent results using:
equity = yf.Ticker(symbol)
info = equity.info
```
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd


# Define the ticker symbol
symbol = "NQ=F"
plt.style.use('dark_background')

# Create the object representing the symbol of interest
equity = yf.Ticker(symbol)
info = equity.info

# Get the data for the ticker
ticker = yf.Ticker(symbol)

# Set the time frame to 2 days with 1-minute intervals
df = ticker.history(period="2d", interval="1m")

# Set the x-axis limits to cover the entire time frame
plt.xlim(df.index[0], df.index[-1])

# Get the stock's current price
price = round(equity.info["previousClose"], 2)

# Get the stock's closing price
close_price = round(equity.info["regularMarketPreviousClose"], 2)

# Calculate the difference between the current price and the closing price in points and percentage terms
points_diff = round((price - close_price), 2)
percent_diff = round((price - close_price) / close_price * 100, 2)

# Loop through each day in the data
for i, day in df.groupby(df.index.date):
	# Plot the close price for the first day in white color
	if i == df.index.date[0]:
		plt.plot(day.index, day['Close'], color='white')
	else:
		# Set the baseline to the final closing price of the first day
		baseline = df[df.index.date == df.index.date[0]]['Close'][-1]

		# Add a vertical dotted line at the open price for the second day
		plt.axvline(x=day.index[0], color='white', linestyle='dotted')

		# Loop through each point in the day
		for j in range(len(day)):
			if day['Close'][j] > baseline:
				plt.plot(day.index[j], day['Close'][j], 'gd',markersize=1)  # green circle and line
			else:
				plt.plot(day.index[j], day['Close'][j], 'rd',markersize=1)  # red circle and line

		# Add a horizontal line at the baseline for the second day
		plt.axhline(y=baseline, color='none', linestyle='--')

# Make the price annotation white
plt.annotate(f"{symbol}\n{price}", xy=(df.index[-1], price), fontsize=8,weight='bold',
			xytext=(5, 5), textcoords='offset points',
			ha='left', va='bottom', color='white')
if points_diff > 0:
	color = 'limegreen'
else:
	color = 'red'
plt.annotate(f"{points_diff}\n{percent_diff}%", xy=(df.index[-1], price), fontsize=8,weight='bold',
             xytext=(5, 5), textcoords='offset points',
             ha='left', va='top', color=color)

plt.xlabel('Date')
plt.xticks(fontsize=6)
plt.ylabel('Price')
plt.title(f'{symbol} Price',color='orange')
plt.show()
```


#this is currently giving incorrect price, points change, and percent change 
#Also, there is this issue between stocks and indices; this works fine for stocks like "JPM" but not for indices like "^vix, ^GSPC, and ^Ndx ( it says KeyError: 'currentPrice') 

```
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd

# Define the ticker symbol
symbol = "JPM"
plt.style.use('dark_background')

# Create the object representing the symbol of interest
equity = yf.Ticker(symbol)
info = equity.info

# Get the data for the ticker
ticker = yf.Ticker(symbol)

# Set the time frame to 2 days with 1-minute intervals
df = ticker.history(period="2d", interval="1m")

# Set the x-axis limits to cover the entire time frame
plt.xlim(df.index[0], df.index[-1])

# Get the stock's current price
price = round(equity.info["currentPrice"], 2)

# Get the stock's closing price
close_price = round(equity.info["regularMarketPreviousClose"], 2)

# Calculate the difference between the current price and the closing price in points and percentage terms
points_diff = round((price - close_price), 2)
percent_diff = round((price - close_price) / close_price * 100, 2)

# Determine the color for the price annotation based on the points difference
if points_diff > 0:
	color = 'limegreen'
else:
	color = 'red'
	
# Loop through each day in the data
for i, day in df.groupby(df.index.date):
	# Plot the close price for the first day in white color
	if i == df.index.date[0]:
		plt.plot(day.index, day['Close'], color='white')
	else:
		# Set the baseline to the final closing price of the first day
		baseline = df[df.index.date == df.index.date[0]]['Close'][-1]
		
		# Shift the index of the second day by 9 hours
		day.index = day.index - pd.Timedelta(hours=17.5)
		
		# Add a vertical dotted line at the open price for the second day
		plt.axvline(x=day.index[0], color='white', linestyle='dotted')
		
		# Loop through each point in the day
		for j in range(len(day)):
			if day['Close'][j] > baseline:
				plt.plot(day.index[j], day['Close'][j], 'gd', markersize=1)  # green circle and line
			else:
				plt.plot(day.index[j], day['Close'][j], 'rd', markersize=1)  # red circle and line
				
		# Add a horizontal line at the baseline for the second day
		plt.axhline(y=baseline, color='none', linestyle='--')
		
# Make the price annotation white
plt.annotate(f"{points_diff}\n{percent_diff}%", xy=(df.index[-1], price), fontsize=7, weight='bold',
			xytext=(-80, 5), textcoords='offset points',
			ha='left', va='top', color=color)

# Add another plot annotation in the original color that shows the current price only
plt.annotate(f"{price}", xy=(df.index[-1], price), fontsize=8, weight='bold',
			xytext=(-80, 0), textcoords='offset points',
			ha='right', va='center', color='white')

plt.xlabel('Date')
plt.xticks(fontsize=6)
plt.xticks(pd.date_range(start=df.index[0] - pd.Timedelta(hours=9.5), end=df.index[-1] - pd.Timedelta(hours=17.5),
						freq='1min'))

plt.ylabel('Price')
plt.title(f'{symbol} Price', color='orange')
plt.show()

```
Please make your posts more concise, no one's reading all that. And use the 'quote code' feature.
Sorry. Essentially, there is an issue a KeyError: 'currentPrice' when using: 
symbol = "^GSPC"
plt.style.use('dark_background')

equity = yf.Ticker(symbol)
info = equity.info

I mean: can you go back and edit above posts.
Yes, I can try. 
```
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd

# Define the ticker symbol
symbol = "^GSPC"
plt.style.use('dark_background')

# Create the object representing the symbol of interest
equity = yf.Ticker(symbol)
info = equity.info

# Get the data for the ticker
ticker = yf.Ticker(symbol)

# Set the time frame to 2 days with 1-minute intervals
df = ticker.history(period="2d", interval="1m")

# Set the x-axis limits to cover the entire time frame
plt.xlim(df.index[0], df.index[-1])

# Get the stock's current price
price = round(equity.info["currentPrice"], 2)

# Get the stock's closing price
close_price = round(equity.info["regularMarketPreviousClose"], 2)

# Calculate the difference between the current price and the closing price in points and percentage terms
points_diff = round((price - close_price), 2)
percent_diff = round((price - close_price) / close_price * 100, 2)

# Determine the color for the price annotation based on the points difference
if points_diff > 0:
	color = 'limegreen'
else:
	color = 'red'
	
# Loop through each day in the data
for i, day in df.groupby(df.index.date):
	# Plot the close price for the first day in white color
	if i == df.index.date[0]:
		plt.plot(day.index, day['Close'], color='white')
	else:
		# Set the baseline to the final closing price of the first day
		baseline = df[df.index.date == df.index.date[0]]['Close'][-1]
		
		# Shift the index of the second day by 9 hours
		day.index = day.index - pd.Timedelta(hours=17.5)
		
		# Add a vertical dotted line at the open price for the second day
		plt.axvline(x=day.index[0], color='white', linestyle='dotted')
		
		# Loop through each point in the day
		for j in range(len(day)):
			if day['Close'][j] > baseline:
				plt.plot(day.index[j], day['Close'][j], 'gd', markersize=1)  # green circle and line
			else:
				plt.plot(day.index[j], day['Close'][j], 'rd', markersize=1)  # red circle and line
				
		# Add a horizontal line at the baseline for the second day
		plt.axhline(y=baseline, color='none', linestyle='--')
		
# Make the price annotation white
plt.annotate(f"{points_diff}\n{percent_diff}%", xy=(df.index[-1], price), fontsize=7, weight='bold',
			xytext=(-80, 5), textcoords='offset points',
			ha='left', va='top', color=color)

# Add another plot annotation in the original color that shows the current price only
plt.annotate(f"{price}", xy=(df.index[-1], price), fontsize=8, weight='bold',
			xytext=(-80, 0), textcoords='offset points',
			ha='right', va='center', color='white')

plt.xlabel('Date')
plt.xticks(fontsize=6)
plt.xticks(pd.date_range(start=df.index[0] - pd.Timedelta(hours=9.5), end=df.index[-1] - pd.Timedelta(hours=17.5),
						freq='1min'))

plt.ylabel('Price')
plt.title(f'{symbol} Price', color='orange')
plt.show()
```
Why is `matplotlib` important?
In this code, it is used to plot the stock's closing prices over a 2-day period with 1-minute intervals and to add annotations indicating the current price and the difference between the current price and the previous close price.




Why is it important *for this bug in `yfinance`*?
I’m trying to illustrate the bug in yfiannce. Try the above codes: the one with “JPM” and the one with “^GSPC”
You’ll see that JPM works and ^GSPC gives a key error for current price. There’s a similar key error for etfs, indices, and currencies, but not stocks like JPM AAPL AMAZN. This leads me to believe there is an underlying bug 

Resolving patch:
diff --git a/yfinance/scrapers/quote.py b/yfinance/scrapers/quote.py
--- a/yfinance/scrapers/quote.py
+++ b/yfinance/scrapers/quote.py
@@ -2,6 +2,7 @@
 import json
 
 import pandas as pd
+import numpy as _np
 
 from yfinance import utils
 from yfinance.data import TickerData
@@ -78,7 +79,7 @@ class FastInfo:
     # Contain small subset of info[] items that can be fetched faster elsewhere.
     # Imitates a dict.
     def __init__(self, tickerBaseObject):
-        utils.print_once("Note: 'info' dict is now fixed & improved, 'fast_info' no longer faster")
+        utils.print_once("yfinance: Note: 'Ticker.info' dict is now fixed & improved, 'fast_info' is no longer faster")
 
         self._tkr = tickerBaseObject
 


Test patch:
diff --git a/tests/ticker.py b/tests/ticker.py
--- a/tests/ticker.py
+++ b/tests/ticker.py
@@ -704,6 +704,11 @@ def test_info(self):
         self.assertEqual(self.symbols[0], data["symbol"], "Wrong symbol value in info dict")
 
     def test_fast_info(self):
+        f = yf.Ticker("AAPL", session=self.session).fast_info
+        for k in f:
+            self.assertIsNotNone(f[k])
+
+    def test_fast_info_matches_info(self):
         yf.scrapers.quote.PRUNE_INFO = False
 
         fast_info_keys = set()