import quandl
import math
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
import pickle
import datetime
from matplotlib import style
import matplotlib.pyplot as plot

# Config
isLoadFromLocal = True
quandl.ApiConfig.api_key = '76eCnz6z9XTH8nfLWeQU'
style.use('ggplot')


# Loading data
if isLoadFromLocal:
    df = pickle.load(open("DataFromQuandl_Stock_Chap2.pickle", "rb"))
else:
    df = quandl.get('WIKI/GOOGL')
    pickle.dump(df, open("DataFromQuandl_Stock_Chap2.pickle", "wb+"))

# Data pre-processing
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close']
df['PCT_Change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open']

df = df[['Adj. Close', 'HL_PCT', 'PCT_Change', 'Adj. Volume']]

forecastCol = 'Adj. Close'
df.fillna('-99999', inplace = True)
forecastOut = int(math.ceil(0.01*len(df)))
df['label'] = df[forecastCol].shift(-forecastOut)

# df['label'].plot()
# df[forecastCol].plot()
# plot.legend(loc = 4)
# plot.show()

x = np.array(df.drop(['label'], 1))
print(x)
x = preprocessing.scale(x)
print(x)
xLately = x[-forecastOut:]
x = x[:-forecastOut]
df.dropna(inplace = True)
y = np.array(df['label'])


# Regression
x_train, x_test, y_train, y_test = cross_validation.train_test_split(x, y, test_size=0.1)

# classifier = svm.SVR(kernel='linear') # SVM SVR

classifier = LinearRegression(n_jobs=3) # Linear Regression
classifier.fit(x_train, y_train)
accuracy = classifier.score(x_test, y_test)
forecastSet = classifier.predict(xLately)

print('Accuracy is ', accuracy, '\nForecasted values are ', forecastSet, '\nNumber of values is ', forecastOut)

df['Forecast'] = np.nan
lastDate = df.iloc[-1].name
print(lastDate)
lastTime = lastDate.timestamp()
print(lastTime)
oneDay = 24 * 60 * 60 # seconds in a day
nextTime = lastTime + oneDay

for iter in forecastSet:
    nextDate = datetime.datetime.fromtimestamp(nextTime)
    nextTime += oneDay
    df.loc[nextDate] = [np.nan for _ in range(len(df.columns) - 1)] + [iter]

df['Adj. Close'].plot()
df['Forecast'].plot()
plot.legend(loc = 4)
plot.xlabel('Date')
plot.ylabel('Price')
plot.show()
[((14, 0, 14, 19), 'matplotlib.style.use', 'style.use', ({(14, 10, 14, 18): '"""ggplot"""'}, {}), "('ggplot')", False, 'from matplotlib import style\n'), ((42, 4, 42, 26), 'sklearn.preprocessing.scale', 'preprocessing.scale', ({(42, 24, 42, 25): 'x'}, {}), '(x)', False, 'from sklearn import preprocessing, cross_validation, svm\n'), ((47, 4, 47, 25), 'numpy.array', 'np.array', ({(47, 13, 47, 24): "df['label']"}, {}), "(df['label'])", True, 'import numpy as np\n'), ((51, 35, 51, 89), 'sklearn.cross_validation.train_test_split', 'cross_validation.train_test_split', (), '', False, 'from sklearn import preprocessing, cross_validation, svm\n'), ((55, 13, 55, 39), 'sklearn.linear_model.LinearRegression', 'LinearRegression', (), '', False, 'from sklearn.linear_model import LinearRegression\n'), ((77, 0, 77, 20), 'matplotlib.pyplot.legend', 'plot.legend', (), '', True, 'import matplotlib.pyplot as plot\n'), ((78, 0, 78, 19), 'matplotlib.pyplot.xlabel', 'plot.xlabel', ({(78, 12, 78, 18): '"""Date"""'}, {}), "('Date')", True, 'import matplotlib.pyplot as plot\n'), ((79, 0, 79, 20), 'matplotlib.pyplot.ylabel', 'plot.ylabel', ({(79, 12, 79, 19): '"""Price"""'}, {}), "('Price')", True, 'import matplotlib.pyplot as plot\n'), ((80, 0, 80, 11), 'matplotlib.pyplot.show', 'plot.show', ({}, {}), '()', True, 'import matplotlib.pyplot as plot\n'), ((21, 9, 21, 33), 'quandl.get', 'quandl.get', ({(21, 20, 21, 32): '"""WIKI/GOOGL"""'}, {}), "('WIKI/GOOGL')", False, 'import quandl\n'), ((71, 15, 71, 56), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', ({(71, 47, 71, 55): 'nextTime'}, {}), '(nextTime)', False, 'import datetime\n')]