Setup
First we import the required libraries, together with yfinance for fetching the inventory information.
import reflex as rx
from reflex_ag_grid import ag_grid
import yfinance as yf
from datetime import datetime, timedelta
import pandas as pd
Fetching and remodeling information
Subsequent, we outline the State class, which accommodates the appliance’s state and logic. The fetch_stock_data
operate fetches inventory information for the desired corporations and transforms it right into a format appropriate for show in AG Grid. We name this operate when clicking on a button, by linking the on_click
set off of the button to this state operate.
We outline state variables, any fields in your app that will change over time (A State Var is straight rendered into the frontend of the app).
The information
state variable shops the uncooked inventory information fetched from Yahoo Finance. We rework this information to around the values and retailer it as an inventory of dictionaries, which is the format that AG Grid expects. The reworked information is sorted by date and ticker in descending order and saved within the dict_data
state variable.
The datetime_now
state variable shops the present datetime when the info was fetched.
# The listing of corporations to fetch information for
corporations = ["AAPL", "MSFT", "GOOGL", "AMZN", "META"]class State(rx.State):
# The information fetched from Yahoo Finance
information: pd.DataFrame
# The information to be displayed within the AG Grid
dict_data: listing[dict] = [{}]
# The datetime of the present fetched information
datetime_now: datetime = datetime.now()
def fetch_stock_data(self):
self.datetime_now = datetime.now()
start_date = self.datetime_now - timedelta(days=180)
# Fetch information for all tickers in a single obtain
self.information = yf.obtain(corporations, begin=start_date, finish=self.datetime_now, group_by='ticker')
rows = []
for ticker in corporations:
# Examine if the DataFrame has a multi-level column index (for a number of tickers)
if isinstance(self.information.columns, pd.MultiIndex):
ticker_data = self.information[ticker] # Choose the info for the present ticker
else:
ticker_data = self.information # If just one ticker, no multi-level index exists
for date, row in ticker_data.iterrows():
rows.append({
"ticker": ticker,
"date": date.strftime("%Y-%m-%d"),
"open": spherical(row["Open"], 2),
"excessive": spherical(row["High"], 2),
"mid": spherical((row["High"] + row["Low"]) / 2, 2),
"low": spherical(row["Low"], 2),
"shut": spherical(row["Close"], 2),
"quantity": int(row["Volume"]),
})
self.dict_data = sorted(rows, key=lambda x: (x["date"], x["ticker"]), reverse=True)
rx.button(
"Fetch Newest Information",
on_click=State.fetch_stock_data,
)