-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtracker.py
52 lines (42 loc) · 1.33 KB
/
tracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import yfinance as yf
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import datetime
# instantiate vars to store stock data and times
prices = []
times = []
# fetch the latest stock price
def get_stock_price(stock_symbol):
stock = yf.Ticker(stock_symbol)
todays_data = stock.history(period='1d')
return todays_data['Close'][0]
# update the graph
def update_graph(i, stock_symbol):
current_price = get_stock_price(stock_symbol)
prices.append(current_price)
times.append(datetime.datetime.now())
# cap number of points surfaced on graph
if len(prices) > 50:
prices.pop(0)
times.pop(0)
plt.cla() # clear current axes
plt.plot(times, prices, label=f'Stock Price: {stock_symbol}', color='blue')
# format graph
plt.gcf().autofmt_xdate
plt.xlabel('Time')
plt.ylabel('Price (USD)')
plt.title(f'Real-Time Stock Price of {stock_symbol}')
plt.legend(loc='upper left')
plt.tight_layout()
# intialize the graph
def start_real_time_tracking(stock_symbol):
global times, prices
times = []
prices = []
fig = plt.figure(figsize=(10, 5))
ani = FuncAnimation(fig, update_graph, fargs=(stock_symbol,), interval=5000)
plt.show()
# run the tracker
if __name__ == "__main__":
stock_symbol = input("Enter the stock symbol (eg AAPL for Apple): ")
start_real_time_tracking(stock_symbol)