Skip to content

Business intelligence made simple

Added Prophet forecasting

Andrew Kane648ba63b97ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8fa30d5a..d8f0e9e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,7 @@
## 2.2.2 (unreleased)
- Added experimental support for the Socrata Open Data API (SODA)
+- Added Prophet forecasting
## 2.2.1 (2019-10-08)
diff --git a/README.md b/README.md
index 479d16f1..fbfdf732 100644
--- a/README.md
+++ b/README.md
@@ -426,10 +426,32 @@ If you’re on Heroku, follow [these additional instructions](#anomaly-detection
## Forecasting
-Blazer has experimental support for forecasting through [Trend](https://trendapi.org/).
+Blazer has experimental support for two different forecasting methods.
+
+A forecast link will appear for queries that return 2 columns with types timestamp and numeric.
[Example](https://blazer.dokkuapp.com/queries/18-forecast?forecast=t)
+## Prophet [master]
+
+**Note:** Prophet only supports daily forecasts right now.
+
+Add [prophet](https://github.com/ankane/prophet) to your Gemfile:
+
+```ruby
+gem 'prophet-rb'
+```
+
+And add to `config/blazer.yml`:
+
+```yml
+forecasting: prophet
+```
+
+## Trend
+
+[Trend](https://trendapi.org/) uses an external service.
+
Add [trend](https://github.com/ankane/trend) to your Gemfile:
```ruby
@@ -442,8 +464,6 @@ And add to `config/blazer.yml`:
forecasting: trend
```
-A forecast link will appear for queries that return 2 columns with types timestamp and numeric.
-
## Data Sources
Blazer supports multiple data sources :tada:
diff --git a/lib/blazer/result.rb b/lib/blazer/result.rb
index e69f42d1..1f6ade70 100644
--- a/lib/blazer/result.rb
+++ b/lib/blazer/result.rb
@@ -85,11 +85,45 @@ module Blazer
@forecastable ||= Blazer.forecasting && column_types == ["time", "numeric"] && @rows.size >= 10
end
+ # TODO cache it?
+ # don't want to put result data (even hashed version)
+ # into cache without developer opt-in
def forecast
- # TODO cache it?
- # don't want to put result data (even hashed version)
- # into cache without developer opt-in
- forecast = Trend.forecast(Hash[@rows], count: 30)
+ count = 30
+
+ case Blazer.forecasting
+ when "prophet"
+ require "prophet"
+
+ df =
+ Daru::DataFrame.new(
+ "ds" => @rows.map { |r| r[0] },
+ "y" => @rows.map { |r| r[1] }
+ )
+
+ # TODO determine frequency
+ freq = "D"
+
+ m = Prophet.new
+ m.fit(df)
+ future = m.make_future_dataframe(periods: count, freq: freq, include_history: false)
+ fcst = m.predict(future)
+ ds = fcst["ds"]
+ if @rows[0][0].is_a?(Date)
+ ds = ds.map { |v| v.to_date }
+ end
+ forecast = ds.zip(fcst["yhat"]).to_h
+ else
+ require "trend"
+
+ forecast = Trend.forecast(Hash[@rows], count: count)
+ end
+
+ # round integers
+ if @rows[0][1].is_a?(Integer)
+ forecast = forecast.map { |k, v| [k, v.round] }.to_h
+ end
+
@rows.each do |row|
row[2] = nil
end