Setup
First we import the mandatory 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 comprises the applying’s state and logic. The fetch_stock_data
perform fetches inventory information for the required corporations and transforms it right into a format appropriate for show in AG Grid. We name this perform when clicking on a button, by linking the on_click
set off of the button to this state perform.
We outline state variables, any fields in your app which will change over time (A State Var is immediately rendered into the frontend of the app).
The information
state variable shops the uncooked inventory information fetched from Yahoo Finance. We remodel this information to around the values and retailer it as a listing of dictionaries, which is the format that AG Grid expects. The remodeled 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 information was fetched.
# The record 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: record[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 information 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,
)