Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/python3
- import math
- import os
- import random
- import re
- import sys
- #
- # Complete the 'predictMissingPrices' function below.
- #
- # The function is expected to return an INTEGER_ARRAY.
- # The function accepts following parameters:
- # 1. STRING startDate
- # 2. STRING endDate
- # 3. STRING_ARRAY knownTimestamps
- # 4. INTEGER_ARRAY pricesAtKnownTimeStamps
- # 5. STRING_ARRAY unknownTimestamps
- #
- # y = mx + b
- def makeLinearPrediction(value_map, i, X):
- # need two points
- X1 = None
- X2 = None
- if i == 0:
- j = i + 1
- while X1 == None or X2 == None:
- if X[j] in value_map:
- if X1 == None:
- X1 = (j, value_map[X[j]])
- else:
- X2 = (j, value_map[X[j]])
- j += 1
- elif i == len(X) - 1:
- j = i - 1
- while X1 == None or X2 == None:
- if X[j] in value_map:
- if X1 == None:
- X1 = (j, value_map[X[j]])
- else:
- X2 = (j, value_map[X[j]])
- j -= 1
- else:
- distance = 1
- while X1 == None or X2 == None:
- j = i - distance
- if 0 < j and X[j] in value_map:
- if X1 == None:
- X1 = (j, value_map[X[j]])
- else:
- X2 = (j, value_map[X[j]])
- j = i + distance
- if j < len(X) and X[j] in value_map:
- if X1 == None:
- X1 = (j, value_map[X[j]])
- else:
- X2 = (j, value_map[X[j]])
- distance += 1
- m = (X2[1]-X1[1]) / float((X2[0]-X1[0]))
- b = X1[1] - (m * X1[0])
- x = i
- return round(m * x + b)
- def timestampToFeatures(ts):
- ts_split = ts.split(' ')
- date_split = ts_split[0].split('-')
- year = int(date_split[0])
- month = int(date_split[1])
- day = int(date_split[2])
- hour = int(ts_split[1].split(':')[0])
- return (year, month, day, hour)
- def predictMissingPrices(startDate, endDate, knownTimestamps, pricesAtKnownTimeStamps, unknownTimestamps):
- value_map = {}
- X_train = [timestampToFeatures(ts) for ts in knownTimestamps]
- for i in range(len(pricesAtKnownTimeStamps)):
- value_map[X_train[i]] = pricesAtKnownTimeStamps[i]
- X_test = [timestampToFeatures(ts) for ts in unknownTimestamps]
- X = sorted(X_train + X_test)
- predictions = []
- for i in range(len(X)):
- Xi = X[i]
- if Xi not in value_map:
- predictions.append(makeLinearPrediction(value_map, i, X))
- return predictions
- """
- from sklearn.svm import SVR
- def predictMissingPrices(startDate, endDate, knownTimestamps, pricesAtKnownTimeStamps, unknownTimestamps):
- X_train = [timestampToFeatures(ts) for ts in knownTimestamps]
- y_train = pricesAtKnownTimeStamps
- X_test = [timestampToFeatures(ts) for ts in unknownTimestamps]
- model = SVR(kernel='rbf', C=10, gamma=0.1, epsilon=.1)
- model.fit(X_train, y_train)
- y_test = model.predict(X_test)
- return y_test
- """
- if __name__ == '__main__':
- # IO handling and parsing
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement