-
Notifications
You must be signed in to change notification settings - Fork 1
Use auto-arima to forecast live data #93
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MCLiii
wants to merge
3
commits into
main
Choose a base branch
from
forecasting
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,8 @@ | ||
| from fastapi import APIRouter | ||
| from . import graph_api, record_data | ||
| from . import graph_api, record_data, forecast | ||
|
|
||
| router = APIRouter() | ||
|
|
||
| router.include_router(graph_api.router) | ||
| router.include_router(record_data.router) | ||
| router.include_router(record_data.router) | ||
| router.include_router(forecast.router) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| from fastapi import APIRouter | ||
| from core import db | ||
| import config | ||
| from statsmodels.tsa.arima.model import ARIMA | ||
| from pmdarima.arima import auto_arima | ||
| import pandas as pd | ||
| import time | ||
| import asyncio | ||
| from concurrent.futures import ProcessPoolExecutor | ||
|
|
||
| router = APIRouter() | ||
|
|
||
| def train_arima(df, forecast_step): | ||
| # Train the model | ||
| model = auto_arima(df, seasonal=False, m=12) | ||
| # Forecast the future data | ||
| forecast = model.predict(n_periods=forecast_step) | ||
| return forecast | ||
|
|
||
| @router.get("/forecast") | ||
| async def get_forecast(data: str, start_time: int = 0, end_time: int = 0, forecast_step: int = 0): | ||
| '''Using ARIMA to predict the future data on selected dataset | ||
| :param data: str: dataset name | ||
| :param start_time: int: start time of the training data | ||
| :param end_time: int: end time of the training data | ||
| :param forecast_step: int: the time to forecast | ||
| ''' | ||
| # If time is not specified, use current time as end time and 5 min ago as start time for forecast 1 min | ||
| if end_time == 0: | ||
| end_time = round(time.time() * 1000) | ||
| if start_time == 0: | ||
| start_time = end_time - 300000 | ||
| if forecast_step == 0: | ||
| forecast_step = 100 | ||
|
|
||
| # Query the data | ||
| df = await db.query([data], start_time, end_time, ['avg'], (end_time - start_time) // 60) | ||
|
|
||
| # relabel the column to 'x','y' | ||
| df.columns = ['y'] | ||
| # Spawn a new async task to train ARIMA in a separate process | ||
| loop = asyncio.get_event_loop() | ||
| with ProcessPoolExecutor() as pool: | ||
| future = loop.run_in_executor(pool, train_arima, df, forecast_step) | ||
| forecast = await future | ||
|
|
||
| # relabel the index to start from 1 to length | ||
| forecast.reset_index(drop=True, inplace=True) | ||
| forecast.index = (forecast.index * (end_time - start_time) // 60) + end_time | ||
| # create json response | ||
| response = [{'x': int(forecast.index[i]), 'y': forecast[forecast.index[i]]} for i in range(len(forecast))] | ||
| return {'response': {data: response}} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -21,6 +21,7 @@ import { | |||||
| Text, | ||||||
| useColorMode, | ||||||
| useDisclosure, | ||||||
| useInterval, | ||||||
| } from "@chakra-ui/react"; | ||||||
| import { | ||||||
| Chart as ChartJS, | ||||||
|
|
@@ -71,7 +72,7 @@ for (const category of GraphData.Output) { | |||||
| } | ||||||
|
|
||||||
| // the options fed into the graph object, save regardless of datasets | ||||||
| function getOptions(now, secondsRetained, colorMode, optionInfo, extremes) { | ||||||
| function getOptions(now, secondsRetained, colorMode, optionInfo, extremes, xaxisbounds) { | ||||||
| const gridColor = getColor("grid", colorMode); | ||||||
| const gridBorderColor = getColor("gridBorder", colorMode); | ||||||
| const ticksColor = getColor("ticks", colorMode); | ||||||
|
|
@@ -125,12 +126,22 @@ function getOptions(now, secondsRetained, colorMode, optionInfo, extremes) { | |||||
| label: (item) => { | ||||||
| // custom dataset label | ||||||
| // name: value unit | ||||||
| if (item.dataset.key.indexOf("_forcast") !== -1) { | ||||||
| return `${item.dataset.label}: ${item.formattedValue}`; | ||||||
| } | ||||||
| return `${item.dataset.label}: ${item.formattedValue} ${optionInfo[item.dataset.key].unit}`; | ||||||
| }, | ||||||
| labelColor: (item) => { | ||||||
| return { | ||||||
| borderColor: optionInfo[item.dataset.key].borderColor, | ||||||
| backgroundColor: optionInfo[item.dataset.key].backgroundColor | ||||||
| if (item.dataset.key.indexOf("_forcast") !== -1) { | ||||||
| return { | ||||||
| borderColor: "red", | ||||||
| backgroundColor: "rgba(255, 0, 0, 0.5)" | ||||||
| } | ||||||
| } else { | ||||||
| return { | ||||||
| borderColor: optionInfo[item.dataset.key].borderColor, | ||||||
| backgroundColor: optionInfo[item.dataset.key].backgroundColor | ||||||
| } | ||||||
| } | ||||||
| }, | ||||||
| }, | ||||||
|
|
@@ -157,9 +168,9 @@ function getOptions(now, secondsRetained, colorMode, optionInfo, extremes) { | |||||
| borderWidth: 2, | ||||||
| }, | ||||||
|
|
||||||
| // show the last secondsRetained seconds | ||||||
| max: DateTime.fromMillis(Math.floor(now/1000) * 1000).toISO(), | ||||||
| min: DateTime.fromMillis((Math.floor(now/1000) - secondsRetained) * 1000).toISO(), | ||||||
| // round to the nearest second | ||||||
| max: Math.round(xaxisbounds.max/1000)*1000, | ||||||
| min: Math.round(xaxisbounds.min/1000)*1000, | ||||||
| }, | ||||||
| y: { | ||||||
| suggestedMin: extremes[0], | ||||||
|
|
@@ -200,9 +211,10 @@ function getOptions(now, secondsRetained, colorMode, optionInfo, extremes) { | |||||
| * @constructor | ||||||
| */ | ||||||
| function Graph(props) { | ||||||
| const { querylist, histLen, colorMode, optionInfo, extremes } = props; | ||||||
| const { querylist, histLen, colorMode, optionInfo, extremes, forcastKey } = props; | ||||||
| // response from the server | ||||||
| const [data, setData] = useState([]); | ||||||
| const [forcastData, setForcastData] = useState([]); | ||||||
| const [fetchDep, setFetchDep] = useState(true); | ||||||
|
|
||||||
| const fetchData = useCallback(async () => { | ||||||
|
|
@@ -239,7 +251,19 @@ function Graph(props) { | |||||
| } | ||||||
| }, [querylist, histLen]); | ||||||
| useEffect(fetchData, [fetchDep]); | ||||||
|
|
||||||
|
|
||||||
| // fetch forcast data every 10 seconds | ||||||
| useInterval(() => { | ||||||
| if (forcastKey) { | ||||||
| const now = Date.now(); | ||||||
| fetch(ROUTES.GET_FORECAST_DATA + `?data=${forcastKey}&start_time=${now - (histLen + 1) * 1000}&end_time=${now}&forecast_step=0`) | ||||||
| .then((response) => response.json()) | ||||||
| .then((data) => { | ||||||
| setForcastData(data.response); | ||||||
| }); | ||||||
| } | ||||||
| }, 10000); | ||||||
| console.log(forcastData); | ||||||
|
||||||
| console.log(forcastData); | |
| // Removed unnecessary console.log statement for production. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] Using a hardcoded value (-10000) to replace infinity may be confusing. Consider adding a comment or refactoring this logic into a named constant to clarify its purpose and allow for easier adjustments in the future.