Skip to content

Commit 625fa9f

Browse files
committed
Merge branch 'master' of https://github.com/gosunfish/IntroToPython into gosunfish-master
Conflicts: .gitignore slides_sources/old_versions/week-06/code/lambda/lambda_keyword.pyc
2 parents b689717 + ee1dc3b commit 625fa9f

File tree

18 files changed

+472
-48
lines changed

18 files changed

+472
-48
lines changed

.gitignore

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
slides_sources/build
2-
2+
.idea
33
.DS_Store
44
#ignore compiled files, sublime workspace and project files
55
*.pyc
@@ -12,4 +12,4 @@ slides_sources/build
1212
.gitignore
1313

1414
# editor back-up files
15-
*.*~
15+
*.*~

Students/A.Kramer/Final_Project/Chart.py

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import matplotlib.pyplot as plt
99
import matplotlib.ticker as mticker
1010
import matplotlib.dates as mdates
11-
from matplotlib.finance import candlestick
11+
from matplotlib.finance import candlestick
1212
import pylab
1313

1414
# adjusted font size for the plots
@@ -20,7 +20,7 @@ def rsiFunc(prices, n=14):
2020
deltas = np.diff(prices)
2121
seed = deltas[:n+1]
2222
up = seed[seed >= 0].sum() / n
23-
down = -seed[seed<0].sum() / n
23+
down = -seed[seed < 0].sum() / n
2424
rs = up/down
2525
rsi = np.zeros_like(prices)
2626
rsi[:n] = 100. - 100./(1. + rs)
@@ -32,12 +32,12 @@ def rsiFunc(prices, n=14):
3232
else:
3333
upval = 0.
3434
downval = -delta
35-
up = (up * (n-1) +upval) / n
35+
up = (up * (n-1) + upval) / n
3636
down = (down*(n-1) + downval) / n
3737
rs = up/down
3838
rsi[i] = 100. - 100. / (1. + rs)
3939
return rsi
40-
40+
4141
# define moving average function
4242
def movingaverage(values, window):
4343
weights = np.repeat(1.0, window) / window
@@ -48,11 +48,11 @@ def graphData(stock, MA1=12, MA2=26):
4848
try:
4949
# define the data file
5050
stockFile = "./data/" + stock + ".txt"
51-
51+
5252
# Load data into numpy arrays
53-
date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=",",
53+
date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=",",
5454
unpack=True, converters = {0: mdates.strpdate2num("%Y%m%d")})
55-
55+
5656
#-----------------------------------------------------------------------------------------------
5757
# building data for drawing plotting candlestick chart. Basically, a an array of comma separated
5858
# values. The order of elements is very specific, so check the documentation for candlestick
@@ -64,20 +64,20 @@ def graphData(stock, MA1=12, MA2=26):
6464
appendLine = date[x], openp[x], closep[x], highp[x], lowp[x], volume[x]
6565
candleArray.append(appendLine)
6666
x += 1
67-
67+
6868
# moving averages for 12 and 26 days
6969
Av1 = movingaverage(closep, MA1)
7070
Av2 = movingaverage(closep, MA2)
7171
# Starting point for graphs
7272
SP = len(date[MA2-1:])
7373
# Creating Moving Average labels
74-
label1=str(MA1) + " SMA"
75-
label2=str(MA2) + " SMA"
76-
77-
78-
# changing the face color of the graphics
74+
label1 = str(MA1) + " SMA"
75+
label2 = str(MA2) + " SMA"
76+
77+
78+
# changing the face color of the graphics
7979
fig = plt.figure(facecolor="#07000D")
80-
80+
8181
# create room and plot candlestick chart
8282
ax1 = plt.subplot2grid((5,4), (1,0), rowspan=4, colspan=4, axisbg="#07000D")
8383
candlestick(ax1, candleArray[-SP:], width=0.75, colorup="#9EFF15", colordown="#FF1717")
@@ -109,9 +109,9 @@ def graphData(stock, MA1=12, MA2=26):
109109
pylab.setp(textEd[0:5], color = "white")
110110
# Tilt the labels to 45 degrees
111111
for label in ax1.xaxis.get_ticklabels():
112-
label.set_rotation(45)
113-
114-
112+
label.set_rotation(45)
113+
114+
115115
# set up RSI area
116116
ax0 = plt.subplot2grid((5,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg="#07000d")
117117
#plot RSI
@@ -134,10 +134,10 @@ def graphData(stock, MA1=12, MA2=26):
134134
ax0.set_yticks([30,70])
135135
ax0.yaxis.label.set_color("white")
136136
plt.ylabel("RSI")
137-
138-
137+
138+
139139
# Plot volume on the same range as ax1
140-
volumeMin = 0
140+
volumeMin = 0
141141
ax1v = ax1.twinx()
142142
# subtract moving average calculations
143143
ax1v.fill_between(date[-SP:], volumeMin, volume[-SP:], facecolor="#00FFE8", alpha=.5)
@@ -154,23 +154,23 @@ def graphData(stock, MA1=12, MA2=26):
154154
# Change axis color
155155
ax1v.tick_params(axis="x", colors="white")
156156
ax1v.tick_params(axis="y", colors="white")
157-
158-
157+
158+
159159
# Setting up the overall appearance of the plot
160160
plt.subplots_adjust(left=.08, bottom=.14, right=.95, top=.95, wspace=.20, hspace=0)
161161
plt.suptitle(stock, color="white")
162162
plt.setp(ax0.get_xticklabels(), visible=False)
163163
plt.show()
164164
fig.savefig("./data/" + stock + ".png", facecolor=fig.get_facecolor())
165-
165+
166166
except Exception, e:
167167
print "main loop", str(e)
168-
168+
169169
if __name__ == "__main__":
170170
# testing the calls
171171
# a list of stocks to process (for testing)
172172
stocksToPull = 'AAPL', 'GOOG', 'AMZN', 'EBAY', 'CMG', 'MSFT', 'C', 'BA', 'TSLA'
173-
173+
174174
graphData(stocksToPull[3])
175-
175+
176176

Students/A.Kramer/Final_Project/DataFactory.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,28 @@ def pullStockData(stock):
1212
# check if data directory exists, if not, create
1313
if not os.path.exists("./data"):
1414
os.makedirs("./data")
15-
15+
1616
# print out the pull time
1717
print "Pulling stock", stock, "\t",
1818
print str(datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"))
19-
19+
2020
# define url and file
21-
urlToVisit="http://chartapi.finance.yahoo.com/instrument/1.0/" + stock + "/chartdata;type=quote;range=1y/csv"
21+
urlToVisit = "http://chartapi.finance.yahoo.com/instrument/1.0/" + stock + "/chartdata;type=quote;range=1y/csv"
2222
saveFileLine = stock + ".txt"
23-
23+
2424
# Determine the time of the last entry in the file, if file exists
2525
# set the last Unix time to 0, if file dies not exist
2626
try:
2727
existingData = open("./data/" + saveFileLine, "r")
28-
allLines = existingData.read();
28+
allLines = existingData.read()
2929
splitExisting = allLines.split("\n")
3030
lastLine = splitExisting[-2]
3131
lastUnix = int(lastLine.split(",")[0])
3232
existingData.close()
3333
except Exception, e:
3434
print "Pulling data: Determining last date", e
3535
lastUnix = 0
36-
36+
3737
# Obtain data for the ticket from Yahoo finance and split the file by new line
3838
sourceCode = urllib2.urlopen(urlToVisit).read()
3939
splitSource = sourceCode.split("\n")
@@ -59,12 +59,11 @@ def pullStockData(stock):
5959
print "Sleeping....."
6060
print str(datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"))
6161
time.sleep(3)
62-
63-
62+
63+
6464
# Pull the data for selected stocks
6565
if __name__ == "__main__":
6666
# Testing data pull
6767
stocksToPull = 'AAPL', 'GOOG', 'AMZN', 'EBAY', 'CMG', 'MSFT', 'C', 'BA', 'TSLA'
6868
pullStockData(stocksToPull[3])
69-
70-
69+

Students/A.Kramer/Final_Project/RunFinal.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
and graphs the data using matplotlib, displaying candlestick chart,
66
simple moving averages for 12 and 26 days (default), and a Relative
77
Strength Index (RSI) for selected stock.
8-
8+
99
I found an excellent video tutorial on financial graphing with python
1010
that shows how to use matplotlib, change parameters of the plots
1111
and to do math calculation to derive moving averages and RSI indexes.
@@ -22,8 +22,7 @@ def runCode():
2222
answer = raw_input("Enter The stock to graph: ")
2323
pullStockData(answer.upper().strip())
2424
graphData(answer.upper().strip())
25-
25+
2626
# run main program
2727
if __name__ == "__main__":
2828
runCode()
29-

Students/CarolynEvans/final_project/__init__.py

Whitespace-only changes.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import yaml
2+
3+
class config():
4+
"""
5+
This class parses config.yaml into a dictionary and provides callability.
6+
"""
7+
_VALUES = dict()
8+
9+
def __init__(self):
10+
with open('config.yaml', 'r') as f:
11+
config = yaml.load(f)
12+
13+
self.flatten(config)
14+
15+
16+
def flatten(self, config):
17+
"""
18+
This method loads a dictionary using the data that was loaded from config.yaml in __init__.
19+
The yaml dictionary 'values' may potentially be another dictionary.
20+
This method is used recursively to explode all levels of the yaml into a flat dictionary.
21+
:param config: A dict containing configuration values.
22+
:return: There is no return value. This method is called during __init__.
23+
"""
24+
# TODO: Rewrite for loop as comprehension
25+
26+
for key, val in config.items():
27+
if type(val) is dict:
28+
self.flatten(val)
29+
else:
30+
self._VALUES[key]=val
31+
32+
33+
34+
def get(self, key):
35+
"""
36+
This method is provides a configuration value for the given 'key'.
37+
:param key: A string containing the 'key' of the config item in the config dict.
38+
:return: A string containing the value of the config item in the config dict.
39+
"""
40+
val = self._VALUES[key]
41+
return val
42+
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
data_warehouse_config:
2+
dw_dbname: "********"
3+
dw_user: "*******"
4+
dw_password: "********"
5+
dw_host: "********"
6+
dw_port: "****"
7+
8+
9+
hummingbird_config:
10+
hummingbird_url: ******
11+
12+
email_config:
13+
email_server: ******
14+
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import psycopg2
2+
from psycopg2._psycopg import ProgrammingError
3+
from config import config
4+
5+
class data_warehouse(object):
6+
'''
7+
This class is used to get data from the Rightside data warehouse.
8+
The complete data warehouse documentation can be found at
9+
https://wiki.rightside.net/display/tnt/BI
10+
'''
11+
12+
def __init__(self):
13+
"""
14+
This method sets the data warehouse connection string from the config.
15+
"""
16+
cnf = config()
17+
dbname = cnf.get('dw_dbname')
18+
user = cnf.get('dw_user')
19+
password = cnf.get('dw_password')
20+
host = cnf.get('dw_host')
21+
port = cnf.get('dw_port')
22+
23+
self.dw_connection_string = \
24+
"dbname='{}' user='{}' password='{}' host='{}' port='{}'".format(dbname,user,password,host,port)
25+
26+
27+
def __call__(self, query):
28+
"""
29+
This method calls the data warehouse API.
30+
The complete data warehouse documentation can be found at
31+
https://wiki.rightside.net/display/tnt/BI
32+
:param query: A string containing a valid redshift data warehouse query.
33+
:return: This depends on the query.
34+
If the query returns records, as in a 'select' query, the records are returned.
35+
If the query does not return records, as in an 'update' query, a unicode string is returned.
36+
"""
37+
with psycopg2.connect(self.dw_connection_string) as conn:
38+
with conn.cursor() as curs:
39+
curs.execute(query)
40+
41+
try:
42+
records = curs.fetchall()
43+
return records
44+
except ProgrammingError as e:
45+
# This error occurs when there are no records to return,
46+
# for example, queries such as inserts, updates, and unloads.
47+
message = unicode(e)
48+
if message == u'no results to fetch':
49+
return message
50+
else:
51+
raise message
52+
53+
54+
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import urllib2
2+
import json
3+
4+
from config import config
5+
6+
class hummingbird(object):
7+
"""
8+
This class is used to call the DizzyNinja Hummingbird Domain Recommendation API.
9+
The complete hummingbird API documentation can be found at
10+
https://wiki.rightside.net/display/tnt/API+Documentation
11+
"""
12+
13+
def __init__(self):
14+
"""
15+
This method sets the hummingbird url from the config.
16+
"""
17+
cnf = config()
18+
self.url = cnf.get('hummingbird_url')
19+
20+
21+
def __call__(self, command, **kwargs):
22+
"""
23+
This method calls the hummingbird API.
24+
The complete hummingbird API documentation can be found at
25+
https://wiki.rightside.net/display/tnt/API+Documentation
26+
:param command: A string containing a valid hummingbird command.
27+
:param kwargs: Depends on 'command'. See hummingbird documentation for complete list.
28+
:return: Returns JSON with results for the 'command'.
29+
"""
30+
31+
# build the query string parameter for the hummingbird API http request.
32+
query_string = "".join(['{}={},'.format(key,val) for key, val in kwargs.items()])
33+
34+
#add the 'command' and the query string to the url.
35+
url = '{}{}?{}'.format(self.url, command, query_string)
36+
37+
response = urllib2.urlopen(url).read()
38+
return json.loads(response)
39+
40+
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
# TODO: Get list of registered domain names from data warehouse
3+
# TODO: Get list of premium domains from data warehouse
4+
# TODO: Call word splitter on both lists and save each in a dict with
5+
# original domain name as key and split words as values.
6+
# TODO: Sort split words for each domain name.
7+
# TODO: Compare split words for registered domain to split words for premium domains.
8+
# TODO: Get registered owners contact info from data warehouse.
9+
# TODO: Write file that can be opened in excel.
10+
11+
12+

0 commit comments

Comments
 (0)