Esempio n. 1
0
def main():
    ticker = str(
        input(
            "Please enter the Stock ticker that you would like to analyze: "))
    totalChoices = 3

    print()
    print("What would you like to know about this stock?")
    print("(1) Get recent news")
    print("(2) Analyze Moving Average")
    print("(3) Compare correlation with another stock")
    print("(0) Exit")

    while (True):
        try:
            print()
            i = int(input("Please Enter your selection, or enter 0 to exit: "))
            if (i < 0 or i > totalChoices):
                print("ERROR: Please enter an integer value between 0-3")
            elif (i == 0):
                break
            elif (i == 1):
                news_scrape.scrape_news(ticker)
            elif (i == 2):
                moving_avg.move_avg(ticker)
            elif (i == 3):
                ticker2 = str(
                    input(
                        "Please enter the Stock ticker that you would like to compare: "
                    ))
                correlation.correlate(ticker, ticker2)

        except Exception as e:
            print("ERROR: Please enter an integer value between 0-3")
            continue
Esempio n. 2
0
    def test_correlation(self):
        self.v = 0
        dtime_t, cval = correlate(self.x, self.y, self.dt, self.v, 't')
        ndtime = int(round(dtime_t*1./self.dt))
        yy = np.zeros(len(self.y))
        yy[:ndtime] = self.y[-ndtime:]
        dtime_f = correlate(self.x, yy, self.dt, self.v, 'f')
        dtime = dtime_t+dtime_f

        self.assertAlmostEqual(dtime, self.expected_tau, 2)
Esempio n. 3
0
def perform2fa():
    if request.method == 'POST':
        f = request.files['file']
        print("Received the file ", f.filename)
        filePath = "./" + secure_filename(f.filename)
        f.save(filePath)
        if "audiorecordpc" in f.filename:
            send_request_to_mobile("send_file")
        else:
            return "File Received Successfully"

        while True:
            time.sleep(1)
            if path.exists("audiorecordmobile.mp4"):
                corr = correlate('audiorecordpc.mp4', 'audiorecordmobile.mp4')
                break
        print(
            "Removing the locally saved files audiorecordpc.mp4, audiorecordmobile.mp4"
        )
        os.remove("audiorecordpc.mp4")
        os.remove("audiorecordmobile.mp4")
        if (corr > 0.5):
            print(
                "correlation greater than threshold, so redirecting to homepage"
            )
            return redirect(url_for('home'))
        print(
            "correlation less than threshold, so returning the user back to login page"
        )
        return render_template('index.html',
                               msg="Two Factor Authentication Failed")
def validate(directory, results_file, crlation, seed):
    reader = ScoreReader()
    for file in [
            os.path.join(directory, file) for directory in directory
            for file in os.listdir(directory)
            if os.path.isfile(os.path.join(directory, file))
    ]:
        reader.read(file, None)

    results = {}
    with open(results_file) as f:
        for line in f:
            parts = line.strip().split()
            results[parts[0]] = float(parts[1])

    # Run cross-validation
    validator = CorrelationKFoldValidator(results,
                                          correlation=crlation,
                                          verbose=True)
    scored_test_items = validator.cross_validate(*reader.scored_items(),
                                                 seed=seed,
                                                 concatenate=False)

    # Output results
    #for item in scored_test_items[1]:
    #    print('{}\t{}'.format(item, str(scored_test_items[1][item])))

    cor = scipy.stats.pearsonr if correlation == 'pearson' else scipy.stats.kendalltau
    c, p = correlation.correlate(results, scored_test_items, cor, sig=True)
    return (c, p)
Esempio n. 5
0
    directories = [f for f in listdir(song_dir) if isdir(join(song_dir, f))]
    for dir in directories:
        songfolder = join(song_dir, dir)
        csv_filename = join(csv_dir, dir + '.csv')
        if exists(csv_filename): remove(csv_filename)
        csv_file = open(csv_filename, "w+", newline='')
        writer = csv.writer(csv_file, delimiter=';')
        writer.writerow(['ID', 'Pan'])

        wav_files = [(int(f[:-4]), join(songfolder, f))
                     for f in listdir(songfolder)]
        wav_files_dict = dict(wav_files)
        file1 = ''
        file2 = ''
        last_processed_index = 0
        for ind, file in enumerate(sorted(wav_files_dict)):
            file1 = file2
            file2 = wav_files_dict[file]
            max_corr, max_corr_offset = 0, 0
            if file1 and file2:
                max_corr, max_corr_offset = correlate(file1, file2)
            if max_corr > 0.62 and max_corr_offset == 0:
                writer.writerow([str(ind - 1), 'L'])
                writer.writerow([str(ind), 'R'])
                last_processed_index = ind
            elif last_processed_index < (ind - 1) or ind == 1:
                writer.writerow([str(ind - 1), 'M'])
                last_processed_index = ind - 1
        print("finished " + dir + "\n")
        csv_file.close()
Esempio n. 6
0
import argparse
from correlation import correlate
from tkinter.filedialog import askdirectory


def initialize(song, song2):

    SOURCE_FILE = song
    TARGET_FILE = song2
    if not SOURCE_FILE or not TARGET_FILE:
        raise Exception("Source or Target files not specified.")
    return SOURCE_FILE, TARGET_FILE


if __name__ == "__main__":
    SOURCE_FILE, TARGET_FILE = initialize()
    correlate(SOURCE_FILE, TARGET_FILE)
Esempio n. 7
0
 def test_auto_corr_fr(self):
     self.v = 0
     dtime = correlate(self.x, self.x, self.dt, self.v, 'f')
     self.assertEqual(dtime, 0)
Esempio n. 8
0
 def test_auto_corr_time(self):
     self.v = 0
     dtime, cval = correlate(self.x, self.x, self.dt, self.v, 't')
     self.assertAlmostEqual(cval, 1)
     self.assertAlmostEqual(dtime, 0)
Esempio n. 9
0
def main(thresh, theta, mid, line, start, path):

    #start = 0: all 1:after create template 2:after correlation 3: after graph 4: just plot

    # # read input files
    set_status(Messages.START_RUN)
    target_path = path
    #
    set_status(Messages.START_CYL)
    cylinder_creation(target_path)
    set_status(Messages.END_CYL)

    ideal_cyl = dir_path + "/source/Cylinder.mrc"
    if not os.path.exists(dir_path + "/correlation"):
        os.makedirs(dir_path + "/correlation")
    if not os.path.exists(dir_path + "/Templates"):
        os.makedirs(dir_path + "/Templates")
    try:
        target_map = MapParser.readMRC(target_path)
        cylinder_map = MapParser.readMRC(ideal_cyl)
        apix = target_map.apix

    # except Exception as e:
    #     print e
    except:
       print Messages.INPUT_FILES_ERROR

    if start < 1 or not (len(os.listdir(dir_path + "/Templates")) >= 144):
        # generate templates
        dic_directions = run_templates(target_map, cylinder_map, overwrite=True)
    else:
        try:
            with open(dir_path + "/correlation/dir_directions.p") as g:
                dic_directions = pickle.load(g)
        except IOError:
            if start > 0:
                set_status(Messages.BUMPED_BACK)
                return main(thresh, theta, mid, line, start-1, path)





    if start < 2 or (not (os.path.isfile(dir_path + "/correlation" + "/max_score"))):
        try:
            # compute correlation
            set_status(Messages.START_CORRELATION)
            max_score, max_dirs = correlate(target_map)
            set_status(Messages.DONE_CORRELATION)
        except IOError:
            if start > 0:
                set_status(Messages.BUMPED_BACK)
                return main(thresh, theta, mid, line, start-1, path)
    if start < 3:
        graph = run_graph(theta, apix, THRESHOLD=thresh)
    else:
        try:
            with open(dir_path + "/source/graph.p", 'rb') as g:
                graph = pickle.load(g)
        except IOError:
            graph = run_graph(theta,apix, THRESHOLD=thresh)
            if graph == None:
                if start > 0:
                    set_status(Messages.BUMPED_BACK)
                    return main(thresh, theta, mid, line, start - 1, path)
                else:
                    return
    if start < 4:
        graph2 = run_linkage(theta, mid, line, apix)
    else:
        try:
            with open(dir_path + "/source/graph2.p", 'rb') as g:
                graph2 = pickle.load(g)
        except IOError:
            graph2 = run_linkage(theta, mid, line, apix)
            if graph2 == None:
                if start > 0:
                    set_status(Messages.BUMPED_BACK)
                    return main(thresh, theta, mid, line, start - 1, path)
                else:
                    return

    output = pruning(graph2, cylinder_map.box_size())
    set_status(Messages.END_RUN)

    plot_matrix(graph2, target_map.box_size())