ServerPortfolio  2.0
Python parsers and server
 All Classes Namespaces Files Functions Variables Properties Pages
Utils.py
Go to the documentation of this file.
1 ## @package serverportfolio.Utils
2 # Utility functions
3 #
4 # Last Changed $Id: Utils.py 27 2015-04-25 16:16:47Z michael $
5 
6 import sys, types
7 import urllib2
8 import datetime, time
9 
10 from serverportfolio import GlobalDicts
12 
13 ## @brief Always return a list of strings.
14 #
15 # Assure the list format expected by Parsers::create_url
16 # @param stock a string ("CAC40") or a list of string ( ["CAC40","GSZ"] )
17 # @return list of strings
18 def to_list(stock):
19  # already a list is input
20  if type(stock) == types.ListType :
21  return stock
22  # if one element, make a list
23  elif type(stock) == types.StringType :
24  #print "it is a string"
25  list_stock = []
26  list_stock.append( stock )
27  return list_stock
28  # if a dictionary
29  elif type(stock) == types.DictType :
30  list_stock = []
31  list_stock.append( stock )
32  return list_stock
33  # error
34  return None
35 
36 ## @brief Always return a valid EAction from an Eaction or an EAction.name
37 # @param action EAction type or EAction.name
38 # @return valid EAction
39 # @throw PortfolioError
40 def stringToEAction( action ):
41 
42  # if already an EAction just return the object
43  if isinstance(action, GlobalDicts.EAction):
44  e_action = action
45 
46  elif type(action) == types.StringType:
47 
48  # do not want a try-catch each time this Utils.function is called...
49  try:
50  e_action = GlobalDicts.EAction[action]
51 
52  except KeyError, ex:
53  #except:
54  #print "sys.exc_info()[2] ", sys.exc_info()[2]
55  #print "traceback ", traceback.format_exc(3)
56  #print "KeyError ex:", ex
57 
58  # better sys.exc[], no good to extract into local variables if an other error, no GC'ed
59  raise PortfolioError( "Error in action, not a valid EAction\nOriginal error, %s : %s" % (sys.exc_info()[0].__name__, ex) )
60 
61  except:
62  self.logger.critical("General Exception in stringToEAction, SHOULD NOT HAPPEN !!")
63  raise
64 
65  else:
66  #print "sys.exc_info()[2] ", sys.exc_info()[2]
67  raise PortfolioError( "Cannot convert %s, type: %s, to a valid EAction" % (action, type(action)) )
68  # no improvment, miss the traceback
69  #raise PortfolioError( "Cannot convert %s to a valid EAction" % action ), None, sys.exc_info()[2]
70 
71  #print "return result"
72  return e_action
73 
74 
75 ## @brief Time function
76 # @code
77 # timestamp_to_string(1424991600) \n
78 # '2015-02-27 00:00:00'
79 # @endcode
81  return datetime.datetime.fromtimestamp( ts ).strftime('%Y-%m-%d %H:%M:%S')
82 
83 ## @brief opposite
84 # all seems to be in local time, like the rest of the application (1970-01-01 00:00:00 = -3600)
85 # http://stackoverflow.com/questions/9637838/convert-string-date-to-timestamp-in-python
86 def string_to_timestamp( str_date ):
87 
88  t1 = time.mktime(datetime.datetime.strptime(str_date, "%Y-%m-%d %H:%M:%S").timetuple())
89  # limited to local time ? timestamp()python > 3.3
90  # t2 = datetime.datetime.strptime(str_date,"%Y-%m-%d %H:%M:%S").timestamp()
91  # round stay float, round 1, 2 decimal ?
92  #t1 = round(t1)
93  t1 = int(t1)
94  return t1
95 
96 ## @brief Nice string output of python dictionary or list of dictionaries.
97 # The function is called recursively and deal with dictionary, list and simple values.
98 #
99 # Deal with a list of dict_data_stock, ok to improve, option multi-column...
100 # @param dict input can be a dictionary or a list of dictionaries
101 # @param out_str used only for recursive calls
102 # @param shift_nb only used for recursive calls
103 # @return a string containing the formatted output
104 # def pretty_dict_origin( dict, out_str = str(), shift_nb = 0 ):
105 #
106 # #print "\nPretty Dict:"
107 # #print "type(dict) ", type(dict)
108 # #print "out_str:", out_str,"!!!"
109 # #print dict
110 #
111 # shift_str=' '
112 # shift_str=shift_str * shift_nb
113 # #print "shift_str %d:%s!!!" % (shift_nb,shift_str)
114 #
115 # if (type(dict) == types.DictType): #| (type(dict) == types.ListType ):
116 #
117 # # if dictionary, for sure will call again
118 # #if (type(dict) == types.DictType) :
119 # # print key, check value. If List for value in dict: (and same logic)
120 # for key,value in dict.iteritems():
121 #
122 # #print "key::"+key+"!!"
123 # #specific entry
124 # #if key == 'list_dict':
125 # # out_str +='\n======= ' + value
126 # # pass
127 #
128 # # do not want to print key for symbol or list_dict
129 # #out_str += shift_str + key +' : '
130 #
131 # # recursive call
132 # if ( type(value) == types.DictType ) | ( type(value) == types.ListType ):
133 #
134 # # specific value, do not want to print
135 # if key == 'list_dict':
136 # pass
137 #
138 # else:
139 # out_str += shift_str + key +' : '
140 # out_str += '\n'
141 # # do not want to increase for each entry, maybe each stock
142 # shift_nb += 1
143 # #shift_nb = 1 #ok with one stock
144 # # append the new dictionary or list
145 # out_str = pretty_dict( value, out_str, shift_nb )
146 # # else simple value
147 # else :
148 #
149 # #specific entry
150 # if key == 'symbol':
151 # out_str +='\n======= ' + value + '\n'
152 # pass
153 # # not place to check
154 # #elif key == 'list_dict':
155 # # pass
156 # #out_str += shift_str + str(value)
157 # else :
158 # out_str += shift_str + key +' : '
159 # out_str += str(value)
160 # out_str += '\n'
161 #
162 # # works if values are a list,
163 # # need more test if elements are dictionary/an other List
164 # elif type(dict) == types.ListType :
165 #
166 # # check type of the first element, only for list
167 # if len(dict) > 0:
168 # type_elem = type( dict[0] )
169 # else:
170 # print "Empty dictionary in Utils.pretty_dict"
171 # return out_str
172 # #print "type_elem ", type_elem
173 #
174 # # case of list of dictionary, to add list of list ??
175 # if type_elem == types.DictType :
176 # #out_str += '\n'
177 # #shift_nb += 1
178 # for value in dict:
179 # out_str = pretty_dict( value, out_str, shift_nb )
180 # #shift_nb -= 1
181 # # simple value to print
182 # else :
183 # # need to loop
184 # out_str += shift_str + ', '.join(str(x) for x in dict)
185 # out_str += '\n'
186 # #shift_nb -= 1
187 #
188 # return out_str
189 
190 def pretty_dict( dict, out_str = str(), shift_nb = 0 ):
191 
192  shift_str=' '
193  shift_str=shift_str * shift_nb
194 
195  if (type(dict) == types.DictType): #| (type(dict) == types.ListType ):
196 
197  # if dictionary, for sure will call again
198  # print key, check value. If List for value in dict: (and same logic)
199  for key,value in dict.iteritems():
200 
201  # recursive call
202  if ( type(value) == types.DictType ) | ( type(value) == types.ListType ):
203 
204  # specific value, do not want to print
205  if key == 'list_dict':
206  pass
207 
208  else:
209  out_str += shift_str + key +' : '
210  out_str += '\n'
211  # do not want to increase for each entry, maybe each stock
212  shift_nb += 1
213  #shift_nb = 1 #ok with one stock
214  # append the new dictionary or list
215  out_str = pretty_dict( value, out_str, shift_nb )
216  shift_nb -= 1
217  # else simple value
218  else :
219 
220  #specific entry
221  if key == 'symbol':
222  out_str +='\n======= ' + value + '\n'
223  pass
224 
225  else :
226  out_str += shift_str + key +' : '
227  out_str += str(value)
228  out_str += '\n'
229 
230  # works if values are a list,
231  # need more test if elements are dictionary/an other List
232  elif type(dict) == types.ListType :
233 
234  # check type of the first element, only for list
235  if len(dict) > 0:
236  type_elem = type( dict[0] )
237  else:
238  #print "Empty dictionary in Utils.pretty_dict"
239  return out_str
240  #print "type_elem ", type_elem
241 
242  # case of list of dictionary, to add list of list ??
243  if type_elem == types.DictType :
244  #out_str += '\n'
245  #shift_nb += 1
246  for value in dict:
247  out_str = pretty_dict( value, out_str, shift_nb )
248  # simple value to print
249  else :
250  # need to loop
251  out_str += shift_str + ', '.join(str(x) for x in dict)
252  out_str += '\n'
253 
254  return out_str
255 
256 
257 
258 # Main for testing functions
259 if __name__ == "__main__":
260 
261  dict1 ={'key1' : 1,
262  'key2' : [2,"toto"], #"2" acepted with join, not 2
263  'key3' : 3 }
264 
265  dict2 = {'symbol': 'CAC40', 'InstValue ': {'volume': 898.0, 'plusbas': 4224.34, 'state': 'OPEN', 'ouverture': 4294.05, 'variation': -0.22, 'plushaut': 4311.0, 'time': '14:36:00', 'date': '2015-01-02', 'value': 4263.39}}
266  # from Fundamental, only 1 stock
267  dict3 = [{'symbol': '"GSZ.PA"', 'list_dict': ['Fundamental'], 'Fundamental': {'other': {}, 'MarketCapitalization': '45.753B', 'BVPS': 21.442, 'SharesOwned': '-', 'PriceBook': 0.9, 'PEG': 'N/A\r', 'DividendYield': 1.67, 'PER': 'N/A'}}]
268 
269  # from Fundamental, only 1 stock
270  dict4 = [{'symbol': '"GSZ.PA"', 'list_dict': ['Fundamental'], 'Fundamental': {'other': {}, 'MarketCapitalization': '45.753B', 'BVPS': 21.442, 'SharesOwned': '-', 'PriceBook': 0.9, 'PEG': 'N/A\r', 'DividendYield': 1.67, 'PER': 'N/A'}},{'symbol': '"GSZ2.PA"', 'list_dict': ['Fundamental'], 'Fundamental': {'other': {'subother':'toto', 'subother2':'toto2'}, 'MarketCapitalization': '45.753B', 'BVPS': 21.442, 'SharesOwned': '-', 'PriceBook': 0.9, 'PEG': 'N/A\r', 'DividendYield': 1.67, 'PER': 'N/A'}}]
271 
272  print "\n== dict 1"
273  print pretty_dict( dict1 )
274 
275  print "\n== dict 2"
276  print pretty_dict( dict2 )
277 
278  #pretty_dict_test( dict2 )
279  str_pretty = pretty_dict( dict4 )
280  print "\n nice formatting"
281  print str_pretty
Base class of the custom exceptions.
def pretty_dict
Nice string output of python dictionary or list of dictionaries.
Definition: Utils.py:190
def to_list
Always return a list of strings.
Definition: Utils.py:18
def string_to_timestamp
opposite all seems to be in local time, like the rest of the application (1970-01-01 00:00:00 = -3600...
Definition: Utils.py:86
Enumeration for the action to be performed by the parser.
Definition: GlobalDicts.py:82
Define custom and specific exceptions for the complete package.
def stringToEAction
Always return a valid EAction from an Eaction or an EAction.name.
Definition: Utils.py:40
def timestamp_to_string
Time function.
Definition: Utils.py:80