21 from serverportfolio
import Utils
51 def __init__(self, action, option_parser = None, opt_multithread = False):
63 self.
_logger = logging.getLogger(
'SP.UpdateStocks')
64 self._logger.debug(
'Init UpdateStocks')
65 self._logger.debug(
'action: %s', action)
68 self.
e_action = Utils.stringToEAction( action )
75 except ParserError
as ex:
76 print "Catch ParserError form ParserFactory ex.get_format_string()"
104 tmp = {
'to_save' : self.
b_save,
117 self._logger.debug(
"_set_parser")
119 self._logger.debug(
"status %s", status)
122 self.
e_action = Utils.stringToEAction( action_name )
133 return self._dictstocks.get_stocks(stock)
137 def print_dict_stocks(self, action, input_stocks = None, opt_all_stocks = False, opt_header = False ):
138 return self._dictstocks.print_dict_stocks( action, input_stocks, opt_all_stocks, opt_header)
158 self._logger.debug(
"_update_data stocks: %s" % (stock) )
159 self._logger.debug(
"action to perform: %s" % action )
160 self._logger.debug(
"self.e_action to perform: %s" % self.
e_action )
170 list_stock = Utils.to_list( stock )
174 if (action ==
None) & (self.
e_action != EAction.NoAction):
180 assert(self.
_myparser !=
None),
"Error in _update_data, the parser could not be created"
181 assert(self.
e_action != EAction.NoAction),
"Error in _update_data, the parser could not be created"
192 if (self.
e_action == EAction.InstValue) | (self.
e_action == EAction.HistPrice) | \
193 (self.
e_action == EAction.DivSplit) | (self.
e_action == EAction.DatesIntro):
202 self._logger.debug(
"multithread activated")
213 t = threading.Thread(target=run_thread_pool_parser, args=(list_stock, self.
e_action, option_post)).
start()
217 option_post[
'tk_manager'].update_me()
243 self._logger.debug(
"mutlithread done")
251 self._logger.debug(
"single thread, make a loop")
253 for stock
in list_stock :
256 self._myparser.run_parser( stock, option_post )
258 except ParserError
as ex:
259 self._logger.error(
"_update_data caught a ParserError from run_parser: %s" % ex)
263 except Exception
as ex:
264 self._logger.error(
"_update_data caught an Exception from run_parser : %s" % ex)
265 print "error message ",ex
278 elif (self.
e_action == EAction.Info) | (self.
e_action == EAction.Fundamental):
290 self._myparser.run_parser_info( list_stock, option_post )
293 self._myparser.run_parser( list_stock, option_post )
297 except ParserError
as ex:
298 self._logger.error(
"_update_data caught a ParserError from run_parser: %s" % ex)
302 except QueryError
as ex:
303 self._logger.error(
"_update_data caught a QueryError from run_parser: %s" % ex)
306 except Exception
as ex:
307 self._logger.error(
"_update_data caught an Exception from run_parser : %s" % ex)
363 self._logger.debug(
"Entry update_xml stock %s" % stock)
365 if not self.save_xml:
366 self._logger.debug(
"update_xml, but save_xml is False, return")
368 self._logger.debug(
"mode interactive %s" % self.
b_interactive)
370 list_stock = Utils.to_list( stock )
372 for stock_symb
in list_stock:
379 except PortfolioError
as ex:
380 self._logger.error(
"Caught PortfolioError")
387 if any(obj_stock._dict_interactive):
388 obj_stock.save_new_data_to_xml()
390 self._logger.debug(
"dict_interactive is empty, nothing to update")
393 print "Interactive to write"
407 def get_string_data( self, list_stock, action=None, opt_header=False, opt_parse=True ):
408 self._logger.debug(
"Entry get_string_data %s opt_parse: %s" % (self.
e_action, opt_parse))
415 lines = self.
print_dict_stocks( self.e_action.name, list_stock, opt_header = opt_header )
427 self._logger.debug(
"Entry check_open")
445 print "Entry thd_pool_run name", threading.current_thread().name
452 if option_post[
'interactive'] ==
True:
453 ref_tk_manager = option_post[
'tk_manager']
454 assert ref_tk_manager
is not None,
"Error in option post"
457 for stock
in list_stock:
458 t = threading.Thread(target=run_thread_parser, name=
"thread_"+stock, args = (stock, e_action, option_post))
459 thread_list.append(t)
461 for th
in thread_list: th.start()
463 for th
in thread_list: th.join()
466 print "thd_pool all joined, send quit signal"
467 ref_tk_manager.write([
"QUIT"])
468 print "thread_pool will die..."
476 logger = logging.getLogger(
'SP.UpdateStocks.thread_parser')
477 logger.debug(
"run_thread name %s" % threading.current_thread().name)
478 logger.debug(
"stock %s", stock)
479 logger.debug(
"e_action %s", e_action.name)
480 logger.debug(
"option_post %s" % option_post)
484 parser = ParserFactory.create_parser( e_action )
486 print "Got an exception "
491 parser.run_parser( stock, option_post )
493 except ParserError
as ex:
494 logger.error(
"run_thread_parser caught a ParserError from run_parser: %s" % ex)
498 except Exception
as ex:
499 logger.error(
"run_thread_parser caught an Exception from run_parser: %s" % ex)
514 EAction.Info:[
'YQL'],
515 EAction.HistPrice:[
'YCSV'],
516 EAction.DatesIntro:[
'YCSV'],
517 EAction.DivSplit:[
'YCSV'],
518 EAction.InstValue:[
'BOURSO'],
519 EAction.Fundamental:[
'YCSV',
'YQL']
536 cls._logger = logging.getLogger(
'SP.ParserFactory' )
537 cls._logger.debug(
"CreateParser e_action: %s, option: %s" % (e_action.name, option) )
539 if e_action == EAction.NoAction:
543 default_option = cls._ACTION[ e_action ]
544 cls._logger.debug(
"default_option %s " % default_option)
546 cls._logger.critical(
"Error action %s not in list ACTION or is invalid" % (e_action.name) )
547 raise ParserError(
"Cannot create a Parser from the action %s" % e_action.name, \
548 None, e_action.name,
None )
551 opt_parser = default_option[0]
557 if opt_parser ==
'BOURSO':
558 assert ( e_action == EAction.InstValue ),
"Error in combination Boursorama / %s" % ( e_action )
563 elif opt_parser ==
'YCSV':
568 elif opt_parser ==
'YQL':
573 cls.logger.debug(
"option parser not yet implemented %s" % opt_parser)
574 raise ParserError(
"option parser not yet implemented %s" % opt_parser, \
575 'None', e_action.name,
'None' )
588 cls._logger.debug(
'is_compatible')
589 cls._logger.debug(
'test current parser.source: %s', actual_parser.source)
590 print "is_compatible"
591 print "actual_parser.source ", actual_parser.source
595 if actual_parser ==
None:
599 if actual_parser.e_action.name == new_action_name:
601 print "Same action, return True"
610 new_action = EAction[new_action_name]
615 raise ParserError(
"Cannot create a Parser from the action %s" % new_action_name, \
616 None, new_action_name,
None )
626 if __name__ ==
"__main__":
631 logging.basicConfig(level=logging.DEBUG)
632 logging.getLogger(
'SP')
633 m_logger = logging.getLogger(
"SP.main")
637 m_stock = sys.argv[1]
638 m_action = sys.argv[2]
642 print " Only for debugging, should call ./Run_Parsers for all options "
644 print " UpdateStocks CAC40,FSLR InstValue"
645 print " Action: all actions, thread option"
647 m_logger.debug(
"Entry Main UpdateStocks")
651 m_update_stocks =
None
653 m_list_stock = m_stock.split(
',')
654 m_logger.debug(
"list_stock: %s", m_list_stock)
655 print "\n== Create UpdateStocks"
658 m_update_stocks =
UpdateStocks( m_action, opt_multithread=
True)
659 except PortfolioError
as ex:
660 print "Caught PortfolioError from UpdateStocks()"
661 print ex.get_format_string()
663 except Exception
as ex:
664 print "Caught Exception ex:",ex
666 print "action ", m_update_stocks.e_action.name
683 m_update_stocks.set_option_post(
True,
True )
685 m_lines = m_update_stocks.get_string_data( m_list_stock, m_action, opt_header=
True)
687 except PortfolioError
as ex:
688 print "Catch PortfolioError, ex: %s" % ex
689 print ex.get_format_string()
691 except Exception
as ex:
692 print "Catch Exception ex: %s" % ex
693 print "traceback:\n", traceback.format_exc(3)
695 m_logger.debug(
"\n==result")
def check_open
Parse instantaneous value and check the stock is in state 'OPEN'.
def get_stocks
Return a Stock (or a list of Stock) object(s) from a symbol (or a list of symbols).
Manage and serialize the access to a ValidationTkinter application, necessary when UpdateStock is run...
_dictstocks
Link to the DictionaryStocks singleton.
b_save
Indicates if the new data must be saved into the file system, post-processing stage.
def get_option_post
Return a new dictionary with the option for post-processing.
def run_thread_pool_parser
Create and run a pool of thread parsers.
def _set_parser
Set or reset an action, a correct parser depending on the action.
Helper functions, all the functions to create a specific parser from a given action.
Specific parser for querying the french Boursorama website.
def run_thread_parser
Create and run the parsing of one action for an unique stock.
def print_dict_stocks
Print one line strings of the data.
Specific parser using Yahoo YQL interface.
def create_parser
Return a specific parser, according to the action.
For graphical user validation before saving the data.
Define custom and specific exceptions for the complete package.
Define the class YahooCSV to use the 'old' Yahoo API.
Derived class specific to the parsers.
b_interactive
Set interactive mode, the user is required to accept / reject the update of data. ...
_multithread
Allow multi-threading for executing _update_data.
Container of all Stocks objects, it also reads the static stocks configuration file "dictstocks...
def _update_data
Update stock(s) data according to the specified action.
Global variables for configuration: paths, TCP ports and generic definitions.
Update data of a list of Stock's (only one action by call is possible).
def set_option_post
To set/unset the options b_save and b_interactive.
tuple start
liststocks=(list_stocks,list_stocks_open)
def get_string_data
Update the stock(s) and return the data as multi lines string.
Define singleton class DictionaryStocks, act as the main container of Stocks objects.
Specific parser for querying the Boursorama website, only for instantaneous data. ...
Derived parser class for retrieving divers data from the 'old' Yahoo API.