-
Notifications
You must be signed in to change notification settings - Fork 48
/
utilgraph.py
157 lines (128 loc) · 4.54 KB
/
utilgraph.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
156
import os.path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator,DayLocator, MONDAY
from matplotlib.finance import candlestick_ohlc
import indicator as ind
import utility as utl
import utilmodel as utm
def plotStock(df, columns, start_index, end_index, title="Selected data"):
"""Plot the desired columns over index values in the given range."""
df_plot = df.ix[start_index:end_index, columns]
"""Plot stock prices with a custom title and meaningful axis labels."""
ax = df_plot.plot(title=title, fontsize=12)
ax.set_xlabel("Date")
ax.set_ylabel("Price")
plt.show()
# Borrowed code from : https://www.udacity.com/course/machine-learning-for-trading--ud501
def plotDailyHist(df, symbol, title="Selected data"):
"""Plot the desired columns over index values in the given range."""
df_plot = ind.daily_returns(df)[symbol]
"""Plot stock prices with a custom title and meaningful axis labels."""
df_plot.hist(bins=20)
ax = plt.axvline(df_plot.mean(), color='w', linestyle='dashed',linewidth=2)
std = df_plot.std()
plt.axvline(std, color='r', linestyle='dashed',linewidth=2)
plt.axvline(-std, color='r', linestyle='dashed',linewidth=2)
#ax.set_xlabel("Daily returns")
#ax.set_ylabel("Frequency")
plt.show()
# Borrowed code from : http://matplotlib.org/examples/pylab_examples/finance_demo.
def plotCandlestick(symbol, start_index, end_index, title="Selected data"):
dates = pd.date_range(start_index, end_index)
quotes = utl.loadStockQuotes(symbol, dates)
mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
alldays = DayLocator() # minor ticks on the days
weekFormatter = DateFormatter('%b %d') # e.g., Jan 12
dayFormatter = DateFormatter('%d') # e.g., 12
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
#ax.xaxis.set_minor_formatter(dayFormatter)
#plot_day_summary(ax, quotes, ticksize=3)
candlestick_ohlc(ax, quotes, width=0.6)
ax.xaxis_date()
ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
plt.show()
def plotHistory(data):
plt.figure(figsize=(6, 3))
plt.plot(data)
plt.ylabel('error')
plt.xlabel('iteration')
plt.title('training error')
plt.show()
def _plotColorLine(close, Ydigit, ax):
# sytles = ['-r', '-g']
green = close.where(Ydigit==1) # new height
red = close.where(Ydigit==0) # not
ax.plot(red.index, red.values, '-r', green.index, green.values,'-g')
ax.legend(['Not', 'predict new high'])
def plot1ColLine(close, Ydigit, title):
_plotColorLine(close, Ydigit, plt)
plt.title(title)
plt.xlabel('Dates')
plt.ylabel('Price')
plt.show()
def plot2ColLine(symbol, X1, Y1, title1, X2, Y2, title2):
fig = plt.figure()
plt.gcf().canvas.set_window_title(symbol)
fig.set_facecolor('#FFFFFF')
ax1 = fig.add_subplot(1,2,1)
ax1.set_title(title1)
ax1.set_xlabel('Dates')
ax1.set_ylabel('Price')
ax1.get_xaxis().set_visible(False)
ax2 = fig.add_subplot(1,2,2)
ax2.set_title(title2)
ax2.set_xlabel('Dates')
ax2.set_ylabel('Price')
ax2.get_xaxis().set_visible(False)
_plotColorLine(X1, Y1, ax1)
_plotColorLine(X2, Y2, ax2)
PIC_PATH = 'debug'
if os.path.exists(PIC_PATH) == False:
os.makedirs(PIC_PATH)
plt.savefig(os.path.join(PIC_PATH, '%s.jpg' % (symbol)))
plt.show()
def plotPCA2d(Xpca, Ydigit):
colors = ['red', 'green']
for number in range(0,2): # 0 to 1
XY = Xpca[np.where(Ydigit == number)[0]]
# seperate to x, y component
x = XY[:, 0]
y = XY[:, 1]
plt.scatter(x, y, c=colors[number])
plt.legend(['Not', 'predict new high in 14 days'])
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')
plt.show()
def plotPCA3d(Xpca, Ydigit):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
colors = ['red', 'green']
for number in range(0,2): # 0 to 1
XYZ = Xpca[np.where(Ydigit == number)[0]]
# seperate to x, y, z component
x = XYZ[:, 0]
y = XYZ[:, 1]
z = XYZ[:, 1]
ax.scatter(x, y, z, c=colors[number])
plt.legend(['Not', 'predict new high in 14 days'])
ax.set_xlabel('First Principal Component')
ax.set_ylabel('Second Principal Component')
ax.set_zlabel('Third Principal Component')
plt.show()
def plotPCA(X, Y):
# Visualize data
# convert to 2 components
Xpca = utm.getPCAvalues(X , 2)
assert Xpca.shape[1] == 2
plotPCA2d(Xpca, Y)
# convert to 3 components
Xpca = utm.getPCAvalues(X , 3)
assert Xpca.shape[1] == 3
plotPCA3d(Xpca, Y)