-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathml_for_stock_trading.py
155 lines (155 loc) · 3.87 KB
/
ml_for_stock_trading.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
# # -*- coding: utf-8 -*-
# """ML for Stock Trading.ipynb
#
# Automatically generated by Colaboratory.
#
# Original file is located at
# https://colab.research.google.com/drive/15Ergxt4zGHY3Z9QWzXOtkZASfRD13btk
#
# <h2> Machine Learning for Stocks Trading </h2>
#
# Step 1: Getting some historical data.
#
# Libraries or Modules:
#
# Yahoo Finance module.
# Create Charts
# Handle dataframes - Pandas
# We need datetime functions
# """
#
# import pandas as pd
# import matplotlib.pyplot as plt
# from datetime import date, time
#
#
# #Install Yahoo Finance Libraries
# try:
# import yfinance
# except:
# !pip install -q yfinance
# import yfinance
# try:
# import yahoofinancials
# except:
# !pip install -q yahoofinancials
# import yahoofinancials
#
# import yfinance as yf
# from yahoofinancials import YahooFinancials
#
# import warnings
# warnings.filterwarnings("ignore")
#
# #Download our Historical Data
# df = yf.download('AAPL',
# start = '2010-01-01',
# end =date.today(),
# progress=False,)
#
# # Create a simple chart
# df.plot(y='Close', title='APPLE STOCK')
# plt.show()
#
# """Creating Technical Analysis Indicators and we are going to also plot them"""
#
# try:
# import pandas_ta as ta #create basic technical analysis
# except:
# !pip install -q pandas_ta
# import pandas_ta as ta
#
# df['RSI(2)'] = ta.rsi(df['Close'],length = 2)
# df['RSI(7)'] = ta.rsi(df['Close'],length = 7 )
# df['RSI(14)'] = ta.rsi(df['Close'],length = 14)
# df['CCI(30)'] = ta.cci(close= df['Close'],lenght = 30,high=df['High'],low=df['Low'])
# df['CCI(50)'] = ta.cci(close= df['Close'],lenght = 30,high=df['High'],low=df['Low'])
# df['CCI(100)'] = ta.cci(close= df['Close'],lenght = 30,high=df['High'],low=df['Low'])
#
# #Drop NaN Values
# df = df.dropna()
#
# #Create a plot showing some of our indicators
# df.plot(y='RSI(2)')
# df.plot(y='CCI(100)')
#
# #How's our current data frame going
# df.head()
#
# """Prepare our data labelling
#
# when we place our trade: Buy at Open (over the next day)
#
# Formula:
#
# Handling the returns this ways: Buy: Open(-1) - Closing: Open(-2)
#
# We want to label our data in the following day
#
# BUY SIGNAL: Open(-2) > Open (-1)
#
# SEEL SIGNAL: Open(-2) < Open(-1)
#
# Indicators the current situations, and our labels take a look ahead of time
#
#
# """
#
# import numpy as np
#
# df['LABEL'] = np.where(df['Open'].shift(-2).gt(df['Open'].shift(-1)),"1","0")
# df = df.dropna()
# df.head()
#
# """Creating a Neural Network
#
# SkLearn
# """
#
# import sklearn
# from sklearn.neural_network import MLPClassifier
# from sklearn.neural_network import MLPRegressor
# from sklearn.model_selection import train_test_split
# from sklearn.metrics import mean_squared_error
# from math import sqrt
# from sklearn.metrics import r2_score
#
#
# #Fitting - Indicators and our Labelling
#
# X = df[df.columns[6:-1]]
# y = df['LABEL'].values
#
# X_train , X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3)
#
# mlp = MLPClassifier(hidden_layer_sizes=(8,8,8),activation='relu',solver='adam',max_iter = 1000)
# mlp.fit(X_train,y_train)
#
# predict_train = mlp.predict(X_train)
# predict_test = mlp.predict(X_test,)
#
# from sklearn.metrics import classification_report,confusion_matrix
#
# print('Train Data Accuracy')
# print(classification_report(y_train,predict_train))
#
# print( ' Testing Data Accuracy')
# print(classification_report(y_test,predict_test))
#
# """Measure the returns obtained by trading our model"""
#
# df['Prediction'] = np.append(predict_train,predict_test)
# df['Strategy Returns'] = np.where( df['Prediction'].eq("1"),df['Open'].shift(-2)-df['Open'].shift(-1),0)
#
# df['Strategy Returns'] = df['Strategy Returns'].cumsum()
#
# df.plot(y='Strategy Returns')
# plt.plot()
#
# prediction = df.iloc[-1]['Prediction']
#
# if prediction == "1":
# print("Today's return forecast: UP")
# else:
# print("Today's retrun forecas: DOWN")
#