<jupyter_start><jupyter_text>COVID-19 бойынша АРИМА моделін болжау  Библиотекаларды импорттау<jupyter_code>from statsmodels.tsa.arima_model import ARIMA
from plotly.subplots import make_subplots
import matplotlib.pyplot as plt
import plotly.graph_objs as go
import plotly.express as px
import numpy as np
import pandas as pd

import os
import warnings
warnings.filterwarnings(action='ignore')<jupyter_output><empty_output><jupyter_text>Расталған Жағдайлардың Жалпы Саны<jupyter_code>url1 = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"
df_confirmed = pd.read_csv(url1)
country = "Kazakhstan"
df_confirmed.head()<jupyter_output><empty_output><jupyter_text>Өлім Жағдайларының Жалпы Саны<jupyter_code>url2 = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv"
df_deaths = pd.read_csv(url2)
df_deaths.head()<jupyter_output><empty_output><jupyter_text>Емделіп Шыққан Жағдайлардың Жалпы Саны<jupyter_code>url3 = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv"
df_recovered = pd.read_csv(url3)
df_recovered.head()<jupyter_output><empty_output><jupyter_text>Визуализациялау<jupyter_code>import datetime
import matplotlib.dates as mdates
country = 'Kazakhstan'
dates = list(df_confirmed.columns[4:])
dates = list(pd.to_datetime(dates))
dates_kz = dates[8:]

df1 = df_confirmed.groupby('Country/Region').sum().reset_index()
df2 = df_deaths.groupby('Country/Region').sum().reset_index()
df3 = df_recovered.groupby('Country/Region').sum().reset_index()

confirmed = df1[df1['Country/Region'] ==
                country].loc[:, '1/30/20':].values.tolist()[0]
deaths = df2[df2['Country/Region'] ==
             country].loc[:, '1/30/20':].values.tolist()[0]
recovered = df3[df3['Country/Region'] ==
                country].loc[:, '1/30/20':].values.tolist()[0]

active = list(map(int.__sub__, list(
    map(int.__sub__, confirmed, deaths)), recovered))

fig = plt.figure(figsize=(16, 12))
plt.suptitle('Қазақстанда белсенді, сауыққандар, қайтыс болғандар')


plt.plot()
plt.bar(dates_kz, active, color='green', alpha=0.8, label='Белсенді')
plt.bar(dates_kz, recovered, color='grey', label='Сауыққандар')
plt.bar(dates_kz, deaths, color='red', label='Өлім')

plt.title('Қазақстан')
plt.legend()
plt.show()
dates = list(df_confirmed.columns[4:])
dates = list(pd.to_datetime(dates))
dates_kz = dates[8:]
df1 = df_confirmed.groupby('Country/Region').sum().reset_index()
df2 = df_deaths.groupby('Country/Region').sum().reset_index()
df3 = df_recovered.groupby('Country/Region').sum().reset_index()

k = df1[df1['Country/Region'] == country].loc[:, '1/30/20':]
kz_confirmed = k.values.tolist()[0]

k = df2[df2['Country/Region'] == country].loc[:, '1/30/20':]
kz_deaths = k.values.tolist()[0]

k = df3[df3['Country/Region'] == country].loc[:, '1/30/20':]
kz_recovered = k.values.tolist()[0]

plt.figure(figsize=(15, 10))
plt.xticks(rotation=90, fontsize=11)
plt.yticks(fontsize=10)
plt.xlabel("Уақыты", fontsize=20)
plt.ylabel('Жалпы саны', fontsize=20)
plt.title("Қазақстанда жалпы расталған, белсенді, өлім", fontsize=20)

ax1 = plt.plot_date(y=kz_confirmed, x=dates_kz,
                    label='Расталған', linestyle='-', color='b')
ax2 = plt.plot_date(y=kz_recovered, x=dates_kz,
                    label='Сауыққан', linestyle='-', color='g')
ax3 = plt.plot_date(y=kz_deaths, x=dates_kz, label='Өлім',
                    linestyle='-', color='r')
plt.legend()<jupyter_output><empty_output><jupyter_text>Өсу Коэффициентін Есептеу<jupyter_code>k = df1[df1['Country/Region'] == country].loc[:, '3/13/20':]
kz_confirmed = k.values.tolist()[0]

growth_diff = []

for i in range(1, len(kz_confirmed)):
    growth_diff.append(kz_confirmed[i] / kz_confirmed[i-1])

growth_factor = sum(growth_diff)/len(growth_diff)
print('Орташа өсу коэффициенті', growth_factor)
prediction_dates = []

start_date = dates_kz[len(dates_kz) - 1]
for i in range(15):
    date = start_date + datetime.timedelta(days=1)
    prediction_dates.append(date)
    start_date = date
previous_day_cases = confirmed[len(dates_kz) - 1]
predicted_cases = []

for i in range(15):
    predicted_value = previous_day_cases * growth_factor
    predicted_cases.append(predicted_value)
    previous_day_cases = predicted_value

plt.figure(figsize=(15, 10))
plt.xticks(rotation=90, fontsize=11)
plt.yticks(fontsize=10)
plt.xlabel("Уақыты", fontsize=20)
plt.ylabel('Жалпы саны', fontsize=20)
plt.title("Алдағы 15 күнге болжамды мәндер", fontsize=20)
ax1 = plt.plot_date(y=predicted_cases, x=prediction_dates,
                    linestyle='-', color='c')
k = df1[df1['Country/Region'] == country].loc[:, '3/13/20':]
kz_confirmed = k.values.tolist()[0]
data = pd.DataFrame(columns=['ds', 'y'])
data['ds'] = dates[len(dates)-len(kz_confirmed):]
data['y'] = kz_confirmed<jupyter_output><empty_output><jupyter_text>Модельді генерациялау және сәйкестендіру<jupyter_code>arima = ARIMA(data['y'], order=(5, 1, 0))
arima = arima.fit(trend='c', full_output=True, disp=True)
forecast = arima.forecast(steps=30)
pred = list(forecast[0])

start_date = data['ds'].max()
prediction_dates = []
for i in range(30):
    date = start_date + datetime.timedelta(days=1)
    prediction_dates.append(date)
    start_date = date
plt.figure(figsize=(16, 8))
plt.xlabel("Уақыты", fontsize=20)
plt.ylabel('Жалпы саны', fontsize=20)
plt.title("Келесі 30 күнге болжанатын мәндер", fontsize=20)

plt.plot_date(y=pred, x=prediction_dates, linestyle='dashed',
              color='red', label='Болжанған')
plt.plot_date(y=data['y'], x=data['ds'], linestyle='-',
              color='blue', label='Нақты')
plt.legend()
pred_res = []
for i in pred:
    i = int(i)
    pred_res.append(i)
arima = ARIMA(data['y'][:-5], order=(5, 1, 0))
arima = arima.fit(trend='c', full_output=True, disp=True)
forecast = arima.forecast(steps=30)
pred1 = list(forecast[0])

start_date1 = data['ds'].iloc[-6]
prediction_dates1 = []
for i in range(30):
    date1 = start_date1 + datetime.timedelta(days=1)
    prediction_dates1.append(date1)
    start_date1 = date1
print(arima.summary())<jupyter_output>ARIMA Model Results                              
==============================================================================
Dep. Variable:                    D.y   No. Observations:                  275
Model:                 ARIMA(5, 1, 0)   Log Likelihood               -2349.776
Method:                       css-mle   S.D. of innovations           1242.910
Date:                Sat, 19 Dec 2020   AIC                           4713.552
Time:                        15:34:25   BIC                           4738.870
Sample:                             1   HQIC                          4723.713
                                                                              
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const        672.1124    162.486      4.136      0.0[...]<jupyter_text>Уақыт Қатарларын Болжау<jupyter_code>pred_res = []
for i in pred1:
    i = int(i)
    pred_res.append(i)
confirmed_dates = pd.DataFrame()
confirmed_dates['Date'] = data['ds']
confirmed_dates.tail()
pred_dates = pd.DataFrame()
pred_dates['Date'] = prediction_dates
pred_dates.head()
cc = []
for a in data['y'].iloc[-5:]:
    cc.append(a)
for b in ['NA', 'NA', 'NA', 'NA', 'NA']:
    cc.append(b)
dates = []
for i in confirmed_dates['Date'][-5:]:
    dates.append(i)
for j in pred_dates['Date'][:5]:
    dates.append(j)<jupyter_output><empty_output><jupyter_text>Модельдің Тиімділігін Бағалау![image.png](attachment:image.png)<jupyter_code># Mean Absolute Percentage error(MAPE)
MAPE = np.mean(np.abs(np.array(cc[:5]) -
                      np.array(pred_res[:5]))/np.array(cc[:5]))
print("MAPE-тың мәні = " + str(MAPE*100) + " %")<jupyter_output>MAPE-тың мәні = 0.07987334687076983 %<jupyter_text>Нәтиже<jupyter_code>month_pred = pd.DataFrame()
month_pred['Аурудың болжамды жағдайлары 30 күн ішінде'] = pred_res
month_pred
r = pd.DataFrame()
r['Уақыты'] = dates
r['Расталған Жағдайлар'] = cc
r['Болжамдалған Жағдайлар'] = pred_res[:10]
r['Модельдің дәлдігі % бойынша'] = str(float(1-MAPE)*100)[:5]
r<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17856304296783282, 'fraction_numerical': 0.03721530875792439, 'mean_word_length': 4.175577156743621, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 40, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '459464', 'license': 'MIT', 'n_tokens_mistral': 3526, 'n_tokens_neox': 3447, 'n_words': 494, 'path': '.ipynb_checkpoints/Project COVID19 prediction ARIMA-checkpoint.ipynb', 'repo_name': 'yeltayzhastay/COVID19TimeForecasting', 'size': '8518'}