Full text
Time Series Forecasting for Local Energy Communities Master’s Thesis Sander Roos MSc Energy for Smart Cities Universitat Politècnica de Catalunya Supervisor: Andreas Sumper Barcelona, 22 September 2020
I n t r o d u c t i o n P a g e | 1-2 Abstract Electricity is not anymore, a solely centralized busines. Nowadays, customers can contribute and convert themselves to prosumers. This is encouraged by an innovative concept defined as Local Energy Community (LEC). An energy cooperative that seek for a way to organize energy enthusiasts and provide benefits for the members. The aim of the project is to find a way to assist these initiatives. A potential method is proposing an accurate forecast model. A well fitted model can be beneficial financially as well as a better usage of energy. The Seasonal Autoregressive Integrated Moving Average or SARIMA model is applied to predict the net electricity consumption of an individual household. Based upon multiple years of data, this time series forecast has been relatively successful. The drawback was that the model did not work properly for the daily measurements. On the other hand, the SARIMA model does work with weekly measurements. Considering the time constraint, further research is definitely interesting.
I n t r o d u c t i o n P a g e | 1-3 Table of Contents 1 Introduction ....................................................................................................................................... 1-5 1.1 Context ....................................................................................................................................... 1-5 1.2 Objectives of the project ............................................................................................................ 1-6 1.3 Scope of the project ................................................................................................................... 1-6 1.4 Thesis structure .......................................................................................................................... 1-7 2 Local Energy Community ................................................................................................................... 2-8 2.1 The Netherlands ......................................................................................................................... 2-8 2.1.1 Legislation .......................................................................................................................... 2-8 2.1.2 Stakeholder Analysis .......................................................................................................... 2-9 2.1.3 Relation between actors and system requirements ........................................................ 2-11 2.2 The United Kingdom ................................................................................................................ 2-13 2.2.1 Legislation ........................................................................................................................ 2-13 2.2.2 Stakeholder analysis......................................................................................................... 2-14 2.2.3 Relation between actors and system requirements ........................................................ 2-17 2.3 The United States of America .................................................................................................. 2-18 2.3.1 Legislation ........................................................................................................................ 2-18 2.3.2 Stakeholders analysis ....................................................................................................... 2-19 2.3.3 Relation between actors and system requirements ........................................................ 2-21 3 Time Series Forecasting ................................................................................................................... 3-23 3.1 Data Analytics .......................................................................................................................... 3-23 3.2 Time Series Analysis ................................................................................................................. 3-23 3.3 Time Series Forecasting ........................................................................................................... 3-24 3.4 ARIMA ...................................................................................................................................... 3-24 3.5 SARIMA .................................................................................................................................... 3-25 4 Methodology .................................................................................................................................... 4-25 4.1 Input data ................................................................................................................................. 4-25 4.2 Software ................................................................................................................................... 4-26 4.3 Time Series code ...................................................................................................................... 4-27 5 Results .............................................................................................................................................. 5-32 5.1 Liander dataset ........................................................................................................................ 5-32 5.2 Individual household dataset ................................................................................................... 5-35 2.2.1 Reduced PV dataset ......................................................................................................... 5-40
I n t r o d u c t i o n P a g e | 1-4 6 Temporary planning and cost .......................................................................................................... 6-43 7 Conclusion ........................................................................................................................................ 7-44 8 Appreciation ..................................................................................................................................... 8-45 9 Bibliography ..................................................................................................................................... 9-46 10 Annexes ...................................................................................................................................... 10-49 10.1 Annex 1: code 1 ...................................................................................................................... 10-49 10.2 Annex 2: code 2 ...................................................................................................................... 10-54
I n t r o d u c t i o n P a g e | 1-5 1 Introduction 1.1 Context Globally, the electricity industry is subjected to a fundamental transition. The old paradigm defined by an electricity production solely via large power plants situated outside city boundaries has changed and is currently still changing. Worldwide, various regions have chosen to set up competition and competitive markets for the generation of electricity. In most cases, the operation of generation and transmission is now organized and operated through market mechanisms [1]. Furthermore, the increasing proportion of renewable energies in the total annual generation and innovations in energy storage have an undeniable impact on how electricity is produced, transmitted, stored and consumed. Simultaneously, the IT- and communication revolutions facilitate the introduction of new devices and applications, empowering small-scale consumers for the first time to respond to local electricity market conditions [1]. In this new paradigm unique opportunities can be pursued with benefits for several stakeholders. In order to allow actors to present their new products, business models, proposals etc., a proper adjusted electricity market model is crucial. “The industry exists to provide a platform for the two-way trade of electricity, with all customers large and small, integrated with and responding to local market conditions “[1]. This quote exposes the existence of the prosumer. With the introduction of renewables, consumers can become relatively easy prosumers. Although, the electricity production of one prosumer has an insignificant impact on the grid, a group of prosumers could have. Organized groups of prosumers are described in various terms, and in articles the term ‘Local Energy Community’ is frequently used. According to the E-Directive, a local energy community means:’’ an association, a cooperative, a partnership, a non-profit organization or other legal entity which is effectively controlled by local shareholders or members, generally value rather than profit-driven, involved in distributed generation and performing activities of a distribution system operator, supplier or aggregator at local level, including across borders [2] .’’ It’s widely acknowledged that Renewable Energy Sources (RES) and Distributed Energy Resources (DERs) affect power distribution networks and are expected to increase in the following years [3]. On one hand, this growth could assure the world of reduced environmental concerns caused by energy production. On the other hand, both RES and DERs cause various challenges of technological, social and policy related nature [3]. Hence, the importance of implementing solutions that can manage this growth in an efficient manner. The role of local communities and cities shouldn’t be overlooked [4]. To meet the needs of local communities, an energy system, that performs well in terms of techno-economics, as well as social and environmental, is necessary. For this reason, the willingness of citizens to participate should be utilized. Already mentioned in 2006, household level energy production, storage and energy management systems were expected to have considerable relevance in integrated energy systems [5]. In hindsight, this statement can be underlined or even validated.
I n t r o d u c t i o n P a g e | 1-6 The grid turns into a so-called smart grid, where every customer has a smart meter that stores and sends data, meaning the actual electricity consumption [6]. Data analytics play a key role in analyzing the whole smart grid. This is of significant importance for a variety of reasons. For example, sustainable environmental usage of energy [6]. Or additionally, economic factors such as an indicator of how much electricity can be sold or the opposite bought. This thesis is focusing on the prediction of household electricity consumption. The statistical model Seasonal Autoregressive Integrated Moving Average (SARIMA) is used to forecast the future consumption of an individual household who also installed solar panels, and therefore can be considered as a prosumer. 1.2 Objectives of the project The aim of this work is to use a machine learning technique to predict the net electricity consumption. The increasing presence of energy communities in the world, but specifically in Europe, is seen as an important development and motivation for this thesis. The specific objectives are: • Better understanding of local energy communities • Forecast of electricity consumption 1.3 Scope of the project This thesis is a first approach to apply a statistical model to the energy profile of an individual household. The time series forecast of an entire energy community would be a logical next step. The present work only proposes the SARIMA model. Future research would definitely be interesting when other models are compared to these results.
I n t r o d u c t i o n P a g e | 1-7 1.4 Thesis structure This thesis is presented in the following structure. Chapter 1 gives context to the project as well as the objectives, scope and thesis structure. Chapter 2 details the concept of a local energy community, as well as a conducted analysis of various countries. Chapter 3 describes time series forecasting and adds theoretical background. Chapter 4 represents the methodology, where also an overview of the code is added for reproduction. Chapter 5 shows the results of this project. Chapter 6 elaborates on the temporary planning and costs. Ultimately, the thesis is concluded in Chapter 7.
L o c a l E n e r g y C o m m u n i t y P a g e | 2-8 2 Local Energy Community This section elaborates on the concept Local Energy Community (LEC) via an analysis of energy cooperatives in three distinct countries. For every country there is a brief description of the legislation, stakeholder analysis, and a discussion of the relation between actors and system requirements. Considering that an energy community is quite a recent development, though gaining popularity, comparing different setups can be beneficial. The idea is to acquire a deeper understanding of energy communities by looking at those different structures. With no suggestion of importance in order, the Netherlands, the United Kingdom and the United States of America. 2.1 The Netherlands 2.1.1 Legislation The European Union regularly meet to discuss views on climate change policy [7]. As a result, certain climate packages are constructed and published. Within those packages’ government leaders have committed themselves to clear goals. In the following, three important Dutch goals within the EU are listed [7]. • The Netherlands aims to raise the EU ambition for 2030 from 40% to 55% emission reduction compared to 1990 and to translate this to a robust and effective legislative framework • The Dutch government considers that it is essential to fully integrate a growing supply of renewable energy into the EU energy system • The Dutch government advocates the development of an internal EU energy market Partial stimulated by these goals, Dutch law allows a household to have an agreement with the energy retailer to pay only the net balance [8]. However, a distinction should be made between production “behind” and “outside” the door. “Behind” represents solely one house that produces and consumes its own electricity. The surplus is injected into the grid. On the other hand, there is also “outside” the door. When a group of households owns for example a wind mill, a special regulation called “PostCodeRoos regeling” is applicable. This regulation allows collective investment in wind- or sun production. Hence, it isn’t a necessity to have solar panels on your own roof, instead you can invest in an area close to your residence. Members receive discount on their energy tax for the production of local and sustainable electricity. In specific, the PostCodeRoos offers 15 years of yearly tax returns on the production per kWh. Anno 2017, the tax per kWh was €0,1013 BTW excluded. Besides the tax returns, it is allowed to sell the electricity to an energy company. The collective or cooperative must have a contract with the energy company wherein an agreement regarding the price is established. With this revenue stream the cooperative can cover the costs, such as maintenance, administration and insurance [9].
L o c a l E n e r g y C o m m u n i t y P a g e | 2-9 2.1.2 Stakeholder Analysis Table 1, mainly based upon the article “Local Alternative for Energy Supply: Performance Assessment of Integrated Community Energy Systems” [10]. TABLE 1 Main task Main goal Business model Energy cooperatives Organize local production of sustainable energy Stimulate the local production of energy and form a community Non-profit, subscription of members, payment by energy supplier (per customer), subsidies and donations Community Other tasks than energy related Reliable and sustainable energy source No business model Renewable Energy Technology producers Produce (and maintain) Renewable energy technology Sell as much as possible Produce and sell product Dutch government Creating and enforcing laws “Working” on energy that is sustainable, reliable, available and affordable for all (2050 milestone) Individual income taxes, corporate income taxes and payroll taxes TSO (TenneT) Controlling and operating the transmission power grid and electricity market Maximize welfare/efficient use of resources Billing ancillary services via grid usage fees DSO (Rendo/Liander etc.) Operates the grid Ensure that electricity is delivered in a secure, reliable and efficient way Manages energy use, load balancing and demand responses at negotiated rates Energy retailer (Powerpeers, om|energie) Facilitate energy for final customers Maximize profit Difference between buy and sell, acquiring large customer base ACM (authority who monitors energy market) Enforcing the rules for free and regulated markets. In addition, they give advice to the Dutch legislature. Task for energy cooperatives: give permission for dispensation (Electricity Law) Ensures fair competition between businesses, and protects consumer interests Government institution
L o c a l E n e r g y C o m m u n i t y P a g e | 2-16 Visualized in figure 3, distinction between profit- and non-profit driven. Profit driven Non-profit driven FIGURE 3
L o c a l E n e r g y C o m m u n i t y P a g e | 2-17 2.2.3 Relation between actors and system requirements When figure 3 is compared to figure 1, the important conclusion is that the UK structure is almost similar to the Dutch example explained in the 2.1.3. Differences are found between the names of the institutions. That’s why in the following chapter the same explanation is shown. To describe the structure of the energy cooperative, a use case style diagram is constructed. This methodology is chosen to specifically clarify the relations between actors and system requirements. Arranged in figure 4, the set of possible steps from a global perspective. FIGURE 4
L o c a l E n e r g y C o m m u n i t y P a g e | 2-18 2.3 The United States of America 2.3.1 Legislation The fifty states in America are adding value to the complexity (different laws). There are over 900 electric cooperatives in 47 states that provide electric service to 56% of nations landmass. These electric cooperatives are all characterized as private, independent, non-profit electric utility businesses. In addition: - they are owned by the customers they serve - incorporated under the laws of the states in which they operate - established to provide at-cost electric service, - governed by a board of directors elected from the membership which sets policies and procedures that are implemented by the cooperatives’ management. [15] The cooperatives can be divided into two groups; the distribution cooperatives and the Generation & Transmission cooperatives (G&Ts). The National Rural Electric Cooperative Association (NRECA) represents the national interests of cooperative electric utilities. NRECA provides among other things legislative, legal and regulatory representation. Besides these electric cooperatives, there is also the Brooklyn Microgrid (BMG). The BMG is not considered as an energy utility or energy retailer. The utility regulations in New York state that “only utilities and retail service providers are allowed to buy and sell energy”. In October 2019, the BMG launched a campaign to allow the BMG operate as a commercial entity. They were asking for a so-called regulatory sandbox, which approves experimenting and learning before adopting a technology or system. In December 2019, the BMG has been approved to conduct a 12-month pilot program for energy trading on its platform. The pilot will begin in the early part of 2020, with forty prosumers and 200 consumers participating [16].
L o c a l E n e r g y C o m m u n i t y P a g e | 2-19 2.3.2 Stakeholders analysis Table 3, mainly based upon the article “Designing microgrid energy markets, a case study: The Brooklyn Microgrid” [17]. TABLE 3 Main task Main goal Business model Benefit corporation (BMG) Connect the Brooklyn community Creating selfsustaining microgrids Show regulators that the technology works LO3 Energy Run the BMG project Developing blockchain based innovations Show regulators that the technology works Brooklyn community/residents Prosumers generating energy and trade in their local marketplace Earn value on excess energy and care about community’s energy future Buy solar panels and sell excess energy via platform Renewable Energy Technology producers Produce (and maintain) Renewable energy technology Sell as much as possible Produce and sell product Local authorities Work with local people and partners to agree and deliver on local priorities Delivering public services to the local community Receive governments grants, council tax and business rates U.S. federal government Creating and enforcing laws Maximum sustainable employment, stable prices and moderate long-term interest rates Individual income taxes, corporate income taxes and payroll taxes TSO (NYISO) Controlling and operating the transmission power grid and electricity market Maximize welfare/efficient use of resources Billing ancillary services via grid usage fees DSO (Con Ed.) Operates the grid Ensure that electricity is delivered in a secure, reliable and efficient way Manages energy use, load balancing and demand responses at negotiated rates Energy retailer (Direct Energy) Facilitate energy for final customers Maximize profit Difference between buy and sell, acquiring large customer base Venture fund (Centrica Innovations) Invests in new technology and ideas Generate value by investing in startups Revenue stream after acquiring share in startups.
L o c a l E n e r g y C o m m u n i t y P a g e | 2-20 FERC Enforcing the rules for free and regulated markets. Ensures fair competition between businesses, and protects consumer interests Independent regulatory agency within US Department of Energy Visualized in figure 5, distinction between profit- and non-profit driven. FIGURE 5 Profit driven Non-profit driven
Loca l E n e r g y C o m m u n i t y P a g e | 2-21 2.3.3 Relation between actors and system requirements To describe the structure of the energy cooperative, a use case style diagram is constructed. This methodology is chosen to specifically clarify the relations between actors and system requirements. Arranged in figure 6, the set of possible steps from a global perspective. The use diagram is partially similar to the Dutch- and UK structure. Therefore, only the actions that endure change are elaborated in the following chapter. Installation The BMG is a network that connects, besides the producers, also the consumers. Different from the European case, the installation must be done in coordination with a third party, that controls the marketplace. To join the BMG, one must access a data platform that creates localized energy marketplace. This platform is maintained by the referred third party, in this case LO3 Energy. Sign contract Notwithstanding the fact that there are still regulation hurdles to overcome and this is not yet practically possible. The assumption is made that this will be the case in the near future. This can only be done by a collaboration between the prosumer, LO3 Energy, energy retailer and local authority/federal government. If a prosumer signs a contract with BMG, he gives his neighbors the opportunity to bid on his solar energy. Additionally, he allows LO3 Energy access to his energy data, such as building management systems. Already mentioned in the introduction, LO3 Energy is not an energy retailer and can only signs this contract if permitted by the local authority and according to the laws of federal government. This entire transaction must be coordinated with the energy retailer or energy utility. Buy & sell energy The most important difference between the European model can be found in this step. Members of the BMG are able to buy and sell local produced energy in a P2P trading system. The traditional electricity retail model is replaced by a blockchain software platform and configurable auction algorithm made by LO3 Energy. Can’t be possible without DSO. The DSO is granted access to consumer data like building management systems. Using price as a proxy, the DSO manages energy use, load balancing, and demand response at negotiated rates (BMG).
L o c a l E n e r g y C o m m u n i t y P a g e | 2-22 FIGURE 6
T i m e S e r i e s F o r e c a s t i n g P a g e | 3-23 3 Time Series Forecasting Forecasting refers to “the job or activity of judging what is likely to happen in the future, based on the information you have now” [18]. Loads are constantly changing, amplified by the addition of local energy generation. The power system should handle these variations taken into account the rule demand equals supply. In Chapter 2, the opportunities of organizing multiple households as energy communities are discussed and analyzed. The growing trend of energy communities in Europe is also bringing more and more complexity to the grid. A cost-effective method to predict the load behavior of these households could add value to these communities and the concept or innovation itself. The higher the precision of forecast the smaller the necessary adjustment for the power system. 3.1 Data Analytics The rapid transformation of the electricity sector, with continuously digitalization, decarbonization and decentralization, stimulates research and implementation of Artificial Intelligence models [19]. In the article of Frederik vom Scheidt et al., so-called push factors and pull factors are discussed. Push factors such as the growing trend of computer power and declining expenses of information technology. Additionally, pull factors, such as increasing volatility of electricity generation, which is emphasized multiple times in this thesis. They argue that both the push factors as well as the pull factors are drivers for the importance and need for Data Analytics. If someone analyzes all datasets available, obviously time doesn’t always play a role in datasets. However, time is considered as a major component in energy related datasets [20]. 3.2 Time Series Analysis A time series is a sequence of data points ordered in time. Before a prediction can be made, it’s widely acknowledged that initially an analysis should be conducted. Time series analysis are performed in order to understand the reasons why certain characteristics or events occur during time periods [21]. It involves developing models that can show the nature of the data. The main goal is to precisely collect and study the past observations of the dataset [22]. A model should be developed that is capable of describing the structure of the time series.
T i m e S e r i e s F o r e c a s t i n g P a g e | 3-24 3.3 Time Series Forecasting Quantitative forecasting methods can be used if there is relevant numerical data available. Evidently, there is a wide range of quantitative methods, and some are developed for specific cases. All those methods have their own design variables, costs and characteristics. In the next section, the ARIMA and SARIMA model are highlighted. Due to time limitation, there are no other models investigated. 3.4 ARIMA An autoregressive integrated moving average (ARIMA) is a statistical model and popular in time series forecasting. Time series do not always have a fixed average and a constant standard deviation. Multiple time series models are developed that are able to forecast, despite the more complex patterns [23]. If the time series is non-stationary and has no seasonality, ARIMA could result in a potentially acceptable prediction. ARIMA consists out of three components, which are all specified in the model as a parameter. • AR; autoregressive component • I; integrated component • MA; moving average component Instead of predicting the time series itself, ARIMA predicts the differences of the time series between one timestamp and the previous timestamp or timestamps. The most important step is the determination of the order of differencing necessary to convert the time series from non-stationary to stationary. The basic notation for ARIMA is (p,d,q), where p, d and q represent non-integer values. The primary parameter p indicates the number of lag observations. The second parameter d stands for the degree of differencing. Lastly, q determines the order of moving average [24]. Below the general forecasting equation. 𝑧𝑡= φ1𝑧𝑡−1+.. . φ𝑝𝑧𝑝−1 + 𝜃1𝜀𝑡−1+. . . +𝜃𝑞𝜀𝑞−1 + 𝜀𝑡 (1) , where 𝑧𝑡 is forecasted value, φ is the auto regressive coefficient, 𝜃 the moving average coefficient and 𝜀 the error. A basic ARIMA model is (1,1,1) and is defined as: 𝑧𝑡= φ1𝑧𝑡−1 + 𝜃1𝜀𝑡−1 + 𝜀𝑡 (2) , where 𝑧𝑡 is predicted difference, φ1 is the auto regressive coefficient, 𝜃1 moving average coefficient and 𝜀𝑡 error. It depends on the data which ARIMA notation is optimal. When working with Python all possibilities can be investigated and the most favorable solution chosen.
Methodology Page | 4-25 3.5 SARIMA A seasonal autoregressive integrated moving average (SARIMA) is the same as an ARIMA model, but with the addition of a seasonal component. When data show regular patterns that repeat over a year, seasonality should be considered. If not, the regression model is negatively affected. In equation 3, the SARIMA model is shown. Similar to ARIMA, but with the control for seasonality by including it as a feature. 𝑆𝐴𝑅𝐼𝑀𝐴(𝑝, 𝑑, 𝑞)(𝑃, 𝐷, 𝑄, 𝑠) (3) , where P, D and Q are parameters at the seasonal level, and s is the number of time steps in each season. 4 Methodology For this thesis, the quantitative forecasting model was created based on a machine learning technique. The theoretical part is all documented on the official website of statsmodels [25]. Statsmodels is a Python module that provides classes and functions for various statistical models, such as time series forecasting. All the data was collected on the internet and are considered open datasets. The data files are saved using Microsoft Office Excel, but not modified. That part was done in Jupyter Notebook, an application that allows the editor to create Python scripts. As a first step, the data was cleaned and prepared for the model. Everything was done using the programming language Python, and additionally various existing libraries. For example, Pandas, Numpy and Matplotlib. While Pandas and Numpy were essential for the structure of the data, Matplotlib was crucial for the graphs and data visualization. To create the model, the Statsmodels library was used to decompose and make the final prediction. A further step with the forecast was taken with the visualization using the Matplotlib library again. 4.1 Input data As stated before, the technical part of this thesis was tested on two different datasets. This section details the origin and differences between both. • “Zonnedael”, Liander open dataset • Individual household Liander is a Dutch network operator and made the data publicly available to stimulate innovation. The Liander dataset is published on August 25th, 2014. This dataset is based upon the smart meters of approximately 80 households. All the addresses are located in the Netherlands, around the city of Zutphen. The smart meters are measuring the electricity consumption per 15 minutes and the units of are Wh. The measurements are collected for one year, starting from 1-1-2013 until 31-12-2013.
R e s u l t s P a g e | 5-32 5 Results 5.1 Liander dataset The first data analysis was done strictly for the Liander dataset. This work was conducted during the first months of the thesis. Data exploration, data cleaning and visualization were among the tasks. After those tasks, the hypothesis was formed that a time series forecast could be applied to this dataset. One of the drivers of that hypothesis; availability of plentiful numerical data. During the process, the conclusion was made to step aside from this hypothesis. The dataset was not considered to be working with the statistical model. In the next section 5.2, this decision has been justified. Nonetheless, for completeness, some results are shown. These figures show the energy profile of the members of the energy community and gave insights about the patterns. In figure 16 and 17, the results from a week in the winter are detailed. The red line presents the accumulated electricity consumption, the blue line the surplus of electricity generation coming from the solar panels. The dataset contained only the net electricity consumption. Therefore, it is impossible to know the exact amount of solar energy produced. On the left side, the base scenario is based upon the real values of the energy community. Only 10 household had access to solar panels, which clarifies the significant difference. On the right side, by modelling extra households with access to solar panels are added. This extra profile is an average profile over those 10-existing household. Not surprisingly, it is possible to have extra production without using the power system. In theory, the total sum of renewable energy could be used within the community. This conclusion can not be made in the summer. Shown in figure 18 and 19, after adding 10 prosumers there is already a surplus of generated energy during the day. This can be explained by the climate conditions. During the summer, the weather is simply more favorable.
R e s u l t s P a g e | 5-33 FIGURE 16
Res u l t s P a g e | 5-34 FIGURE 17 FIGURE 18
R e s u l t s P a g e | 5-35 FIGURE 19 5.2 Individual household dataset In this section the results from the time series forecasting are provided. The dataset is published on the website Kaggle and last updated December 2019. It’s an open dataset and details the daily electricity usage. Besides, this individual household installed photovoltaic modules on the roof that have a total power of 5 kWp. To justify why this dataset is preferred above the data from Liander three arguments are listed. • Amount of years • Amount of measurements • Computer power Theoretically, you should be able to make predictions using data of twelve months. However, data of longer periods often provide a more complete representation and therefore ensures a more accurate forecast. Specially in this case because the hypothesis is that seasonality plays a dominant role.
R e s u l t s P a g e | 5-36 Secondly, the rate of measurement is every 15 minutes in the Liander dataset. On the contrary, the daily electricity usage. The higher the numbers of measurements per day the greater the issue with noise. If the series is seen as too long, the machine learning estimation is affected by the noise. Thirdly, the availability of computer power. The calculation of the time series of the entire energy community would be too long. This is the case for the Liander dataset. For this reason, the data from one individual household is chosen. Overall, the utilization of time series forecasting results in a promising outcome. FIGURE 20: ELECTRICITY CONSUMPTION PER DAY As shown in figure 20, the net electricity consumption is essentially the same for all years. On the x-axis, the time period which consists out of collected data from October 2011 until November 2019. The y-axis represents the total electricity in kilowatts for every day. Also mentioned above, one measurement per day. Firstly, there is a significant difference noticeable between summer and winter months. Naturally, the energy profile has higher peaks in the winter mainly due to the usage of heating. In addition to the consumption, the generation of electricity from the solar panels is higher in summer months. The data displays negative output especially during the summer. Those negative values represent an injection to the grid due to the surplus of energy.
R e s u l t s P a g e | 5-37 In figure 21, the input is decomposed into three distinct components, respectively trend, seasonality and noise. The trend is relatively well readable and understandable. What was already concluded from figure 20 but emphasized by this graph, the model should make a distinction between the seasons. For the seasonal graph it was expected to see an average of data points for each month. From this result no conclusion can be made. In the second part of this section it is further investigated. The residual is the remainder component. It is interesting to see that the noise component is clear in comparison with the seasonal component. FIGURE 21 After decomposing, the Seasonal Autoregressive Integrated Moving Average (SARIMA) model is applied. The SARIMA model is chosen primarily due to the expected importance of a seasonal component. There are four seasonal elements that must be configured: • P: Seasonal autoregressive order • D: Seasonal difference order • Q: Seasonal moving average order • s: The number of time steps for a single seasonal period
R e s u l t s P a g e | 5-38 After fitting the model, the Akaike information criterion (AIC) of 18341 was the lowest solution. This value will be used, since the lowest AIC is considered the optimal solution. Additionally, the optimal seasonal components are P=1, D=1, Q=1 and m= 12. In figure 22, the diagnostics are visualizing important information. In the right bottom, the Auto Correlation ACF Plot or correlogram. The summary of correlation at different time periods shows relatively small correlation coefficients. Also, no consistent upward or downward pattern is visible. The data is likely without any significant autocorrelation. The histogram as well as the scatterplot show a normal distribution. The Q-Q plot is forming a line that is approximately straight. The histogram has the typical bell-shaped and is symmetric about the mean. Normality is assumed. FIGURE 22
R e s u l t s P a g e | 5-39 In figure 23, the forecast of our model is tested and compared with the observations. The first day of January 2019 is chosen as the starting date of the prediction. This is only because it is more convenient to just compare a small part of the period. The orange line represents the forecast, and the blue line the true values. The forecast fits well with the true values. The model is capable of following the trend and is therefore promising. FIGURE 23 In order to analyze the estimation, the mean squared error (MSE) and the root mean squared error (RMSE) are also added. These are both a measure of accuracy. MSE 47.12 RMSE 6.86 Nevertheless, when the forecast for roughly two years is performed, only a straight line is seen in figure 24. This result didn’t change while modifying the time period of the forecast. The hypothesis is that with some trial and error a forecast should be possible. Though, mainly because of time boundaries, it is decided that a potential cause could be the amount of data. FIGURE 24
R e s u l t s P a g e | 5-40 2.2.1 Reduced PV dataset In this section, a second time series forecasting is presented, directly related to the outcome of the first. After questioning the negative impact of the amount of data, a decision has been taken to train and test the model using less data. In this example, the data is modified and decreased to a time period from October 2016 until October 2019. For clearness both modifications are listed below. • Weekly data • Smaller time frame First, the daily measurements are converted into weekly measurements. For this example, the preference is rationalized by the density of figure 21. The hypothesis is that one of the reasons for the straight line could be the great number of measurements per year. The weekly net total electricity profile is determined by the summation of seven days. Secondly, the data is filtered into a smaller time frame to be able to do the calculating significantly faster. Finding the optimal AIC is a time- and computer power consuming task. Briefly, the fit of the model has a better result for the alternative of less data. Visualized in figure 25, a different result is shown after decomposition. The seasonal element is not anymore unreadable. The seasonal component is continuously throughout the years. Also, the residual component differs. The density is adjusted and single errors are noticeable. That being said, the error is well spread around zero. FIGURE 25
R e s u l t s P a g e | 5-41 Equal to Chapter 5.2.1, the diagnostics are visualizing important information. In the top corner, the standardized residual shares the same characteristics, besides obliviously less years. The histogram and scatterplot indicate normality once more. In the bottom corner, the correlogram shows no significant upward or downward trend. FIGURE 26 Figure 27, the forecast of our model is tested and compared with the observations. The first day of January 2019 is chosen as the starting date of the prediction. This is only because it is more convenient to just compare a small part of the period. The orange line represents the forecast, and the blue line the true values. The forecast fits well with the true values. FIGURE 27
B i b l i o g r a p h y P a g e | 9-48 [27] NumPy. (2020). NumPy. Retrieved from https://numpy.org/ [28] Matplotlib. (2020). Retrieved from https://matplotlib.org/ [29] Ironhack. (2020). Retrieved from https://www.ironhack.com/en
A n n e x e s P a g e | 10-49 10 Annexes 10.1 Annex 1: code 1 1. #!/usr/bin/env python 2. # coding: utf-8 3. 4. # In[6]: 5. 6. 7. import warnings 8. import itertools 9. import numpy as np 10. import matplotlib.pyplot as plt 11. warnings.filterwarnings("ignore") 12. plt.style.use('fivethirtyeight') 13. import pandas as pd 14. import statsmodels.api as sm 15. import matplotlib 16. matplotlib.rcParams['axes.labelsize'] = 14 17. matplotlib.rcParams['xtick.labelsize'] = 12 18. matplotlib.rcParams['ytick.labelsize'] = 12 19. matplotlib.rcParams['text.color'] = 'G' 20. 21. 22. # In[10]: 23. 24. 25. df =pd.read_csv("Raw data/Original datasets/PV_individual.csv") 26. df.rename(columns={'Unnamed: 0':'date'},inplace=True) 27. 28. 29. # In[11]: 30. 31. 32. df.date = pd.to_datetime(df.date) 33. df.set_index('date', inplace=True) 34. 35. 36. # In[12]: 37. 38. 39. df.head(2) 40. 41.
A n n e x e s P a g e | 10-50 42. # In[154]: 43. 44. 45. df['Elec_kW'].plot(figsize=(19,12)) 46. plt.xlabel("Time") 47. plt.ylabel("Electricity (kW)") 48. plt.show() 49. 50. 51. # In[17]: 52. 53. 54. # I dropped other two columns 55. df 56. 57. 58. # In[18]: 59. 60. 61. from pylab import rcParams 62. rcParams['figure.figsize'] = 18, 8 63. decomposition = sm.tsa.seasonal_decompose(df, model='additive') 64. fig = decomposition.plot() 65. plt.show() 66. 67. 68. # In[19]: 69. 70. 71. p = d = q = range(0, 2) 72. pdq = list(itertools.product(p, d, q)) 73. seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))] 74. print('Examples of parameter for SARIMA...') 75. print('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[1])) 76. print('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[2])) 77. print('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[3])) 78. print('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[4])) 79. 80. 81. # In[22]: 82. 83. 84. for param in pdq: 85. for param_seasonal in seasonal_pdq: 86. try: 87. mod = sm.tsa.statespace.SARIMAX(df,order=param,seasonal_order=param_sea sonal,enforce_stationarity=False,enforce_invertibility=False) 88. results = mod.fit()
A n n e x e s P a g e | 10-51 89. print('ARIMA{}x{}12 - AIC:{}'.format(param,param_seasonal,results.aic)) 90. except: 91. continue 92. 93. 94. # In[ ]: 95. 96. 97. # ARIMA(1, 1, 1)x(1, 1, 1, 12)12 - AIC:18341.658999442654 Lowest!! 98. 99. 100. # In[24]: 101. 102. 103. mod = sm.tsa.statespace.SARIMAX(df, 104. order=(0, 0, 1), 105. seasonal_order=(1, 1, 1, 12), 106. enforce_stationarity=False, 107. enforce_invertibility=False) 108. 109. # fit model and save in results 110. results = mod.fit() 111. print(results.summary().tables[1]) 112. 113. 114. # In[25]: 115. 116. 117. # After fit 118. results.plot_diagnostics(figsize=(18, 8)) 119. plt.show() 120. 121. 122. # In[160]: 123. 124. 125. pred = results.get_prediction(start=pd.to_datetime('2019- 01-01'), dynamic=False) 126. pred_ci = pred.conf_int() 127. ax = df.plot(label='observed') 128. pred.predicted_mean.plot(ax=ax, label='One-step ahead Forecast', alpha=.7, figsize=(40, 8)) 129. ax.fill_between(pred_ci.index, 130. pred_ci.iloc[:, 0], 131. pred_ci.iloc[:, 1], color='k', alpha=.2) 132. ax.set_xlabel('Date') 133. ax.set_ylabel('Electricity')
A n n e x e s P a g e | 10-52 134. plt.legend() 135. plt.show() 136. 137. 138. # In[156]: 139. 140. 141. u = pd.DataFrame({'Elec_kW':[1,2,3,4,5]}) 142. 143. 144. # In[157]: 145. 146. 147. 148. # x= pd.DataFrame(df['2019-07-01':]['Elec_kW']) 149. # print(x) 150. 151. df_forecasted = pd.DataFrame(df_forecasted, index=df_truth.index,columns=['Elec_kW'] ) 152. df_forecasted 153. 154. 155. # In[158]: 156. 157. 158. df_forecasted 159. #df_truth 160. 161. 162. # In[159]: 163. 164. 165. #df_forecasted = pred.predicted_mean 166. 167. df_truth = df['2019-07-01':] 168. mse = ((df_forecasted - df_truth) ** 2).mean() 169. print('The Mean Squared Error is {}'.format(round(mse, 2))) 170. print('The Root Mean Squared Error is {}'.format(round(np.sqrt(mse), 2))) 171. 172. 173. # In[167]: 174. 175. 176. # Forecast for the next 12 months?? 30 days times 12 177. 178. pred_uc = results.get_forecast(steps=730) 179. pred_ci = pred_uc.conf_int() 180. 181. ax = df.plot(label='observed', figsize=(40, 4)) 182. pred_uc.predicted_mean.plot(ax=ax, label='Forecast')
A n n e x e s P a g e | 10-53 183. 184. ax.fill_between(pred_ci.index, 185. pred_ci.iloc[:, 0], 186. pred_ci.iloc[:, 1], color='k', alpha=.25) 187. 188. ax.set_xlabel('Date') 189. ax.set_ylabel('Sales') 190. plt.legend() 191. plt.show() 192. 193. 194. # In[147]: 195. 196. 197. df_forecasted = pred.predicted_mean 198. df_forecasted.head(12) 199. 200. 201. # In[148]: 202. 203. 204. df_truth.head(12) 205. 206. 207. # In[149]: 208. 209. 210. # Boundaries for the forecasting 211. pred_ci.head(24) 212. 213. 214. # In[150]: 215. 216. 217. forecast = pred_uc.predicted_mean 218. forecast.head(30) 219.
A n n e x e s P a g e | 10-54 10.2 Annex 2: code 2 1. #!/usr/bin/env python 2. # coding: utf-8 3. 4. # In[99]: 5. 6. 7. import warnings 8. import itertools 9. import numpy as np 10. import matplotlib.pyplot as plt 11. warnings.filterwarnings("ignore") 12. plt.style.use('fivethirtyeight') 13. import pandas as pd 14. import statsmodels.api as sm 15. import matplotlib 16. matplotlib.rcParams['axes.labelsize'] = 14 17. matplotlib.rcParams['xtick.labelsize'] = 12 18. matplotlib.rcParams['ytick.labelsize'] = 12 19. matplotlib.rcParams['text.color'] = 'G' 20. 21. 22. # In[100]: 23. 24. 25. df =pd.read_csv("/Users/Desktop/sander/New_approach/PV_individual.cs v") 26. df.rename(columns={'Unnamed: 0':'date'},inplace=True) 27. 28. 29. # In[101]: 30. 31. 32. df.date = pd.to_datetime(df.date) 33. df.set_index('date', inplace=True) 34. 35. 36. # In[102]: 37. 38.
A n n e x e s P a g e | 10-55 39. df.head(2) 40. 41. 42. # In[103]: 43. 44. 45. # im resetting date as column 46. df.reset_index(level=0, inplace=True) 47. 48. 49. # In[104]: 50. 51. 52. df.columns 53. 54. 55. # In[105]: 56. 57. 58. df["Day_of_Week"] = df['date'].dt.weekday 59. 60. 61. # In[106]: 62. 63. 64. # Let´s now find out the date of each commencing week 65. from datetime import datetime, timedelta 66. 67. 68. # In[107]: 69. 70. 71. df["First_day_of_the_week"] = df.apply(lambda x: x['date'] - timedelta(days=x['Day_of_Week']), axis=1) 72. 73. 74. # In[108]: 75. 76. 77. df.head() 78. 79. 80. # In[109]: 81. 82. 83. # Let's first aggregate the dataset with start date and count 84. df_by_week=df.groupby(['First_day_of_the_week']).sum()
A n n e x e s P a g e | 10-56 85. 86. 87. # In[110]: 88. 89. 90. # let´s drop the other columns which are not relevant 91. df_by_week = df.drop(['cum_power','Gas_mxm','Day_of_Week','date'],axis =1) 92. 93. 94. # In[111]: 95. 96. 97. df_by_week 98. 99. 100. # In[112]: 101. 102. 103. # lets set the weekly date as index 104. 105. df_by_week['First_day_of_the_week'] = pd.to_datetime(df_by_week['First_day_of_the_week']) 106. df.info() 107. 108. 109. # In[113]: 110. 111. 112. df_by_week.set_index('First_day_of_the_week', inplace=True) 113. df_by_week.info() 114. 115. 116. # In[114]: 117. 118. 119. df_by_week.head() 120. 121. 122. # In[115]: 123. 124. 125. df_by_week.tail(10) 126. 127. 128. # In[116]: 129.
A n n e x e s P a g e | 10-57 130. 131. # Let´s plot the Electricity Consumption by week 132. df_by_week.plot(figsize=(19,12)) 133. plt.xlabel("Week/C") 134. plt.ylabel("Electricity (kW)") 135. plt.show() 136. 137. 138. # ### Let´s try the SARIMA predictive model approach 139. 140. # In[117]: 141. 142. 143. # Let's import all relevant libraries 144. 145. import warnings 146. import itertools 147. import numpy as np 148. import matplotlib.pyplot as plt 149. warnings.filterwarnings("ignore") 150. plt.style.use('fivethirtyeight') 151. import pandas as pd 152. import statsmodels.api as sm 153. import matplotlib 154. matplotlib.rcParams['axes.labelsize'] = 14 155. matplotlib.rcParams['xtick.labelsize'] = 12 156. matplotlib.rcParams['ytick.labelsize'] = 12 157. matplotlib.rcParams['text.color'] = 'G' 158. 159. 160. # In[118]: 161. 162. 163. df_by_week.plot(figsize=(19,4)) 164. plt.show() 165. 166. 167. # In[119]: 168. 169. 170. # I will make the dataset shorter as this is too much data to process 171. start_date = '2016-10-31' 172. end_date = '2019-10-28' 173. 174. 175. # In[120]: