HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Charting daily balance

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
balancechartingdaily

Problem

I have been trying my hand at Python lately. I have been able to look at code examples and create a custom application that queries a Microsoft SQL Server, pulls out two columns (date, balance) and charts them using pyplot embedded in tkinter for future development.

Because of the "chop and change" nature in which I wrote the code, I know there are plenty of bad practices and am looking for some constructive advice!
(I have removed the SQL script as it is huge)

```
import pymssql
import getpass
import matplotlib

matplotlib.rcParams['toolbar'] = 'None'
matplotlib.use('TkAgg')

import numpy as np
import tkinter as Tk
import matplotlib.dates as mdates
from matplotlib.figure import Figure

from matplotlib.ticker import FuncFormatter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def movingaverage(dvalues,window):
weights = np.repeat(1.00,window)/window
values = [float(val) for val in dvalues]
sma = np.convolve(values, weights, 'valid')
return sma

root = Tk.Tk()
root.wm_title("Daily balance tracker")

f = Figure(figsize=(10, 7), dpi=75)
a = f.add_subplot(111)

server = "RHYSPC"
user = "rhys"
password = getpass.getpass("Please enter password: ")
print("Loading results, please wait...")

conn = pymssql.connect(server, user, password, "RhysACC")

cursor = conn.cursor()

cursor.execute("""
SELECT Date, Balance FROM Example -- Not the actual query!
""")

results = cursor.fetchall()

x = [i[0] for i in results]
y = [i[1] for i in results]

yMA = movingaverage(y,31)

j = [0] * len(x)

conn.close()

def pounds(x, pos):
return '£%1.0d' % x

formatter = FuncFormatter(pounds)

f.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%Y'))
f.gca().xaxis.set_major_locator(mdates.YearLocator())
f.gca().yaxis.set_major_formatter(formatter)

a.plot(x, j, color='k', linewidth=2.0)
a.plot(x, y, color='b', linewidth=1.0)
a.plot(x[len(x)-len(yMA):], yMA, color='r', linewidth=1.5)

canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()

canvas._t

Solution

Using % for string formatting is deprecated, you should be using str.format instead. The str.format methods also allows you to do some cool things as well. Here's an example of it in action:

# No positional or named arguments
print "{} {}".format("Hello", "world")

# Positional arguments (*args)
print "{1} {0}".format("world", "Hello")

# Named arguments (**kwargs)
print "{word1} {word2}".format(word1="Hello", word2="world")


When running the line Tk.mainloop(), you should encapsulate it in an if __name__ == "__main__": block. See this Stackoverflow question for more details.

These two lines should be moved underneath all of your imports/includes:

matplotlib.rcParams['toolbar'] = 'None'
matplotlib.use('TkAgg')


I'm also noticing your lack of comments as well. Even if this is a small utility script, I'd still recommend adding comments for clarity.

Finally, a few of your variable names confuse me. For example, f, a, and j are all good examples of names that could be better. Try seeing if you can expand on these.

Code Snippets

# No positional or named arguments
print "{} {}".format("Hello", "world")

# Positional arguments (*args)
print "{1} {0}".format("world", "Hello")

# Named arguments (**kwargs)
print "{word1} {word2}".format(word1="Hello", word2="world")
matplotlib.rcParams['toolbar'] = 'None'
matplotlib.use('TkAgg')

Context

StackExchange Code Review Q#95889, answer score: 5

Revisions (0)

No revisions yet.