def execute(self): stock_list = [ "GLO", "ALI", "FMETF", "TEL", "ICT", "SCC", "MER", "SHLPH", "UBP", "PSE" ] #stock_list = ["TEL", "ICT", "SCC", "MER", "SHLPH", "UBP", "PSE"] for stock_no in stock_list: yesterday = datetime.datetime.now() - datetime.timedelta(days=1) yesterday = yesterday.strftime('%Y-%m-%d') d30ago = datetime.datetime.now() - datetime.timedelta(days=45) d30ago = d30ago.strftime('%Y-%m-%d') df = get_pse_data(stock_no, d30ago, yesterday) continue_3day, close_price = self.continue_3day(df) continue_10day, close_price = self.continue_10day(df) if continue_3day == True and continue_10day == False: msg = "Stock {stock} 5日線站上20日均線,均線向上,昨日價格為{price}".format( stock=stock_no, price=close_price) print(msg) if continue_3day == False and continue_10day == True: msg = "Stock {stock} 5日線跌破20日均線,均線向下,昨日價格為{price}".format( stock=stock_no, price=close_price) print(msg)
def test_get_pse_data(): stock_df = get_pse_data(PHISIX_SYMBOL, DATE_START, DATE_END, format="c") assert isinstance(stock_df, pd.DataFrame)
def test_get_pse_data(): stock_df = get_pse_data(SYMBOL, DATE_START, DATE_END) assert isinstance(stock_df, pd.DataFrame)
def __init__(self, StockCode, StartDate, EndDate): log_txt.insert(INSERT, 'getting price list\n') try: df = get_pse_data(StockCode, StartDate, EndDate) except Exception as e: log_txt.insert(INSERT, 'Get pse data error: {e}\n'.format(e=e)) log_txt.insert(INSERT, 'price list obtained') # Derive the 30 day SMA of JFC's closing prices ma30 = df.close.rolling(30).mean() ma100 = df.close.rolling(100).mean() # Combine the closing prices with the 30 day SMA data = pd.concat([df.close, ma30, ma100], axis=1).dropna() data.columns = [ 'Closing Price', 'Simple Moving Average (30 day)', 'Simple Moving Average (100 day)' ] #Create a new dataframe signal = pd.DataFrame(index=df['close'].index) signal['close'] = data['Closing Price'] signal['SMA30'] = data['Simple Moving Average (30 day)'] signal['SMA100'] = data['Simple Moving Average (100 day)'] log_txt.insert(INSERT, 'calculate RSI\n') v_RSI = RSI.getRSI(self, signal) log_txt.insert(INSERT, 'done calculating RSI\n') log_txt.insert(INSERT, 'calculate moving averages\n') MA = MovingAverage.buy_sell(signal) log_txt.insert(INSERT, 'done calculating moving averages\n') try: signal['Buy_Signal_Price_MA'] = MA[0] signal['Sell_Signal_Price_MA'] = MA[1] signal['Buy_Signal_Price_RSI'] = v_RSI[0] signal['Sell_Signal_Price_RSI'] = v_RSI[1] except Exception as e: log_txt.insert(INSERT, 'Get buy and sell data error: {e}\n'.format(e=e)) # Visually Show The Stock buy and sell signals # Create the title title = 'Adj. Close Price History Buy / Sell Signals ' # Get the stocks my_stocks = signal ticker = "close" # Create and plot the graph try: plt.figure(figsize=(12.2, 4.5)) # width = 12.2in, height = 4.5 plt.scatter(my_stocks.index, my_stocks['Buy_Signal_Price_MA'], color='green', label='Buy Signal MA', marker='^', alpha=1) plt.scatter(my_stocks.index, my_stocks['Sell_Signal_Price_MA'], color='darkred', label='Sell Signal MA', marker='v', alpha=1) plt.scatter(my_stocks.index, my_stocks['Buy_Signal_Price_RSI'], color='blue', label='Buy Signal RSI', marker='^', alpha=1) plt.scatter(my_stocks.index, my_stocks['Sell_Signal_Price_RSI'], color='red', label='Sell Signal RSI', marker='v', alpha=1) plt.plot( my_stocks[ticker], label=ticker, alpha=0.35 ) # plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending, label) plt.plot(my_stocks['SMA30'], label='SMA30', alpha=0.35) plt.plot(my_stocks['SMA100'], label='SMA100', alpha=0.35) plt.title(title) plt.xlabel('Date', fontsize=18) plt.ylabel('Adj. Close Price PHP', fontsize=18) plt.legend(loc='upper left') except Exception as e: log_txt.insert(INSERT, 'Plotting data error: {e}\n'.format(e=e)) try: plt.show() except Exception as e: log_txt.insert(INSERT, 'Plotting data error: {e}\n'.format(e=e)) log_txt.insert(INSERT, 'Produced graph\n')
def __init__(self, stockCode, StartDate, EndDate): # get the stock price df = get_pse_data(stockCode, StartDate, EndDate) #print(df.tail()) '''#visualize plt.figure(figsize=(16,8)) plt.title("Closing Price History") plt.plot(df['close']) plt.xlabel("Date", fontsize=18) plt.xlabel("Closing Price", fontsize=18) #plt.show() ''' #dataframe with only closing data = df.filter(['close']) #convert to numpy array dataset = data.values #get the number of rows to train the model training_Data_len = math.ceil(len(dataset) * .8) #scale the data scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(dataset) #create the training data set #create the scaled training data set train_data = scaled_data[0:training_Data_len, :] #split the training data x: training y: target x_train = [] y_train = [] for i in range(60, len(train_data)): x_train.append(train_data[i - 60:i, 0]) y_train.append(train_data[i, 0]) '''if i<=60: print(x_train) print(y_train) print()''' #convert x_train and y_train to numpy arraws x_train, y_train = np.array(x_train), np.array(y_train) #reshape the data x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) #create the testing data set #create a new array containing scaled values test_data = scaled_data[training_Data_len - 60:, :] #Create the data sets x_test and y_test x_test = [] y_test = dataset[training_Data_len:, :] for i in range(60, len(test_data)): x_test.append(test_data[i - 60:i, 0]) #Convert the data into numpy arraw x_test = np.array(x_test) #reshape the data x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) # build the LSTM model model = Sequential() model.add( LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1))) model.add(LSTM(50, return_sequences=False)) model.add(Dense(25)) model.add(Dense(1)) # compile the model model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy']) # train the model model.fit(x_train, y_train, batch_size=1, epochs=1) #get the models predicted price values predictions = model.predict(x_test) predictions = scaler.inverse_transform(predictions) #print(predictions) #Get the root mean squared error rmse = np.sqrt(np.mean(predictions - y_test)**2) #plot the data train = data[:training_Data_len] valid = data[training_Data_len:] valid['predictions'] = predictions #visualize the model plt.figure(figsize=(16, 8)) plt.title('Model for {stockCode}'.format(stockCode=stockCode)) plt.xlabel('Date', fontsize=18) plt.ylabel('Close Price', fontsize=18) plt.plot(train['close']) plt.plot(valid[['close', 'predictions']]) plt.legend(['Train', 'Val', 'Predictions'], loc='lower right') plt.show() #show the valid and predicted prices #print(valid) #predict today's Closing price today = datetime.today() DD = timedelta(days=300) delta = today - DD d_today = datetime.today().strftime('%Y-%m-%d') d_delta = delta.strftime('%Y-%m-%d') #get the quote quote = get_pse_data(stockCode, d_delta, d_today) #create a new dataframe new_df = quote.filter(['close']) #get last 60 days data last_60_days = new_df[-60:].values #scale the data last_60_days_scaled = scaler.transform(last_60_days) #Create an empty list X_test = [] #append the past 60 days X_test.append(last_60_days_scaled) #Convert X_test to numpy arrau X_test = np.array(X_test) #reshape X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) #get the predicted scaled price pred_price = model.predict(X_test) #undo the scaling pred_price = scaler.inverse_transform(pred_price) print('Prediction Closing Price for today:', pred_price) # Override current model if acc greater # load json and create model json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("model.h5") loaded_model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy']) acc1 = loaded_model.evaluate(x_test, y_test, verbose=0) acc2 = model.evaluate(x_test, y_test, verbose=0) print(acc1) print(acc2) if acc1 < acc2: # serialize model to JSON model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model.h5") print('Overwrite model')
from fastquant import get_pse_data, backtest df = get_pse_data("JFC", "2018-01-01", "2019-01-01") backtest('smac', df, fast_period=15, slow_period=40)