syntax

MRAB python at mrabarnett.plus.com
Tue Jan 19 02:32:06 CET 2010


marlowe wrote:
> I wrote this program, but i have a feeling like there might be a more
> practical way of writing it. Can someone give me an idea of how to
> simplify this? Here is an example of the csv file i am using. This
> program calculates the exponential moving average of the 20 day range.
> 
> USOtable.csv (full table found at http://ichart.finance.yahoo.com/table.csv?s=USO)
> 
> Date,Open,High,Low,Close,Volume,Adj Close
> 2010-01-15,38.97,39.02,38.28,38.40,12615300,38.40
> 2010-01-14,39.30,39.44,38.88,39.06,8575900,39.06
> 2010-01-13,39.40,39.71,38.63,39.21,15502700,39.21
> 2010-01-12,40.07,40.36,39.53,39.63,11960100,39.63
> 2010-01-11,41.09,41.19,40.46,40.54,8902200,40.54
> 2010-01-08,40.63,41.17,40.45,40.93,9393500,40.93
> 2010-01-07,40.87,41.08,40.68,40.72,10012000,40.72
> 2010-01-06,40.32,41.19,39.89,40.97,19789800,40.97
> 2010-01-05,40.25,40.45,39.93,40.41,10450200,40.41
> 
> 
> test.py
> 
> import csv
> 
> 
> reader = open('/prog/USOtable.csv','rb')
> data = [row for row in csv.reader(reader)]
>
data = list(csv.reader(reader))

> Nvals=
> [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
>

Nvals = [1] * 40

> 
> H=float(data[40][2])+float(data[41][2])+float(data[42][2])+float(data
> [43][2])\
> +float(data[44][2])+float(data[45][2])+float(data[46][2])+float(data
> [47][2])\
> +float(data[48][2])+float(data[49][2])+float(data[50][2])+float(data
> [51][2])\
> +float(data[52][2])+float(data[53][2])+float(data[54][2])+float(data
> [55][2])\
> +float(data[56][2])+float(data[57][2])+float(data[58][2])+float(data
> [59][2])\
> +float(data[60][2])
> 
H = sum(float(d[2]) for d in data[40 : 61])

> L=float(data[40][3])+float(data[41][3])+float(data[42][3])+float(data
> [43][3])\
> +float(data[44][3])+float(data[45][3])+float(data[46][3])+float(data
> [47][3])\
> +float(data[48][3])+float(data[49][3])+float(data[50][3])+float(data
> [51][3])\
> +float(data[52][3])+float(data[53][3])+float(data[54][3])+float(data
> [55][3])\
> +float(data[56][3])+float(data[57][3])+float(data[58][3])+float(data
> [59][3])\
> +float(data[60][3])
> 
L = sum(float(d[3]) for d in data[40 : 61])
> 
> Nvals[39]=(H-L)/2
> 
> 
> i=1
> while i <=38:
>     high=float(data[39-i][2])
>     low=float(data[39-i][3])
>     TR=high-low
>     Nvals[39-i]=(19*Nvals[40-i]+TR)/20
>     i+=1
> 
Instead of:

i=1
while i <=38:
    ...
    i+=1

you could use:

for i in range(1, 39):
    ...

Note that the start value is inclusive and the end value is exclusive.

> for value in Nvals:
>     print value





More information about the Python-list mailing list