示例#1
0
def stockValueInFuture():
    print(
        "enter the code for the company you want to check the predictions of:")
    companyCode = input()
    print("Enter the No. of Days you want to predict the stocks for:")
    n = int(input())
    st = Stocker(companyCode)
    st.create_prophet_model(n)
 def listenToClient(client):
     data = bytearray()
     while True:
         datachunk = client.recv(BUFFER)
         if not datachunk:
             break
         data += datachunk
     client.close()
     data = data.decode().strip('\n').replace(" ", "").split(",")
     requestID = data[0]
     request_symbol = data[1]
     days_into_future = data[2]
     s3_client = boto3.client('s3')
     obj = s3_client.get_object(
         Bucket='elasticbeanstalk-us-west-1-643247086707',
         Key=request_symbol + '.csv')
     payload = str(obj['Body'].read()).replace(r'\n', '\n')
     with open(request_symbol + ".csv", 'w') as f:
         f.write(payload)
     stock = Stocker(request_symbol, 'CSV', '')
     predicted_price = stock.create_prophet_model(
         days=int(days_into_future),
         resample=False,
         symbol=request_symbol,
         requestID=requestID)
     graph = open(request_symbol + "_" + requestID + ".png", "rb").read()
     os.remove(request_symbol + '.csv')
     r.set(request_symbol + "_" + requestID, graph)
     os.remove(request_symbol + "_" + requestID + ".png")
     r.set(request_symbol + "_price_" + requestID, predicted_price)
示例#3
0
# In[38]:

f = open('msft6.txt', 'w')
f.write(
    str(
        microsoft.buy_and_hold(start_date='1999-01-05',
                               end_date='2002-01-03',
                               nshares=100)))
f.close()

# In[39]:

microsoft.changepoint_date_analysis()

# In[40]:

f = open('msft7.txt', 'w')
f.write(str(microsoft.changepoint_date_analysis()))
f.close()

# In[41]:

model, future = microsoft.create_prophet_model(days=30)

# In[42]:

f = open('msft8.txt', 'w')
f.write(str(microsoft.create_prophet_model(days=30)))
f.close()
示例#4
0
from stocker import Stocker

hp = Stocker("HPQ")
stock_history = hp.stock
print(stock_history.head())

model, model_data = hp.create_prophet_model()
model.plot_components(model_data)
plt.show()
示例#5
0
def GetStockPrediction(csvfile,ticker,inifile,litemode=False):
	### MAKE HISTORY GRAPH.
	hstg = 30 # number of days 

	# Define files and filetypes
	ext = ".pdf"
	ModZ =[str(stocksfolder+ticker+".HighLowClose" + ext), #0
				str(stocksfolder+ticker+".ChangeVolume"+ext),   #1
				str(stocksfolder+ticker+".ChangePoint"+ext),    #2
				# str(stocksfolder+ticker+".ChangePointTrends"+ext),#3
				str(stocksfolder+ticker+".evaluate_prediction"+ext),#4
				str(stocksfolder+ticker+".TrendsA"+ext),#5
				str(stocksfolder+ticker+".Naive" + str(hstg) + ext)]
				#6
	StockFiles=[str(stocksfolder+ticker+".HighLowClose" + ext), #0
				str(stocksfolder+ticker+".ChangeVolume"+ext),   #1
				str(stocksfolder+ticker+".ChangePoint"+ext),    #2
				str(stocksfolder+ticker+".ChangePointTrends"+ext),#3
				str(stocksfolder+ticker+".evaluate_prediction"+ext),#4
				str(stocksfolder+ticker+".TrendsA"+ext),#5
				str(stocksfolder+ticker+".Naive" + str(hstg) + ext),#6
				# ACTUAL MACHINE LEARNING BEGINS
				str(stocksfolder+ticker+".linear_regression_01"+ext)]#7

	# print(csvfile)

	# df = pd.read_csv(csvfile)
	


	## START ANALSYS.
	
	Months = str((today - datetime.timedelta(days=hstg)).date())
	### Stocker is initialized and will retrieve the entire stock's data as it is read in the file.
	stock = Stocker(ticker=ticker, 
		exchange='CSV',
		csv_repository='stocks')
	print(stock.stock.head())
	plt.clf()

	### plot_stock will plot the stock's (High, Low, Close) recent history. see 'hstg' for number of days

	stock.plot_stock(start_date = str(Months),
		stats = ['high', 'low', 'close'],
		plot_type='hlc',
		filename=StockFiles[0])
	plt.clf()

	### plot_stock will plot the Stock's (Daily Change, Volume) recent history. see 'hstg' for number of days

	stock.plot_stock(start_date = str(Months) ,
		stats = ['Daily Change', 'volume'], 
		plot_type='pct',
		filename=StockFiles[1])
	plt.clf()

	stock.changepoint_date_analysis(filename=StockFiles[2])
	plt.clf()

	# stock.buy_and_hold(start_date=str(Months),nshares=1,filename=str(stocksfolder+ticker+".PredictedBuyHold"+ext)) # This function is broken.
	# plt.clf()

	stock.evaluate_prediction(start_date=str(Months),nshares=1,filename=StockFiles[4])
	plt.clf()

	## START BASIC PREDICTIONS BASED ON ANALYSIS
	model, model_data = stock.create_prophet_model()
	model.plot_components(model_data)
	plt.savefig(StockFiles[5])
	plt.clf()

	stock.predict_future(days=hstg,filename=StockFiles[6])
	plt.clf()

	# START MORE ADVANCED PREDICTONS BASED ON DEEP LEARNING.
	if litemode:
		pass
	else:
		### changepoint_date_analysis is looking through historical data of the past 3 years to find the optimal time to buy or sell a stock.
		print(inifile)
		search_terms = inifile["STOCK PROFILE"]["search_terms"]
		# print(search_terms)
		bountylist = search_terms.split(",")
		# print(bountylist)
		stock.changepoint_date_analysis(search=bountylist,filename=StockFiles[3])
		plt.clf()
		# LINEAR REGRESSION 01
		stock.Stocker_linear_regression(days=hstg, filename=StockFiles[7])
		plt.clf()

	## Merge files into a pdf.
	
	if litemode:
		ModZ = ModZ; print(ModZ)
	else:
		ModZ = StockFiles[:]; print(ModZ)
		# thelimit = len(ModZ)
	
	Merge_PDFS(ModZ,reportsfolder+ticker+"._REPORT.PDF")
示例#6
0
from stocker import Stocker

amazon = Stocker('AMZN')
amazon.plot_stock()
# predict days into the future
model, model_data = amazon.create_prophet_model(days=90)
amazon.evaluate_prediction()
    price = df.squeeze()
    #print(price.head())
    #print(price.index)

    Target = Stocker(price, name=sid)

    #Target.changepoint_prior_validation(start_date ='2015-12-03',end_date ='2018-12-21',changepoint_priors = [0.3,0.4,0.45,0.5,0.6])

    #Target.plot_stock()

    #原始參數預測
    #model, model_data = Target.create_prophet_model(days=10)
    #原始參數回測
    #Target.evaluate_prediction()

    #Target.changepoint_prior_analysis(changepoint_priors=[0.001, 0.05, 0.1, 0.2])

    #Target.changepoint_prior_validation(start_date='2015-01-07', end_date='2018-12-21', changepoint_priors=[0.05,0.1,0.2,0.3,0.4])

    #調整參數為0.4
    Target.changepoint_prior_scale = 0.1
    #Target.changepoint_prior_scale = 0.6
    #修改後回測
    Target.evaluate_prediction()
    #修改後參數預測
    Target.predict_future(days=30)
    Target.predict_future(days=90)
    model, model_data = Target.create_prophet_model(days=60)

    #Target.evaluate_prediction(start_date='2017-12-15', end_date='2018-12-17', nshares=1000)
示例#8
0
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 20, 10
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LinearRegression
from fastai.structured import add_datepart
import tensorflow as tf
from tensorflow.keras import layers
from sklearn import neighbors
from sklearn.model_selection import GridSearchCV
from pandas.util.testing import assert_frame_equal

goog = Stocker('GOOGL')
goog.plot_stock()

# Create model
model, model_data = goog.create_prophet_model(days=90)
goog.evaluate_prediction()

# Optimize the model
goog.changepoint_prior_analysis(changepoint_priors=[0.001, 0.05, 0.1, 0.2])
goog.changepoint_prior_validation(start_date='2016-01-04',
                                  end_date='2017-01-03',
                                  changepoint_priors=[0.001, 0.05, 0.1, 0.2])

# Evaluate the new model
goog.evaluate_prediction()
print(goog.evaluate_prediction(nshares=1000))

# Getting the dataframe of the data
goog_data = goog.make_df('2004-08-19', '2018-03-27')
print(goog_data.head(50))
示例#9
0
from stocker import Stocker
import matplotlib.pyplot as plt

microsoft = Stocker(ticker='MSFT')

stock_history = microsoft.stock
# microsoft.plot_stock(start_date='2001-01-05', end_date='2002-02-05', stats=["Adj. Close"], plot_type="basic")
# microsoft.buy_and_hold(start_date='2001-01-05', end_date='2002-02-05', nshares=200)

model, model_data = microsoft.create_prophet_model()

model.plot_components(model_data)
plt.show()
print(microsoft.weekly_seasonality)
microsoft.weekly_seasonality = True
print(microsoft.weekly_seasonality)

model, model_data = microsoft.create_prophet_model(days=0)
model.plot_components(model_data)
plt.show()
microsoft.weekly_seasonality = False
microsoft.changepoint_date_analysis()
model, future = microsoft.create_prophet_model(days=180)
示例#10
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep  1 20:43:37 2018

@author: https://towardsdatascience.com/stock-prediction-in-python-b66555171a2
"""

#%%
from stocker import Stocker

teradyne = Stocker('TER')

#%%
model, model_data = teradyne.create_prophet_model(days=180)

#%%
teradyne.stock.head()

#%%
teradyne.evaluate_prediction(nshares=100)

#-------------
#%%

twtr = Stocker('TWTR')
#%%
model, model_data = twtr.create_prophet_model(days=200)

#%%
twtr.stock.tail()
示例#11
0
'''
Created on 2019 M01 21

@author: kgap1
'''

from stocker import Stocker
 
aurora = Stocker('ACB.TO')
aurora.plot_stock()
# predict days into the future
model, model_data = aurora.create_prophet_model(days=90)
# import pystan
# model_code = 'parameters {real y;} model {y ~ normal(0,1);}'
# model = pystan.StanModel(model_code=model_code)  # this will take a minute
# y = model.sampling(n_jobs=1).extract()['y']
# y.mean()  # should be close to 0
示例#12
0
f.close()


# In[18]:


britishmidland.changepoint_date_analysis()


# In[19]:


f = open('./BMI/bmi7.txt','w')
f.write(str(britishmidland.changepoint_date_analysis()))
f.close()


# In[20]:


model, future = britishmidland.create_prophet_model(days=30)


# In[21]:


f = open('./BMI/bmi8.txt','w')
f.write(str(britishmidland.create_prophet_model(days=30)))
f.close()

示例#13
0
# Stock is an attribute of the microsoft object
stock_history = microsoft.stock
stock_history.head()

# A method (function) requires parentheses
microsoft.plot_stock()

microsoft.plot_stock(start_date='2000-01-03',
                     end_date='2018-01-16',
                     stats=['Daily Change', 'Adj. Volume'],
                     plot_type='pct')

microsoft.buy_and_hold(start_date='1986-03-13',
                       end_date='2018-01-16',
                       nshares=100)

microsoft.buy_and_hold(start_date='1999-01-05',
                       end_date='2002-01-03',
                       nshares=100)
model, model_data = microsoft.create_prophet_model()

# model and model_data are from previous method call
model.plot_components(model_data)
plt.show()

print(microsoft.weekly_seasonality)
microsoft.weekly_seasonality = True
print(microsoft.weekly_seasonality)

microsoft.changepoint_date_analysis()
示例#14
0
def stockPrediction():
    print(
        "enter the code for the company you want to check the predictions of:")
    companyCode = input()
    st = Stocker(companyCode)
    st.create_prophet_model()
                     StockName.predict(dates),
                     color='black',
                     label='Observations')
            plt.plot(StockName.dates,
                     StockName.predict(dates),
                     color='black',
                     label='Observations')
            plt.plot(StockName.dates,
                     StockName.predict(dates),
                     color='blue',
                     label='Predicted',
                     attr='bold')
            plt.plot(StockName.dates,
                     StockName.predict(dates),
                     color='yellow',
                     label='Confidence Interval',
                     attr='block')
            plt.plot(StockName.midpoint.random(dates),
                     label='Prediction Start',
                     color='red',
                     attr='dotted')

            plt.xlabel('Date')
            plt.ylabel('Price $')
            plt.title(StockName, 'Model Evaluation from ', Startdate, 'to ',
                      Enddate)


model, model_data = StockName.create_prophet_model(days=no_of_days)
StockName.evaluate_prediction()
示例#16
0
get_ipython().system('pip install quandl')
get_ipython().system('pip install fbprophet')
get_ipython().system('pip install pytrends')

from stocker import Stocker
import quandl
quandl.ApiConfig.api_key = 'AsJgrNdvc_MbnWxwNB4V'
import matplotlib.pyplot as plt

ms = Stocker('MSFT')

ms.plot_stock()
ms.changepoint_date_analysis()
ms.buy_and_hold(start_date='2017-09-01', end_date='2018-03-01', nshares=100)
model, future = ms.create_prophet_model(days=180)