<jupyter_start><jupyter_text>Project  Bitcoin Predictor  Now we'll grab the bitcoin market data and price history!<jupyter_code>import requests
import pandas as pd
from fbprophet import Prophet
from matplotlib import pyplot as plt
%matplotlib inline
bitcoin = 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=USD&days=365'
bit_coin = requests.get(bitcoin)
bit_json = bit_coin.json()
type(bit_json)
bitcoin_prices = bit_json['prices']
bitcoin_df = pd.DataFrame(bitcoin_prices, columns=['DateTime', 'Prices'])
bitcoin_df.head()
bitcoin_df.shape<jupyter_output><empty_output><jupyter_text>First column is probably a raw data time column! and the other is price<jupyter_code>bitcoin_df['DateTime'] = pd.to_datetime(bitcoin_df['DateTime'], unit='ms') 
bitcoin_df.tail()
bitcoin_df.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
RangeIndex: 366 entries, 0 to 365
Data columns (total 2 columns):
DateTime    366 non-null datetime64[ns]
Prices      366 non-null float64
dtypes: datetime64[ns](1), float64(1)
memory usage: 5.8 KB<jupyter_text>Calculate a rolling mean value by taking the prices column, the last 28 values(days), and calculating the average for those 28 values, finally filling the first 28 (blank) values with the value from the first mean value<jupyter_code>bitcoin_df['rolling_mean_price'] = bitcoin_df['Prices'].rolling(28).mean().fillna(method='bfill')
bitcoin_df.head()
plt.figure(figsize=(10,8))
plt.plot(bitcoin_df['DateTime'], bitcoin_df['Prices'])
plt.plot(bitcoin_df['DateTime'], bitcoin_df['rolling_mean_price'])

plt.xticks(rotation=-45)
plt.legend()<jupyter_output><empty_output><jupyter_text>Let's upscale Compare to train data Predict future values Play around with how many days<jupyter_code>bitcoin_df = bitcoin_df.set_index('DateTime').drop(columns='rolling_mean_price')
bitcoin_df.head()
upsample_series = bitcoin_df['Prices'].resample('H')
linear_upsample = upsample_series.interpolate()
cubic_upsample = upsample_series.interpolate(method='cubic')
quadratic_upsample = upsample_series.interpolate(method='quadratic')

linear_upsample.head(3)
cubic_upsample.head(3)
quadratic_upsample.head(3)
linear_upsample.shape
plt.figure(figsize=(16,10))

plt.plot(bitcoin_df.index[:20], bitcoin_df['Prices'][:20])
plt.plot(linear_upsample.index[:480], linear_upsample[:480])
plt.plot(cubic_upsample.index[:480], cubic_upsample[:480])
plt.plot(quadratic_upsample.index[:480], quadratic_upsample[:480])

plt.legend(['Normal Prices', 'Linear Upsample', 'Cubic Upsample', 'Quadratic Upsample'])
plt.show()<jupyter_output><empty_output><jupyter_text>Separate some of the final rows of our hourly predictions for test data<jupyter_code>linear_df = linear_upsample.to_frame()
cubic_df = cubic_upsample.to_frame()
quadratic_df = quadratic_upsample.to_frame()
linear_prophet = linear_df.reset_index().rename(columns={'DateTime': 'ds', 'Prices': 'y'}).iloc[:8689]
cubic_prophet = cubic_df.reset_index().rename(columns={'DateTime': 'ds', 'Prices': 'y'}).iloc[:8689]
quadratic_prophet = quadratic_df.reset_index().rename(columns={'DateTime': 'ds', 'Prices': 'y'}).iloc[:8689]<jupyter_output><empty_output><jupyter_text>I have here deleted the final 51 hourly values for my bitcoin data - I can now use Prophet to detect which of the models is best: linear, cubic, or quadratic! Now, let's use Prophet on our Test Data! First, for linear model:<jupyter_code>mlin = Prophet()
mlin.fit(linear_prophet)
linear_test = mlin.make_future_dataframe(periods=51, freq = 'H', include_history=False)
forecast_linear_test = mlin.predict(linear_test)
forecast_linear_test[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].head()
forecast_linear_test[['ds','yhat']].head()
fig_lin = mlin.plot(forecast_linear_test) # The blue part is the actual forecast
None<jupyter_output><empty_output><jupyter_text>Second, the cubic model:<jupyter_code>mcub = Prophet()

mcub.fit(cubic_prophet)

cubic_test = mcub.make_future_dataframe(periods=51, freq = 'H', include_history=False)

forecast_cubic_test = mcub.predict(cubic_test)
forecast_cubic_test[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].head()
fig_cub = mlin.plot(forecast_linear_test) # The blue part is the actual forecast
None<jupyter_output><empty_output><jupyter_text>Finally, for the quadratic model:<jupyter_code>mquad = Prophet()

mquad.fit(quadratic_prophet)

quadratic_test = mquad.make_future_dataframe(periods=51, freq = 'H', include_history=False)

forecast_quadratic_test = mquad.predict(quadratic_test)
forecast_quadratic_test[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].head()
fig_quad = mquad.plot(forecast_quadratic_test) # The blue part is the actual forecast
None<jupyter_output><empty_output><jupyter_text>Now we can compare this to our actual data in the original bitcoin dataframe! We can see which is the best predictor  Now let's plot it with ALL the data and find out what the predictions will be for the next 2 days!<jupyter_code>bitcoin_df.tail(3)
print(forecast_linear_test[['ds', 'yhat']].iloc[23])
print(forecast_linear_test[['ds', 'yhat']].iloc[47])
print(forecast_cubic_test[['ds', 'yhat']].iloc[23])
print(forecast_cubic_test[['ds', 'yhat']].iloc[47])
print(forecast_quadratic_test[['ds', 'yhat']].iloc[23])
print(forecast_quadratic_test[['ds', 'yhat']].iloc[47])<jupyter_output>ds      2019-05-02 00:00:00
yhat                5418.79
Name: 23, dtype: object
ds      2019-05-03 00:00:00
yhat                5409.87
Name: 47, dtype: object<jupyter_text>It seems like just about the linear prediction for prophet is marginally better than the rest so let's run our prediction on that!<jupyter_code>linear_model = linear_df.reset_index().rename(columns={'DateTime': 'ds', 'Prices': 'y'})
m = Prophet()

m.fit(linear_model)

linear_future = m.make_future_dataframe(periods=70, freq = 'H', include_history=False)

forecast_linear = m.predict(linear_future)
forecast_linear[['ds','yhat', 'yhat_lower', 'yhat_upper']].tail(20)
fig_linear_future = m.plot(forecast_linear) # The blue part is the actual forecast
None<jupyter_output><empty_output><jupyter_text>Cubic prediction<jupyter_code>cubic_model = cubic_df.reset_index().rename(columns={'DateTime': 'ds', 'Prices': 'y'})
m = Prophet()

m.fit(cubic_model)

cubic_future = m.make_future_dataframe(periods=70, freq = 'H', include_history=False)

forecast_cubic = m.predict(cubic_future)
forecast_cubic[['ds','yhat', 'yhat_lower', 'yhat_upper']].iloc[38]
forecast_cubic[['ds','yhat', 'yhat_lower', 'yhat_upper']].iloc[62]<jupyter_output><empty_output><jupyter_text>Quadratic Model<jupyter_code>quadratic_model = quadratic_df.reset_index().rename(columns={'DateTime': 'ds', 'Prices': 'y'})
m = Prophet()

m.fit(quadratic_model)

quadratic_future = m.make_future_dataframe(periods=70, freq = 'H', include_history=False)

forecast_quadratic = m.predict(quadratic_future)
forecast_quadratic[['ds','yhat', 'yhat_lower', 'yhat_upper']].iloc[38]
forecast_quadratic[['ds','yhat', 'yhat_lower', 'yhat_upper']].iloc[62]<jupyter_output><empty_output><jupyter_text>Other work trying to make a big ol' dataframe<jupyter_code>test_df = pd.concat([linear_df, cubic_df, quadratic_df], axis=1)
symbols = ['Linear Prices','Cubic Prices', 'Quadratic Prices']
test_df.columns = symbols
test_df.head()
df = test_df.reset_index().iloc[8688:]
df
# plot_components = m.plot_components(forecast)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13824570961590849, 'fraction_numerical': 0.02329065649686734, 'mean_word_length': 8.499353169469599, 'pattern_counts': {'":': 0, '<': 52, '<?xml version=': 0, '>': 52, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '260354', 'license': 'MIT', 'n_tokens_mistral': 2821, 'n_tokens_neox': 2661, 'n_words': 518, 'path': 'Project_4_BitcoinPredictor_Prophet.ipynb', 'repo_name': 'maximcondon/Project_TimeSeries', 'size': '7342'}