Building a Streaming Stock Charts Component

How can be built a component that can give me streaming data for candles of 1 min and 5 mins of Tesla/Apple/Microsoft… etc ?

Something similar to this:

Thanks!

Hi @axislumens,

I would start by finding a REST API that handles this kind of data, parse the results in GH (or elsewhere and stream as .csv or .json) and go from there.

Something like this (I can’t endorse this as I’ve never tried it, just a quick google search as an example):

or this (historical candle data):
https://kite.trade/docs/connect/v3/historical/

I don’t have much experience with fintech APIs so hopefully another user will weigh in.

Maybe this will be a starting point.

But essentially you will need to stream the data or at least refresh it every so often, then parse that data into some kind of point/line based graph representation of the data and then visually style it in Grasshopper as geometry or whatever, or as a UI interface.

Also it depends on what you want the end result to be/look like.

More specifics would be helpful

Thank you really much for the answer.

Yes, the result I am searching is like this:

Basically:
the open and close prices
high and low prices
and showing the volume below.

This should be drawn automatically each minute.

Makes sense.

-You could represent that by plotting the “graph points” across XY screen or world space.
-Draw the thin candle line based on the data for each “graph point”
-Draw the thick candle line based on the data for each “graph point”

You can create Model Linetype with varying thickness to graphically represent the candles.
This would be easier and more performant than creating surfaces/rectangles.

-You would set a trigger/timer/or event that would update the script on 1 minute intervals or whatever.

Keep in mind if you go the REST API route, often times API charge money per call volume.

However at 60 calls an hour for a single user (to get the latest data every minute) that’s only 1,440 calls per day if you were running for 24 hours straight.

A lot of APIs give you free access under 1,000 or 10,000 calls for non commercial use.

Mileage will vary with each data provider of course… some aren’t free at all.

Again I go to what is the end result though?

If it’s only graphic representation… you’re better off doing a web view embed in grasshopper canvas or Rhino that shows an existing webpage with the search query you are after.

If you are after the actual geometry/lines of the chart then yes you would need to likely parse data into grasshopper to manipulate and create geometry from.

Is really great idea to plot the candles as line thickness! thanks Michael!

Yes, I go for the REST API,
how can I start?
I imagine I have to code a component, but I dont know about coding…
Could be the first time!

Yes the end result is to have it on gh as geometry to study.

1 Like

You can get the data for free from yahoo usiny yfinance api

You get back a pandas frame that you have to parse, but that’s trivially easy.

Check this Demo

2 Likes

Thanks for sharing that! Unfortunately it looks like the smallest interval it can handle is day and not the 1 minute interval @axislumens is hoping for.

Unless that’s just the example and it can return minute and 5 minute intervals?

See here on the page you linked:

  • interval: {“1d”, “1wk”, “1mo”}. Refers to the interval to sample the data: “1d”= daily, “1wk”= weekly, “1mo”=monthly.

@axislumens while you certainly can and should go the route of learning to code if you like doing specific things like in GH like parsing web data, there are existing plugins you could use if you are open to that.

One that comes to mind is jSwan which let’s you parse .json via REST API get requests.

And of course there’s going the scripting module route which is more what @adel.albloushi is talking about with the panda frame.

1 Like

It can return 1 minute, but the time span is smaller

1 Like

Nice!

i have some old code, maybe you’d like to try it out

import yfinance as yf
import tkinter as tk
from tkinter import simpledialog, messagebox, Frame, Label
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def get_stock_history(ticker):
    stock = yf.Ticker(ticker)
    data = stock.history(period='1d', interval='1m')
    return data['Close']

def get_current_price(ticker):
    stock = yf.Ticker(ticker)
    data = stock.history(period='1d')
    return data['Close'][0]

def update_current_price_label(ticker):
    try:
        current_price = get_current_price(ticker)
        current_price_label.config(text=f"Current Price: ${current_price:.2f}")
    except Exception as e:
        messagebox.showerror("Error", f"Couldn't fetch current price for {ticker}.\nError: {str(e)}")

def plot_graph(ticker):
    try:
        data = get_stock_history(ticker)
        fig, ax = plt.subplots(figsize=(10, 6))
        data.plot(kind='line', ax=ax)
        ax.set_title(f"{ticker} Stock Price Per Minute (current day)")
        ax.set_ylabel('Price')
        ax.set_xlabel('Date')

        # Clear previous graphs (if any) and display the new one
        for widget in frame.winfo_children():
            widget.destroy()

        canvas = FigureCanvasTkAgg(fig, master=frame)
        canvas.draw()
        canvas.get_tk_widget().pack()

    except Exception as e:
        messagebox.showerror("Error", f"Couldn't fetch graph data for {ticker}.\nError: {str(e)}")

def update_graph():
    ticker = ticker_entry.get()
    plot_graph(ticker)
    update_current_price_label(ticker)
    root.after(60000, update_graph)  # Schedule next update in 60 seconds (60000 milliseconds)

# GUI setup
root = tk.Tk()
root.title("Stock Price Tracker")

lbl = tk.Label(root, text="Enter Stock Ticker:")
lbl.pack(pady=10)

ticker_entry = tk.Entry(root)
ticker_entry.pack(pady=10)

btn = tk.Button(root, text="Show Graph", command=update_graph)
btn.pack(pady=10)

current_price_label = Label(root, text="Current Price: $0.00", font=("Arial", 12, "bold"))
current_price_label.pack(pady=10)

frame = Frame(root)
frame.pack(pady=20, padx=20)

root.mainloop()

This looks really cool:

you shouldn’t need this with py3 and yfianance. if only there was an easy way to install modules/packages

@eirannejad


getting partially initialized module ... error. any ideas?

1 Like

@eirannejad seems to work after a restart…

@axislumens open this in rhino 8, let the python script download what it needs, restart rhino and open again
unnamed.gh (10.1 KB)

I am using Rhino 6 at the moment … is it possible with Rh6?

unfortunately i no longer have rhino 6, so i don’t know…

I can test to put the python code you write, coudl you paste it?

# r: pandas
# r: yfinance

import locale
locale.setlocale(locale.LC_ALL, 'en_US')

import pandas as pd
import numpy as np
import yfinance as yf

def get_stock_history(ticker):
    stock = yf.Ticker(ticker)
    data = stock.history(period='max', interval='1m')
    return data['Close']

prices = get_stock_history(ticker)
print(prices)

thanks,
could we try to write it on this ?

I can use it from rh6 and it supports python 3