Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 41 additions & 52 deletions stock_price.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,53 @@
# Remember the pre-requisites
# pip install requests matplotlib
import requests
import matplotlib.pyplot as plt
from collections import deque
import time

# Use a public API for real data, e.g., Finnhub.io or Alpha Vantage.
# This example uses a placeholder URL and dummy data.
def get_stock_price(ticker):
"""Fetches real-time stock price from a mock API."""
# Replace this with a real API call.
# Example using dummy data:
if ticker == 'AAPL':
# Simulate a slight price fluctuation
return 150.0 + (time.time() % 10) * 0.5 - 2.5
else:
return None
# Real-Time Stock Price Plotter (Console Version)
# Hacktoberfest 2025 Contribution
# Author: Sonika KC
# Works without installing any external libraries

import random
import time
import datetime
import os

# Function: Generate dummy stock price
def get_stock_price(dummy_price):
"""Simulates stock price fluctuations."""
fluctuation = random.uniform(-1.0, 1.0) # +/- $1
return round(dummy_price + fluctuation, 2)

# Function: Draw simple text-based graph
def draw_graph(prices):
os.system('cls' if os.name == 'nt' else 'clear') # Clear terminal
max_price = max(prices)
min_price = min(prices)
scale = 50 / (max_price - min_price + 0.01) # Scale to 50 characters

print("Real-Time Stock Price (AAPL)\n")
for price in prices:
num_chars = int((price - min_price) * scale)
print(f"${price:6} | " + "*" * num_chars)
print("\nPress Ctrl+C to stop.\n")

# Main function
def main():
"""Fetches and plots stock prices in real time."""
stock_ticker = 'AAPL'
time_series_data = deque(maxlen=50) # Use a deque for efficient sliding window
time_points = deque(maxlen=50)

plt.ion() # Turn on interactive mode
fig, ax = plt.subplots()
line, = ax.plot([], [], 'o-')
ax.set_title(f"Real-Time Stock Price for {stock_ticker}")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Price ($)")

start_time = time.time()
max_points = 20 # number of points to display
current_price = 150.0
prices = []

try:
while True:
#code by Madhav :)
current_price = get_stock_price(stock_ticker)
if current_price is not None:
current_time = time.time() - start_time
time_series_data.append(current_price)
time_points.append(current_time)

# Update plot data
line.set_xdata(time_points)
line.set_ydata(time_series_data)

# Adjust plot limits dynamically
ax.relim()
ax.autoscale_view()

# Redraw the plot
fig.canvas.draw()
fig.canvas.flush_events()
current_price = get_stock_price(current_price)
prices.append(current_price)
if len(prices) > max_points:
prices.pop(0)

time.sleep(1) # Update every second
draw_graph(prices)
print(f"Time: {datetime.datetime.now().strftime('%H:%M:%S')}")
time.sleep(1)

except KeyboardInterrupt:
print("\nStopping real-time plot.")
plt.ioff()
plt.show()
print("\nStopped real-time plotting.")

# Run the program
if __name__ == "__main__":
main()