8 from __future__
import with_statement
10 import logging, types, math
11 import datetime, time, threading
13 from serverportfolio
import Utils
32 def __init__(self, parent_stock, tk_manager=None):
33 self.
_logger = logging.getLogger(
'SP.ValidUpdateStock')
34 self._logger.debug(
'Init ValidUpdateStock')
35 self._logger.debug(
'parent symbol: %s', parent_stock.symbol)
36 self._logger.debug(
'tk_manager: %s' % tk_manager)
56 self._logger.debug(
"post_process_one_action %s", e_action.name)
57 interactive = option_post[
'interactive']
58 to_save = option_post[
'to_save']
66 self._logger.debug(
"== check new data")
68 except PortfolioError
as ex:
69 self._logger.error(
"Caught PortfolioError in check_new_data")
70 self._logger.error(
"ex: %s" % ex.get_format_string())
73 if interactive ==
True:
74 self._logger.debug(
"Interactive True")
75 self._logger.debug(
"beforeGUI")
78 except Exception
as ex:
79 self._logger.error(
"Caught Exception from ValidationTkinter ex: %s" % ex )
89 self._logger.info(
"dict_interactive is empty, nothing to update")
91 self._logger.debug(
"Save flag not set")
97 self._logger.debug(
"check_new_data e_action %s" % e_action)
98 self._logger.debug(
"interactive %s", interactive)
99 dict_inter_action =
None
101 if self.
get_parent().saved_as(e_action.name,
'xml'):
110 except PortfolioError
as ex:
111 self._logger.error(
"Caught PortfolioError in check_new_data")
113 except Exception
as ex:
114 self._logger.error(
"Caught Exception in check_new_data: %s" % ex)
117 if self.
get_parent().saved_as(e_action.name,
'csv'):
121 except PortfolioError
as ex:
122 self._logger.error(
"Caught PortfolioError in check_new_data")
124 except Exception
as ex:
125 self._logger.error(
"Caught Exception in check_new_data: %s" % ex)
129 if any(dict_inter_action):
135 self._logger.debug(
"save_new_data e_action.name %s" % e_action.name)
137 if self.
get_parent().saved_as(e_action.name,
'xml'):
140 except Exception
as ex:
141 self._logger.info(
"Caught Exception ex:%s" % ex)
144 if self.
get_parent().saved_as(e_action.name,
'csv'):
145 print "Deal with CSV"
146 if e_action == EAction.HistPrice:
157 self._logger.debug(
"valid_interactive, tk_manager %s" % self.
_tk_manager)
170 except Exception
as ex:
171 self._logger.error(
"Caught exception from ValidationTkinter/ ex:")
187 self._logger.debug(
"opt_interactive %s", opt_interactive)
188 dict_interactive = {}
191 self._logger.debug(
"_dict_stock: %s", self._dict_stock)
196 for key,value
in self.get_action().iteritems() :
197 self._logger.debug(
"key/value %s %s" % (key, value))
199 if self.saved_as( key,
'xml' ):
203 if any(dict_action_inter):
204 dict_interactive[ key ] = dict_action_inter
208 self._logger.debug(
"\nFinal dict_interactive:\n%s" % dict_interactive)
209 print Utils.pretty_dict( dict_interactive )
216 self._logger.debug(
"Entry save_new_xml_data")
218 for (key_action, value_action)
in self._dict_interactive.iteritems():
219 self._logger.debug(
"key_action/value_action %s / %s" % (key_action, value_action))
221 dict_xml = self.
get_parent().get_dict_xml( key_action )
224 for (key_data, value_data)
in value_action.iteritems():
225 self._logger.debug(
"\nkey_data / value_data %s / %s" % (key_data, value_data))
227 if value_data[
'repl_add'] > 0:
228 self._logger.info(
"update xml value / key_data : %s / %s / %s " % \
229 (self.
get_parent().symbol, key_data, value_data[
'new_value']) )
231 if dict_xml[
'template'][key_data][-1][
'attrib'][
'append'] ==
True:
234 new_tmpl_value = StTmpl.get_template_one_value_xml()
235 new_tmpl_value[
'value'] = value_data[
'new_value']
236 new_tmpl_value[
'attrib'][
'date'] = value_data[
'date']
237 new_tmpl_value[
'attrib'][
'source'] = value_data[
'source']
238 new_tmpl_value[
'attrib'][
'append'] =
'True'
240 dict_xml[
'template'][ key_data ].append( new_tmpl_value )
243 dict_xml[
'template'][ key_data ][-1][
'value'] = value_data[
'new_value']
245 dict_xml[
'template'][ key_data ][-1][
'attrib'][
'date'] = value_data[
'date']
246 dict_xml[
'template'][ key_data ][-1][
'attrib'][
'source'] = value_data[
'source']
249 self._logger.debug(
"dict_xml before wirte_xml:\n%s " % Utils.pretty_dict(self.
get_parent().get_dict_xml()) )
250 self._logger.debug(
"dict_xml before wirte_xml:\n%s " % (self.
get_parent().get_dict_xml()) )
253 except Exception
as ex:
254 self._logger.info(
"Caught Exception ex:%s" % ex)
265 self._logger.debug(
"Entry _valid_new_xml_value, key_action %s", key_action)
266 self._logger.debug(
"interactive %s", interactive)
268 self._logger.debug(
"new_data / _dict_stock action %s", self.
get_parent().get_action( key_action ))
270 self._logger.debug(
"xml_data / _dict_xml %s", self.
get_parent().get_dict_xml( key_action ))
272 new_data = self.
get_parent().get_action( key_action )
273 assert ( new_data !=
None ),
"New_data should not be None at this stage"
276 assert 'source' in new_data,
"source is missing"
277 new_data_source = new_data[
'source']
281 xml_data = self.
get_parent().get_dict_xml( key_action )
288 dict_inter_action = {}
292 for key_data
in new_data.keys():
294 if (key_data ==
'other') | (key_data ==
'error') | (key_data ==
'source'):
297 new_value = new_data[key_data]
301 xml_value = xml_data[
'template'][key_data][-1][
'value']
304 self._logger.error(
"key_data %s not found in xml_value" % key_data)
308 if ( key_action ==
"Fundamental"):
309 type_values = types.FloatType
310 elif ( key_action ==
'Info'):
311 type_values = types.StringType
313 self._logger.error(
"action not implemented in list_update_xml_value_generic")
314 type_values = types.StringType
317 status = ValidStockUpdate.check_value( new_value, xml_value, type_values )
319 except Exception
as ex:
320 self._logger.info(
"Exception check_value: new_value %s, xml_value %s, status %d" % (new_value, xml_value, status))
321 self._logger.info(
"ex: %s" % ex)
323 self._logger.debug(
"new_value %s, xml_value %s, status %d" % (new_value, xml_value, status))
327 if ( status <= 0 ) | ( ( status==1) & (
not interactive) ):
328 self._logger.debug(
"Discard this data")
334 elif (status == 2 ) | (( status == 1) & interactive) :
338 tmpl_new_value = StTmpl.get_template_valid_xml_value()
340 tmpl_new_value[
'new_value'] = new_value
342 tmpl_new_value[
'xml_value'] = xml_value
344 tmpl_new_value[
'date'] = datetime.datetime.now().strftime(
"%Y-%m-%d")
346 tmpl_new_value[
'repl_add'] = status
348 tmpl_new_value[
'source'] = new_data_source
350 dict_inter_action[ key_data ] = tmpl_new_value
351 self._logger.debug(
"dict_inter_action %s: %s" % (key_action,dict_inter_action))
352 return dict_inter_action
375 self._logger.debug(
"check_list_csv interactive %s", opt_interactive)
377 dict_interactive = {}
381 for key_action,value
in self.get_action().iteritems() :
384 if key_action !=
'HistPrice':
391 if len(dict_action_inter):
392 dict_interactive[ key_action ] = dict_action_inter
394 self._logger.debug(
"\nFinal dict_interactive:\n%s" % dict_interactive)
414 self._logger.debug(
"action %s", key_action)
416 self._logger.debug(
"Entry _valid_new_value_csv: %s", self.
get_parent().symbol)
417 self._logger.debug(
"interactive %s", interactive)
419 self._logger.debug(
"new_data / _dict_parser %s", self.
get_parent().get_action( key_action ))
421 new_data = self.
get_parent().get_action( key_action )
422 assert ( new_data !=
None ),
"New_data should not be None at this stage"
424 dict_inter_action = {}
427 for key_data
in new_data.keys():
430 if key_data !=
'list_csv':
434 first_date = Utils.timestamp_to_string(new_data[key_data][0][0])
435 first_values = new_data[key_data][0]
437 first_status, first_error = ValidStockUpdate._error_list_csv(new_data[key_data][0], interactive)
442 for values
in new_data[key_data][1:]:
446 status, error = ValidStockUpdate._error_list_csv(values, interactive)
447 if (status != first_status) | ( count_values == ( len(new_data[key_data])-1) ) :
449 dict_inter_action[count_group] = {
450 'repl_add' : first_status,
451 'error' : first_error,
452 'first_date': first_date,
453 'first_values' : first_values,
455 'last_date': Utils.timestamp_to_string( new_data[key_data][count_values-1][0] ),
456 'last_values' : new_data[key_data][count_values-1]
459 if count_values == len(new_data[key_data]) :
460 dict_inter_action[count_group][
'last_date'] = Utils.timestamp_to_string(values[0])
461 dict_inter_action[count_group][
'last_values'] = values
466 first_status = status
468 first_date = Utils.timestamp_to_string( values[0] )
469 first_values = values
470 self._logger.debug(
"dict_inter_action %s: %s" % (key_action,dict_inter_action))
471 return dict_inter_action
487 if values[1] == values[2] == values[3] == values[4]:
488 error =
'values equal'
489 if float(values[5]) == 0:
490 error =
'volume missing'
493 return (status, error)
519 self._logger.debug(
"entry gen_part_list_csv, last_date %s " % (last_date) )
520 assert 'list_csv' in self.get_action(
'HistPrice'),
'list_csv not loaded !'
522 if last_date ==
None:
523 last_date =
yield None
525 p_list = self.get_action(
'HistPrice',
'list_csv')
530 if p_list[i][0] <= last_date:
531 part_list.append(p_list[i])
534 last_date =
yield part_list
536 part_list = [ p_list[i] ]
564 new_value = type_value(new_value)
565 status = ValidStockUpdate.is_valid_value( new_value, type_value )
567 except (ValueError,TypeError):
571 except Exception
as ex:
573 print "Got exception ex: %s", ex
581 if xml_value ==
None:
583 xml_value = type_value()
585 if (new_value ==
None) | (new_value == type_value()):
586 print "\n ValidStockUpdate, case xml_value is None and new_value is also the default\n"
592 xml_value = type_value(xml_value)
593 except Exception
as ex:
598 if new_value == xml_value:
601 if new_value == type_value():
602 print "\n ValidStockUpdate, case new_value is default\n"
622 if type_value == types.FloatType:
623 if math.isnan( value ):
628 elif type_value == types.StringType:
_dict_interactive
Dictionary of data after check_new_data.
def gen_part_of_list_csv
Generate a sub-list of list_csv, starting from the last call until the last_date (included) ...
def _valid_new_value_csv
Fill dict_interactive in case of list of data (HistPrice action implemented) dict_inter_action stores...
def check_list_csv
Check the CSV data are not wrong.
def save_new_xml_data
Final merge (after user/auto validation) and write XML file.
def valid_interactive
User validation of the new data.
def _error_list_csv
Check for common error in historical price data and return a status and an error code.
def check_new_xml_data
Check the validity of the new retrieved data stored Stock._dict_stock.
Define the global variable StockTemplates.StTmpl and dictionary templates.
def is_valid_value
Guess if the input value is valid.
For graphical user validation before saving the data.
Define custom and specific exceptions for the complete package.
Extend class Stock with functions related to the validation and saving after a stock update: most of ...
def check_new_data
Check the validity of the last updated values from Stock.dict_stock and generate dict_interactive.
def post_process_one_action
Assure the post_processing of a Stock after the parsing of one unique action.
_tk_manager
Store a ManagerTk interface in multi-thread mode.
_parent_stock
Associated to an unique stock.
Global variables for configuration: paths, TCP ports and generic definitions.
def save_new_data
Final merge (after user/auto-validation) and write to file.
GUI interface to validate the update and saving of data.
def check_value
Generic function to check if new_value can be updated.
def get_parent
Return the parent Stock.
def _valid_new_value_xml
Valid last values retrieved with parsers, try to guess values to be updated.