-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprices_data_international.py
183 lines (141 loc) · 6.47 KB
/
prices_data_international.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# -*- coding: utf-8 -*-
"""Simulate price trajectory for imported coal and gas, based on historical trend and correlation.
Created on Mon Jan 8 11:44:08 2018
@author: Alice Duval
Prices are in $/mt (in 2017 US dollars and metric ton) for Coal based on Australian prices and
in $/mmbtu for Gas based on Japan prices.
Data has to be choose in the beginning of this script by uncomment the right one
They are from the World Bank (WB), British Petroleum (BP) or US Energy Information Agency (EIA)
"""
import sys
import numpy as np
from scipy.stats import norm
from init import pd, START_YEAR, END_YEAR, t, MBtu, CALORIFIC_POWER
international_past_data = {}
# FROM WB
international_past_data["path_data"] = "data/Oil_Gas_prices/data_prices_international_past_WB.csv"
international_past_data["ini_year_Gas"] = 1977
international_past_data["ini_year_Coal"] = 1970
# FROM BP
#international_past_data["path_data"] = "data/Oil_Gas_prices/data_prices_international_past_BP.csv"
#international_past_data["ini_year_Gas"] = 1977
#international_past_data["ini_year_Coal"] = 1970
# FROM EIA
#international_past_data["path_data"] = "data/Oil_Gas_prices/data_\
#prices_international_past_EIA.csv"
#international_past_data["ini_year_Gas"] = 1970
#international_past_data["ini_year_Coal"] = 1960
#%%Monte Carlo characteristics : 35 forcasted prices from 2016 to 2050
for_values = END_YEAR - START_YEAR + 1
#Collect of data
import_prices_data = pd.read_csv(international_past_data["path_data"], index_col=0)
import_prices_data.columns = ["Gas", "Coal"]
x = np.array(import_prices_data.index)
y_coal = np.array(import_prices_data.Coal) / (CALORIFIC_POWER["Coal_international"] * t)
y_gas = np.array(import_prices_data.Gas) / MBtu
price_gas = pd.DataFrame({
'Price_Gas': import_prices_data['Gas']}).loc[
international_past_data["ini_year_Gas"]:2016] / (MBtu)
price_coal = pd.DataFrame({
'Price_Coal': import_prices_data['Coal']}).loc[
international_past_data["ini_year_Coal"]:2016] / (CALORIFIC_POWER["Coal_international"] * t)
coal = []
gas = []
for j in range(len(price_coal)):
coal.append(np.array(price_coal)[j][0])
for j in range(len(price_gas)):
gas.append(np.array(price_gas)[j][0])
def x_function(prices):
"""Define a sequence used in correlation factor calculation."""
x_list = []
for i, n in enumerate(prices):
if i < len(prices) - 1:
x_list.append(np.log(n / prices[i + 1]))
return x_list
def average_coeff(sequence):
"""Calculate the average of a sequence."""
return 1 / len(sequence) * np.sum(sequence)
def random():
"""Generate random number for N(0,1) distribution."""
return norm.ppf(np.random.rand(for_values, 1))
def log_returns(data):
"""Calculate the log return of a time serie."""
log_ret = np.log(1 + data.pct_change()).loc[1978:2016]
u = log_ret.mean()
var = log_ret.var()
drift = u - (0.5 * var)
stdev = log_ret.std()
return drift.values[0], stdev.values[0]
class import_prices_path():
"""A future trajectory of international oil and gas prices.
Based on historical data and a correlated geometric brownian movement model.
"""
def __init__(self, past_gas, past_coal):
self.past_gas = past_gas
self.past_coal = past_coal
self.coef_cor = self.realized_pairwise_correlation()
self.forecast_price = self.price_path()
self.import_prices = pd.DataFrame({
'Coal': self.forecast_price[1],
'Gas': self.forecast_price[0]},
index=range(START_YEAR, END_YEAR + 1))
def realized_pairwise_correlation(self):
"""Calculate the correlation factor of past data."""
c_coal = [c[0] for c in np.array(self.past_coal)[7:]]
c_gas = [g[0] for g in np.array(self.past_gas)]
x_gas = x_function(c_gas)
x_coal = x_function(c_coal)
av_gas = average_coeff(x_gas)
av_coal = average_coeff(x_coal)
coef_gas = []
coef_coal = []
for i, _ in enumerate(x_gas):
coef_gas.append(x_gas[i] - av_gas)
coef_coal.append(x_coal[i] - av_coal)
coef_cor = (sum(a * b for (a, b) in zip(coef_gas, coef_coal)) /
np.sqrt(
sum(a * b for (a, b) in zip(coef_gas, coef_gas)) *
sum(a * b for (a, b) in zip(coef_coal, coef_coal))))
return coef_cor
def price_path(self):
"""Generate two correlated prices paths."""
b = [random(), random()]
drift = [log_returns(self.past_gas)[0], log_returns(self.past_coal)[0]]
stdev = [log_returns(self.past_gas)[1], log_returns(self.past_coal)[1]]
yearly_returns = [np.exp(drift[0] + stdev[0] * b[0]),
np.exp(drift[1] + stdev[1] * (
self.coef_cor * b[0] +
np.sqrt(1 - self.coef_cor**2) * b[1]))]
price_list = [np.zeros_like(yearly_returns)[0], np.zeros_like(yearly_returns)[1]]
last_price = [self.past_gas.iloc[-1], self.past_coal.iloc[-1]]
price_list[0][0] = last_price[0][0]
price_list[1][0] = last_price[1][0]
for i in range(1, for_values):
price_list[0][i] = price_list[0][i - 1] * yearly_returns[0][i]
price_list[1][i] = price_list[1][i - 1] * yearly_returns[1][i]
for_coal = []
for_gas = []
for i in range(START_YEAR, END_YEAR + 1):
for_coal.append(price_list[1][i - START_YEAR][0])
for_gas.append(price_list[0][i - START_YEAR][0])
return for_gas, for_coal
def summary(self):
return ("Gaz prices\n" +
"Drift value : " + str(round(log_returns(self.past_gas)[0], 3)) + "\n" +
"Standard Deviation : " + str(round(log_returns(self.past_gas)[1], 2)) + "\n\n" +
"Coal prices\n" +
"Drift value : " + str(round(log_returns(self.past_coal)[0], 3)) + "\n" +
"Standard Deviation : " + str(round(log_returns(self.past_coal)[1], 2)) +
"\n\n" +
"Correlation factor between the two series: " + str(round(self.coef_cor, 2)) + "\n"
)
def summarize(self):
print(self.summary())
if __name__ == '__main__':
if (len(sys.argv) == 2) and (sys.argv[1] == "summarize"):
print("""
******************************************
*** Past data characteristics ***
******************************************
""")
import_prices_path(price_gas, price_coal).summarize()