Beispiel #1
0
    def write_file(self, path, stop_on_write):
        if self.read_only:
            return(None)

        header_row = []
        for column in self.column_map.columns:
            header_row.append(column.name)
        output_csv_list = [header_row]
        for row in self.data:
            output_csv_list.append(row)

        file_open_success = False
        while file_open_success != True:
            try:
                with open(path, "w", newline = "") as f:
                    writer = csv.writer(f)
                    writer.writerows(output_csv_list)
                print("Wrote to %s" % path)
                file_open_success = True

            except PermissionError:
                try_again_selection = zr_io.yes_no("Unable to write to file. Might be open. Try again?")
                if try_again_selection == False:
                    print("Write aborted")
                    return(None)

        if stop_on_write:
            zr_io.message("Verify accuracy of file and run again. This is not an error.")
Beispiel #2
0
def archive_ledger():
    source_path = ReadLedger.get_ledger_path()
    if not os.path.isfile(source_path):
        source_path = ReadLedger.get_ledger_path(prior=True)
        if not os.path.isfile(source_path):
            return (False)
    archive_dir = Config.get_path("ledger_archive_dir")
    destination_name = os.path.split(source_path)[1]
    destination_name = os.path.splitext(destination_name)[
        0] + "-" + datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + ".xlsx"
    destination_path = os.path.join(archive_dir, destination_name)

    #purge old ledgers
    archive_months = Config.get_ledger("archive_months")
    earliest_date = (datetime.now().date() -
                     relativedelta(months=archive_months))
    earliest_ledger = earliest_date.strftime("%Y-%m")
    for i in os.listdir(archive_dir):
        if i[0:7] < earliest_ledger:
            print("Removing archive %s from %s" % (i, archive_dir))
            os.remove(os.path.join(archive_dir, i))

    moved = False
    while not moved:
        try:
            shutil.move(source_path, destination_path)
            moved = True
        except PermissionError:
            if not Io.yes_no(
                    "Failed to archive existing ledger. It might be open. Try again?"
            ):
                Io.error("Aborting.")

    return (destination_path)
Beispiel #3
0
def set_new_info(symbol, element, csv_file):
    print("Uknown %s for %s." % (element, symbol))

    security_categories = csv_file.find_unique_by_column(element)
    security_categories.remove("Unknown")
    security_categories.sort()
    count = 0
    selection_string = ""
    for i in security_categories:
        selection_string += "[%s] %s\t" % (str(count), i)
        count += 1
        if count % 3 == 0:
            selection_string += "\n"
    selection_string = selection_string.rstrip("\n") + ("\n[%s] Enter new %s" %
                                                        (str(count), element))

    accepted = False
    while accepted != True:
        print("\nSelect %s\n" % element)
        print(selection_string)
        selection = input("\n> ")
        try:
            selection = int(selection)
            if selection == len(security_categories):
                new_cat = input("\nEnter new category: ")
            else:
                new_cat = security_categories[selection]
            accepted = Io.yes_no("Set %s for %s to %s?" %
                                 (element, symbol, new_cat))
        except:
            print("\nInvalid selection")

    return (new_cat)
Beispiel #4
0
def save_workbook(xl_workbook, xl_wb_path):
    #close and write the workbook
    while True:
        try:
            xl_workbook.close()
            print("\nWorkbook written to %s" % xl_wb_path)
            break
        except:
            if not zr_io.yes_no("Couldn't write Excel file %s. Close it if it's open. Try writing again?" % xl_wb_path):
                break
    return(0)
Beispiel #5
0
def verify_manual_beta(symbol):
    #manual beta entry
    columns = [
        Csv.CsvColumn(name="Symbol", is_row_identifier=True),
        Csv.CsvColumn(name="Beta", data_type="float")
    ]
    default_rows = []
    manual_beta_csv = Csv.CsvFile(Config.get_beta("manual_averages"),
                                  default_column_list=columns,
                                  default_data_rows=default_rows,
                                  read_only=True)
    custom_beta_symbols = manual_beta_csv.find_unique_by_column("Symbol")
    if not symbol in custom_beta_symbols:
        if Io.yes_no("Set custom beta for %s?" % symbol):
            opt = "x"
            custom_beta = opt
            while custom_beta == "x":
                opt = input("Enter custom beta as a whole number or decimal: ")
                try:
                    opt = float(opt)
                    if Io.yes_no("Set beta for %s to %s?" %
                                 (symbol, str(opt))):
                        custom_beta = opt
                except:
                    pass
        else:
            custom_beta = -9001
        custom_beta = str(custom_beta)

        default_rows = [[symbol, custom_beta]]

        manual_beta_csv = Csv.CsvFile(Config.get_beta("manual_averages"),
                                      default_column_list=columns,
                                      default_data_rows=default_rows,
                                      stop_on_write=False,
                                      read_only=False)
    return (0)
Beispiel #6
0
def symbol_lookup():
    while True:
        if not Io.yes_no("Run Beta lookup?"):
            return (0)
        symbol = input("Enter symbol: ").upper()
        position = Instruments.StockPosition(symbol, 0, quickrun=True)
        if Db.sync_history([position], "stock_shares") == 0:
            load_portfolio_betas([position])
            beta_sum = 0.00
            if len(position.betas) != 0:
                for b in position.betas[::-1]:
                    print("%s Month Beta (Monthly): %s" %
                          (str(b.months), str(b.beta)))
                    beta_sum += b.beta
                print("Average Monthly Beta: %s" %
                      (str(beta_sum / len(position.betas))))
            else:
                print("Not enough history to calculate beta.")
Beispiel #7
0
def purge(cursor):
    tables_to_keep = ["zmaintenance", "start_dates"]
    #see if old data needs purged
    today = datetime.now()
    today = today.strftime("%Y-%m-%d")
    tables = cursor.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
    maintenance_table_exists = False
    for table in tables:
        if table[0] == "zmaintenance":
            maintenance_table_exists = True
    purged = False
    if not maintenance_table_exists:
        purged = True
        cursor.execute("CREATE TABLE 'zmaintenance' (zid TEXT PRIMARY KEY, zvalue TEXT);")
    else:
        last_purge = cursor.execute("SELECT zvalue FROM 'zmaintenance' WHERE zid='last_purge';").fetchall()
        time_since = None
        if len(last_purge) == 0:
            time_since = "Infinity"
        else:
            last_purge = datetime.strptime(last_purge[0][0], "%Y-%m-%d")
            time_since = int((datetime.now() - last_purge).days)
            if time_since < int(Config.get_sqlite("history_rebuild_days")):
                time_since = None
        if time_since:
            if Io.yes_no("It has been %s days since your last purge. Purge now?" % str(time_since)):
                purged = True
                for table in tables:
                    table = table[0]
                    if table not in tables_to_keep:
                        cursor.execute("DROP TABLE '%s';" % table)

    if purged == True:
        print("Inserting purge date: %s" % today)
        cursor.execute("INSERT OR REPLACE INTO zmaintenance(zid, zvalue) VALUES ('last_purge', '%s');" % today)
    return(None)
Beispiel #8
0
def get_api_key():
    api_key = Config.get_api_key("iexcloud")
    if not is_prod(api_key):
        if not (Io.yes_no("Continue with sandbox iexcloud key?")):
            Io.message("Aborting.")
    return (api_key)