|
From the previous value of the time series, exponential smoothing, twice a predicted estimate the next time.
Python code is as follows:
forecast.py
# - * - Coding: utf-8 - * -
# Time: 2015.11.25 sangjin
__author__ = 'hunterhug'
import matplotlib
# Matplotlib.use ( "Agg")
# Matplotlib.use ( "TkAgg")
# Matplotlib.use ( "gtk")
import matplotlib.pyplot as plt
from matplotlib.pyplot import savefig
from matplotlib.font_manager import FontProperties
from operator import itemgetter
# Read execel use (support 07)
from openpyxl import Workbook
# Write excel using (support 07)
from openpyxl import load_workbook
import os
def judgefile ():
path = input ( "Please enter the excel file name of the directory:") # file path
if os.path.isfile (path):
return path.lower ()
else:
print ( "File does not exist")
return judgefile ()
def writeexcel07 (path, content, name = 'Sheet1', sheetnum = 0):
wb = Workbook ()
# Sheet = wb.add_sheet ( "xlwt3 Test Data Form")
sheet = wb.create_sheet (sheetnum, name)
# Values = [[ "name", "Hadoop programming combat", "hbase actual programming", "lucene real programming"], [ "price", "52.3", "45", "36"], [ "Press "" Machinery industry Press, "" Posts & Telecom Press "," Chinese People's Publishing House "], [" Chinese layout "," medium "," English "," English "]]
for i in range (0, len (content)):
for j in range (0, len (content [i])):
sheet.cell (row = i + 1, column = j + 1) .value = content [i] [j]
# Sheet.cell (row = 1, column = 2) .value = "temperature"
wb.save (path)
print ( "write data successfully!")
def read07excel (path):
excelcontent = []
wb2 = load_workbook (path)
sheetnames = wb2.get_sheet_names ()
ws = wb2.get_sheet_by_name (sheetnames [0])
row = ws.get_highest_row ()
col = ws.get_highest_column ()
# Print ( "series:", ws.get_highest_column ())
# Print ( "line number:", ws.get_highest_row ())
for i in range (0, row):
rowcontent = []
for j in range (0, col):
if ws.rows [i] [j] .value:
rowcontent.append (ws.rows [i] [j] .value)
excelcontent.append (rowcontent)
print ( "read data successfully!")
return excelcontent
def calvalue (excel, a):
date = [] # x label date
data = [] # y label data
for i in range (2, len (excel) -1):
data.append (float (excel [i] [1]))
date.append (excel [i] [0])
e1 = [data [0]] # one time forecast
for i in range (0, len (data)):
next = data [i] * a + e1 [i] * (1 - a)
e1.append (next)
e1e = [] # one time absoultion error
for i in range (0, len (data)):
e1e.append (abs (data [i] -e1 [i]))
e1e2 = sum (e1e)
e2 = [data [0]] # second time forecast
for i in range (0, len (data)):
next = e1 [i] * a + e2 [i] * (1 - a)
e2.append (next)
e2e = [] # second time absoultion error
for i in range (0, len (data)):
e2e.append (abs (data [i] -e2 [i]))
e2e2 = sum (e2e)
e1y = e1 [len (e1) -1] # one time forecast value
e2y = e2 [len (e2) -1] # two time forecast value
return [a, e1y, e2y, e1e2, e2e2]
def calvaluetop5 (excel, step = 0.01):
initvalue = 1.0
all = []
top5 = []
while initvalue <= 1.0 and initvalue> = 0:
all.append (calvalue (excel, initvalue))
initvalue = initvalue -step
d = {}
for i in range (0, len (all)):
d.setdefault (i, all [i] [3])
d1 = sorted (d.items (), key = itemgetter (1))
#print (d1)
topnum = len (d1)
if topnum> = 5:
topnum = 5
else:
pass
for i in range (0, topnum):
pos = d1 [i] [0]
top5.append (all [pos])
return top5
def judgestep ():
try:
a = float (input ( "Please select the step size factor (range 0 ~ 1):")) # change var
except:
print ( "Please enter a number, okay ...")
return judgestep ()
while a> 1 or a <0:
print ( 'Enter the step length range is between 0-1')
return judgestep ()
return a
def judge ():
try:
a = float (input ( "Please enter the coefficient of variation of a:")) # change var
except:
print ( "Please enter a number, okay ...")
return judge ()
while a> 1 or a <0:
print ( 'coefficient of variation range between 0-1 inputs')
return judge ()
return a
def single (a, path):
excel = read07excel (path)
title1 = excel [0] [0]
title2 = excel [1]
# Print (excel)
title = ':'. join (excel [0])
date = [] # x label date
data = [] # y label data
for i in range (2, len (excel) -1):
data.append (float (excel [i] [1]))
date.append (excel [i] [0])
# Print ( '/ n', data)
# Print (title, data, date)
e1 = [data [0]] # one time forecast
for i in range (0, len (data)):
next = data [i] * a + e1 [i] * (1 - a)
e1.append (next)
# Print ( '/ n', e1)
e1e = [] # one time absoultion error
for i in range (0, len (data)):
e1e.append (abs (data [i] -e1 [i]))
# Print ( '/ n', e1e)
ele2 = sum (e1e)
# Print (ele2)
e2 = [data [0]] # second time forecast
for i in range (0, len (data)):
next = e1 [i] * a + e2 [i] * (1 - a)
e2.append (next)
# Print ( '/ n', e2)
e2e = [] # second time absoultion error
for i in range (0, len (data)):
e2e.append (abs (data [i] -e2 [i]))
# Print ( '/ n', e2e)
e2e2 = sum (e2e)
# Print (e2e2)
e1y = e1 [len (e1) -1] # one time forecast value
e2y = e2 [len (e2) -1] # two time forecast value
content = [[title1, 'changing coefficient a =', a]]
content.append ([title2 [0], title2 [1], 'Exponential Smoothing forecast value', 'absolute error', 'secondary exponential smoothing', 'absolute error'])
datas = [date, data, e1 [: len (e1) -1], e1e, e2 [: len (e2) -1], e2e]
datast = [[r [col] for r in datas] for col in range (len (datas [0]))]
content [len (content):] = datast
yu1 = [ '', e2y, e1y, ele2, e2y, e2e2]
yu2 = [ '', 'final prediction value', 'Exponential Smoothing forecast value', 'Exponential Smoothing absolute error accumulation', 'secondary exponential smoothing prediction value', 'Exponential Smoothing absolute error accumulation']
content.append (yu1)
content.append (yu2)
content.append ([ 'Notice: Please manually insert charts this file is calculated automatically.'])
# Print (content)
path1 = path.replace ( '. xlsx', '(the results generated) .xlsx')
writeexcel07 (path1, content, 'Make Table')
print ( "Please open the excel file directory generated (generated result)")
plt.close ( 'all')
font = FontProperties (fname = r "c: \ windows \ fonts \ simsun.ttc", size = 14)
plt.figure (figsize = (10,7))
num = range (0, len (date))
plt.plot (num, data, 'b- *', label = 'raw data')
plt.plot (num, e1 [: len (e1) -1], 'r * -', label = 'a prediction index')
plt.plot (num, e2 [: len (e2) -1], 'g * -', label = 'secondary index prediction')
bottomtitle1 = '\ n a predictive value:' + str (e1y) + "\ t and error:" + str (ele2)
bottomtitle = bottomtitle1 + '\ n secondary predictive value:' + str (e2y) + "\ t and error:" + str (e2e2)
plt.title ( 'exponential smoothing forecast chart (time series) variation coefficient a = {0: 3f}'. format (a) + bottomtitle, fontproperties = font) # simfang.ttf
# Plt.text (0, 0, bottomtitle, fontproperties = font)
plt.xlabel ( 'interval', fontproperties = font)
plt.ylabel ( 'turnover', fontproperties = font)
legend = plt.legend (loc = 'upper right', prop = font)
# Legend = plt.legend (loc = 'upper right', shadow = True, prop = font)
legend.get_frame (). set_facecolor ( 'white')
plt.grid (True)
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust (left = 0.15)
plt.show ()
savefig ( 'Fig.png')
def begin ():
sangjin = '' '
-----------------------------------------
| Welcome to predict the future value of the quadratic exponential smoothing |
| |
| Use: |
| 1. Follow the prompts |
| 2. output is forecast charts and excel treated |
-----------------------------------------
| Aoki company nickname: Sang Jin |
| Sina Weibo: a Nima |
| Micro-channel / QQ: 569929309 |
-----------------------------------------
'' '
print (sangjin)
def loop (path):
choice1 = input ( "coefficient of variation is calculated automatically select y, manually select n \ n")
if choice1 == 'y':
step = judgestep ()
p5 = calvaluetop5 (read07excel (path), step)
print ( 'total error is smallest first five')
for i in p5:
print ( 'coefficient of variation: {0: 3f} \ t predictive value: {1: 3f} \ t total error value: {2: 3f}'. format (i [0], i [2], i [4] ))
single (p5 [0] [0], path)
else:
a = judge ()
single (a, path)
def loop3 (path):
choice2 = input ( "If you want to operate other files, select y, exit options n, press any key other operating \ n")
if choice2 == 'y':
loop1 ()
elif choice2 == 'n':
print ( "Exiting the ... \ n" * 6)
print ( "Exiting the ... Thank you.")
exit (1)
else:
loop (path)
loop3 (path)
def loop1 ():
path = judgefile ()
loop (path)
loop3 (path)
begin ()
loop1 () |
|
|
|