markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Transforming and Creating Columns
df.assign(bmi=df['weight'] / (df['height']/100)**2) df['bmi'] = df['weight'] / (df['height']/100)**2 df df['something'] = [2,2,None,None,3] df
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Sorting Data Frames Sort on indexes
df.sort_index(axis=1) df.sort_index(axis=0, ascending=False)
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Sort on values
df.sort_values(by=['something', 'bmi'], ascending=[True, False])
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Summarizing Apply an aggregation function
df.select_dtypes(include=np.number) df.select_dtypes(include=np.number).agg(np.sum) df.agg(['count', np.sum, np.mean])
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Split-Apply-CombineWe often want to perform subgroup analysis (conditioning by some discrete or categorical variable). This is done with `groupby` followed by an aggregate function. Conceptually, we split the data frame into separate groups, apply the aggregate function to each group separately, then combine the aggre...
df['treatment'] = list('ababa') df grouped = df.groupby('treatment') grouped.get_group('a') grouped.mean()
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Using `agg` with `groupby`
grouped.agg('mean') grouped.agg(['mean', 'std']) grouped.agg({'weight': ['mean', 'std'], 'height': ['min', 'max'], 'bmi': lambda x: (x**2).sum()})
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Using `trasnform` wtih `groupby`
g_mean = grouped['weight', 'height'].transform(np.mean) g_mean g_std = grouped['weight', 'height'].transform(np.std) g_std (df[['weight', 'height']] - g_mean)/g_std
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Combining Data Frames
df df1 = df.iloc[3:].copy() df1.drop('something', axis=1, inplace=True) df1
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Adding rowsNote that `pandas` aligns by column indexes automatically.
df.append(df1, sort=False) pd.concat([df, df1], sort=False)
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Adding columns
df.pid df2 = pd.DataFrame(OrderedDict(pid=[649, 533, 400, 600], age=[23,34,45,56])) df2.pid df.pid = df.pid.astype('int') pd.merge(df, df2, on='pid', how='inner') pd.merge(df, df2, on='pid', how='left') pd.merge(df, df2, on='pid', how='right') pd.merge(df, df2, on='pid', how='outer')
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Merging on the index
df1 = pd.DataFrame(dict(x=[1,2,3]), index=list('abc')) df2 = pd.DataFrame(dict(y=[4,5,6]), index=list('abc')) df3 = pd.DataFrame(dict(z=[7,8,9]), index=list('abc')) df1 df2 df3 df1.join([df2, df3])
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Fixing common DataFrame issues Multiple variables in a column
df = pd.DataFrame(dict(pid_treat = ['A-1', 'B-2', 'C-1', 'D-2'])) df df.pid_treat.str.split('-') df.pid_treat.str.split('-').apply(pd.Series, index=['pid', 'treat'])
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Multiple values in a cell
df = pd.DataFrame(dict(pid=['a', 'b', 'c'], vals = [(1,2,3), (4,5,6), (7,8,9)])) df df[['t1', 't2', 't3']] = df.vals.apply(pd.Series) df df.drop('vals', axis=1, inplace=True) pd.melt(df, id_vars='pid', value_name='vals').drop('variable', axis=1)
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Reshaping Data FramesSometimes we need to make rows into columns or vice versa. Converting multiple columns into a single columnThis is often useful if you need to condition on some variable.
url = 'https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv' iris = pd.read_csv(url) iris.head() iris.shape df_iris = pd.melt(iris, id_vars='species') df_iris.sample(10)
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Chaining commandsSometimes you see this functional style of method chaining that avoids the need for temporary intermediate variables.
( iris. sample(frac=0.2). filter(regex='s.*'). assign(both=iris.sepal_length + iris.sepal_length). groupby('species').agg(['mean', 'sum']). pipe(lambda x: np.around(x, 1)) )
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Moving between R and Python in Jupyter
%load_ext rpy2.ipython import warnings warnings.simplefilter('ignore', FutureWarning) iris = %R iris iris.head() iris_py = iris.copy() iris_py.Species = iris_py.Species.str.upper() %%R -i iris_py -o iris_r iris_r <- iris_py[1:3,] iris_r
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
SLU13: Bias-Variance trade-off & Model Selection -- Examples--- 1. Model evaluation* a. [Train-test split](traintest)* b. [Train-val-test split](val)* c. [Cross validation](crossval) 2. [Learning curves](learningcurves) 1. Model evaluation
import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import learning_curve %matplotlib inline # Create the DataFrame with the data df = pd.read_csv("data/beer.csv") # Cre...
Number of entries: 1000
MIT
S01 - Bootcamp and Binary Classification/SLU13 - Bias-Variance tradeoff & Model Selection /Examples notebook.ipynb
FarhadManiCodes/batch5-students
[Return to top](top) Create a training and a test set
from sklearn.model_selection import train_test_split # Using 20 % of the data as test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) print("Number of training entries: ", X_train.shape[0]) print("Number of test entries: ", X_test.shape[0])
Number of training entries: 800 Number of test entries: 200
MIT
S01 - Bootcamp and Binary Classification/SLU13 - Bias-Variance tradeoff & Model Selection /Examples notebook.ipynb
FarhadManiCodes/batch5-students
[Return to top](top) Create a training, test and validation set
# Using 20 % as test set and 20 % as validation set X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4) X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.50) print("Number of training entries: ", X_train.shape[0]) print("Number of validation entries: ", X_val.shape[0]) pri...
Number of training entries: 600 Number of validation entries: 200 Number of test entries: 200
MIT
S01 - Bootcamp and Binary Classification/SLU13 - Bias-Variance tradeoff & Model Selection /Examples notebook.ipynb
FarhadManiCodes/batch5-students
[Return to top](top) Use cross-validation (using a given classifier)
from sklearn.model_selection import cross_val_score knn = KNeighborsClassifier(n_neighbors=5) # Use cv to specify the number of folds scores = cross_val_score(knn, X, y, cv=5) print(f"Mean of scores: {scores.mean():.3f}") print(f"Variance of scores: {scores.var():.3f}")
Mean of scores: 0.916 Variance of scores: 0.000
MIT
S01 - Bootcamp and Binary Classification/SLU13 - Bias-Variance tradeoff & Model Selection /Examples notebook.ipynb
FarhadManiCodes/batch5-students
[Return to top](top) 2. Learning Curves Here is the function that is taken from the sklearn page on learning curves:
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): """ Generate a simple plot of the test and training learning curve. Parameters ---------- estimator : object type that implements the "fit" and "predict" metho...
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU13 - Bias-Variance tradeoff & Model Selection /Examples notebook.ipynb
FarhadManiCodes/batch5-students
And remember the internals of what this function is actually doing by knowing how to use theoutput of the scikit [learning_curve](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.learning_curve.html) function
# here's where the magic happens! The learning curve function is going # to take your classifier and your training data and subset the data train_sizes, train_scores, test_scores = learning_curve(clf, X, y) # 5 different training set sizes have been selected # with the smallest being 59 and the largest being 594 # the...
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU13 - Bias-Variance tradeoff & Model Selection /Examples notebook.ipynb
FarhadManiCodes/batch5-students
Phi_K advanced tutorialThis notebook guides you through the more advanced functionality of the phik package. This notebook will not cover all the underlying theory, but will just attempt to give an overview of all the options that are available. For a theoretical description the user is referred to our paper.The packa...
%%capture # install phik (if not installed yet) import sys !"{sys.executable}" -m pip install phik # import standard packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import itertools import phik from phik import resources from phik.binning import bin_data from phik.decorators import * ...
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Load dataA simulated dataset is part of the phik-package. The dataset concerns car insurance data. Load the dataset here:
data = pd.read_csv( resources.fixture('fake_insurance_data.csv.gz') ) data.head()
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Specify bin typesThe phik-package offers a way to calculate correlations between variables of mixed types. Variable types can be inferred automatically although we recommend to variable types to be specified by the user. Because interval type variables need to be binned in order to calculate phik and the significance,...
data_types = {'severity': 'interval', 'driver_age':'interval', 'satisfaction':'ordinal', 'mileage':'interval', 'car_size':'ordinal', 'car_use':'ordinal', 'car_color':'categorical', 'area':'categorical'} interval_cols = [col for ...
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Phik correlation matrixNow let's start calculating the correlation phik between pairs of variables. Note that the original dataset is used as input, the binning of interval variables is done automatically.
phik_overview = data.phik_matrix(interval_cols=interval_cols) phik_overview
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Specify binning per interval variableBinning can be set per interval variable individually. One can set the number of bins, or specify a list of bin edges. Note that the measured phik correlation is dependent on the chosen binning. The default binning is uniform between the min and max values of the interval variable.
bins = {'mileage':5, 'driver_age':[18,25,35,45,55,65,125]} phik_overview = data.phik_matrix(interval_cols=interval_cols, bins=bins) phik_overview
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Do not apply noise correctionFor low statistics samples often a correlation larger than zero is measured when no correlation is actually present in the true underlying distribution. This is not only the case for phik, but also for the pearson correlation and Cramer's phi (see figure 4 in XX ). In the phik calculation...
phik_overview = data.phik_matrix(interval_cols=interval_cols, noise_correction=False) phik_overview
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Using a different expectation histogramBy default phik compares the 2d distribution of two (binned) variables with the distribution that assumes no dependency between them. One can also change the expected distribution though. Phi_K is calculated in the same way, but using the other expectation distribution.
from phik.binning import auto_bin_data from phik.phik import phik_observed_vs_expected_from_rebinned_df, phik_from_hist2d from phik.statistics import get_dependent_frequency_estimates # get observed 2d histogram of two variables cols = ["mileage", "car_size"] icols = ["mileage"] observed = data[cols].hist2d(interval_co...
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Statistical significance of the correlationWhen assessing correlations it is good practise to evaluate both the correlation and the significance of the correlation: a large correlation may be statistically insignificant, and vice versa a small correlation may be very significant. For instance, scipy.stats.pearsonr ret...
significance_overview = data.significance_matrix(interval_cols=interval_cols) significance_overview
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Specify binning per interval variableBinning can be set per interval variable individually. One can set the number of bins, or specify a list of bin edges. Note that the measure phik correlation is dependent on the chosen binning.
bins = {'mileage':5, 'driver_age':[18,25,35,45,55,65,125]} significance_overview = data.significance_matrix(interval_cols=interval_cols, bins=bins) significance_overview
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Specify significance methodThe recommended method to calculate the significance of the correlation is a hybrid approach, which uses the G-test statistic. The number of degrees of freedom and an analytical, empirical description of the $\chi^2$ distribution are sed, based on Monte Carlo simulations. This method works w...
significance_overview = data.significance_matrix(interval_cols=interval_cols, significance_method='asymptotic') significance_overview
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Simulation methodThe chi2 of a contingency table is measured using a comparison of the expected frequencies with the true frequencies in a contingency table. The expected frequencies can be simulated in a variety of ways. The following methods are implemented: - multinominal: Only the total number of records is fixed....
# --- Warning, can be slow # turned off here by default for unit testing purposes #significance_overview = data.significance_matrix(interval_cols=interval_cols, simulation_method='hypergeometric') #significance_overview
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Expected frequencies
from phik.simulation import sim_2d_data_patefield, sim_2d_product_multinominal, sim_2d_data inputdata = data[['driver_age', 'area']].hist2d(interval_cols=['driver_age']) inputdata
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Multinominal
simdata = sim_2d_data(inputdata.values) print('data total:', inputdata.sum().sum()) print('sim total:', simdata.sum().sum()) print('data row totals:', inputdata.sum(axis=0).values) print('sim row totals:', simdata.sum(axis=0)) print('data column totals:', inputdata.sum(axis=1).values) print('sim column totals:', sim...
data total: 2000.0 sim total: 2000 data row totals: [ 65. 462. 724. 639. 110.] sim row totals: [ 75 468 748 586 123] data column totals: [388. 379. 388. 339. 281. 144. 56. 21. 2. 2.] sim column totals: [378 380 375 335 281 164 59 25 1 2]
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
product multinominal
simdata = sim_2d_product_multinominal(inputdata.values, axis=0) print('data total:', inputdata.sum().sum()) print('sim total:', simdata.sum().sum()) print('data row totals:', inputdata.sum(axis=0).astype(int).values) print('sim row totals:', simdata.sum(axis=0).astype(int)) print('data column totals:', inputdata.sum(...
data total: 2000.0 sim total: 2000 data row totals: [ 65 462 724 639 110] sim row totals: [ 65 462 724 639 110] data column totals: [388 379 388 339 281 144 56 21 2 2] sim column totals: [399 353 415 349 272 139 45 22 4 2]
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
hypergeometric ("patefield")
# patefield simulation needs compiled c++ code. # only run this if the python binding to the (compiled) patefiled simulation function is found. try: from phik.simcore import _sim_2d_data_patefield CPP_SUPPORT = True except ImportError: CPP_SUPPORT = False if CPP_SUPPORT: simdata = sim_2d_data_patefield...
data total: 2000.0 sim total: 2000 data row totals: [ 65 462 724 639 110] sim row totals: [ 65 462 724 639 110] data column totals: [388 379 388 339 281 144 56 21 2 2] sim column totals: [388 379 388 339 281 144 56 21 2 2]
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Outlier significanceThe normal pearson correlation between two interval variables is easy to interpret. However, the phik correlation between two variables of mixed type is not always easy to interpret, especially when it concerns categorical variables. Therefore, functionality is provided to detect "outliers": excess...
c0 = 'mileage' c1 = 'car_size' tmp_interval_cols = ['mileage'] outlier_signifs, binning_dict = data[[c0,c1]].outlier_significance_matrix(interval_cols=tmp_interval_cols, retbins=True) outlier_signifs
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Specify binning per interval variableBinning can be set per interval variable individually. One can set the number of bins, or specify a list of bin edges. Note: in case a bin is created without any records this bin will be automatically dropped in the phik and (outlier) significance calculations. However, in the outl...
bins = [0,1E2, 1E3, 1E4, 1E5, 1E6] outlier_signifs, binning_dict = data[[c0,c1]].outlier_significance_matrix(interval_cols=tmp_interval_cols, bins=bins, retbins=True) outlier_signifs
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Specify binning per interval variable -- dealing with underflow and overflowWhen specifying custom bins as situation can occur when the minimal (maximum) value in the data is smaller (larger) than the minimum (maximum) bin edge. Data points outside the specified range will be collected in the underflow (UF) and overfl...
bins = [1E2, 1E3, 1E4, 1E5] outlier_signifs, binning_dict = data[[c0,c1]].outlier_significance_matrix(interval_cols=tmp_interval_cols, bins=bins, retbins=True, drop_under...
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Dealing with NaN's in the data Let's add some missing values to our data
data.loc[np.random.choice(range(len(data)), size=10), 'car_size'] = np.nan data.loc[np.random.choice(range(len(data)), size=10), 'mileage'] = np.nan
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Sometimes there can be information in the missing values and in which case you might want to consider the NaN values as a separate category. This can be achieved by setting the dropna argument to False.
bins = [1E2, 1E3, 1E4, 1E5] outlier_signifs, binning_dict = data[[c0,c1]].outlier_significance_matrix(interval_cols=tmp_interval_cols, bins=bins, retbins=True, drop_under...
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Here OF and UF are the underflow and overflow bin of car_size, respectively.To just ignore records with missing values set dropna to True (default).
bins = [1E2, 1E3, 1E4, 1E5] outlier_signifs, binning_dict = data[[c0,c1]].outlier_significance_matrix(interval_cols=tmp_interval_cols, bins=bins, retbins=True, drop_under...
_____no_output_____
Apache-2.0
phik/notebooks/phik_tutorial_advanced.ipynb
ionicsolutions/PhiK
Support Vector Clustering visualizedTo get started, please click on the cell with the code below and hit `Shift + Enter` This may take a while. Support Vector Clustering(SVC) is a variation of Support Vector Machine (SVM).SVC is a way of determining a boudary point between different labels. It utilizes a kernel metho...
%matplotlib notebook import matplotlib.pyplot as plt import numpy as np from ipywidgets import * from IPython.display import display from sklearn.svm import SVC plt.style.use('ggplot') def plot_data(data, labels, sep): data_x = data[:, 0] data_y = data[:, 1] sep_x = sep[:, 0] sep_y = sep[:, 1] # ...
_____no_output_____
MIT
demo/classification.ipynb
DandikUnited/dandikunited.github.io
import pandas as pd import numpy as np values_1 = np.random.randint(10, size=10) values_2 = np.random.randint(10, size = 10) print(values_1) print(values_2) years = np.arange(2010, 2020) print(years) groups = ['A','A','B','A','B','B','C','A','C','C'] len(groups) df = pd.DataFrame({'group':groups, 'year':years,'value_1'...
_____no_output_____
MIT
2020_07_15_pandas_functions.ipynb
daekee0325/Data-Analysis
SMPLE
Sample1 = df.sample(n=3) Sample1 Sample2 = df.sample(frac=0.5) Sample2 df['new_col'].where(df['new_col']>0,0) np.where(df['new_col'] >0, df['new_col'], 0)
_____no_output_____
MIT
2020_07_15_pandas_functions.ipynb
daekee0325/Data-Analysis
isin
years = ['2010','2014','2015'] df[df.year.isin(years)] df.loc[:2, ['group','year'] ] df.loc[[1,3,5],['year','value_1']] df['value_1'] df.value_1.pct_change() df.value_1.sort_values() df.value_1.sort_values().pct_change() df['rank_1'] = df['value_1'].rank( ) df df.select_dtypes(exclude='int64') df.replace({'A':'A_1','B'...
_____no_output_____
MIT
2020_07_15_pandas_functions.ipynb
daekee0325/Data-Analysis
Description This notebook runs some pre-analyses using DBSCAN to explore the best set of parameters (`min_samples` and `eps`) to cluster `pca` data version. Environment variables
from IPython.display import display import conf N_JOBS = conf.GENERAL["N_JOBS"] display(N_JOBS) %env MKL_NUM_THREADS=$N_JOBS %env OPEN_BLAS_NUM_THREADS=$N_JOBS %env NUMEXPR_NUM_THREADS=$N_JOBS %env OMP_NUM_THREADS=$N_JOBS
env: MKL_NUM_THREADS=2 env: OPEN_BLAS_NUM_THREADS=2 env: NUMEXPR_NUM_THREADS=2 env: OMP_NUM_THREADS=2
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Modules loading
%load_ext autoreload %autoreload 2 from pathlib import Path import numpy as np import pandas as pd from sklearn.neighbors import NearestNeighbors from sklearn.metrics import pairwise_distances from sklearn.cluster import DBSCAN from sklearn.metrics import ( silhouette_score, calinski_harabasz_score, davies...
_____no_output_____
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Global settings
np.random.seed(0) CLUSTERING_ATTRIBUTES_TO_SAVE = ["n_clusters"]
_____no_output_____
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Data version: pca
INPUT_SUBSET = "pca" INPUT_STEM = "z_score_std-projection-smultixcan-efo_partial-mashr-zscores" DR_OPTIONS = { "n_components": 50, "svd_solver": "full", "random_state": 0, } input_filepath = Path( conf.RESULTS["DATA_TRANSFORMATIONS_DIR"], INPUT_SUBSET, generate_result_set_name( DR_OPTION...
_____no_output_____
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Tests different k values (k-NN)
# `k_values` is the full range of k for kNN, whereas `k_values_to_explore` is a # subset that will be explored in this notebook. If the analysis works, then # `k_values` and `eps_range_per_k` below are copied to the notebook that will # produce the final DBSCAN runs (`../002_[...]-dbscan-....ipynb`) k_values = np.arang...
_____no_output_____
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Extended test Generate clusterers
CLUSTERING_OPTIONS = {} # K_RANGE is the min_samples parameter in DBSCAN (sklearn) CLUSTERING_OPTIONS["K_RANGE"] = k_values_to_explore CLUSTERING_OPTIONS["EPS_RANGE_PER_K"] = eps_range_per_k_to_explore CLUSTERING_OPTIONS["EPS_STEP"] = 33 CLUSTERING_OPTIONS["METRIC"] = "euclidean" display(CLUSTERING_OPTIONS) CLUSTERER...
_____no_output_____
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Generate ensemble
data_dist = pairwise_distances(data, metric=CLUSTERING_OPTIONS["METRIC"]) data_dist.shape pd.Series(data_dist.flatten()).describe().apply(str) ensemble = generate_ensemble( data_dist, CLUSTERERS, attributes=CLUSTERING_ATTRIBUTES_TO_SAVE, ) ensemble.shape ensemble.head() _tmp = ensemble["n_clusters"].value_c...
_____no_output_____
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Testing
assert ensemble_stats["min"] > 1 assert not ensemble["n_clusters"].isna().any() # all partitions have the right size assert np.all( [part["partition"].shape[0] == data.shape[0] for idx, part in ensemble.iterrows()] )
_____no_output_____
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Add clustering quality measures
def _remove_nans(data, part): not_nan_idx = ~np.isnan(part) return data.iloc[not_nan_idx], part[not_nan_idx] def _apply_func(func, data, part): no_nan_data, no_nan_part = _remove_nans(data, part) return func(no_nan_data, no_nan_part) ensemble = ensemble.assign( si_score=ensemble["partition"].apply...
_____no_output_____
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Cluster quality
with pd.option_context("display.max_rows", None, "display.max_columns", None): _df = ensemble.groupby(["n_clusters"]).mean() display(_df) with sns.plotting_context("talk", font_scale=0.75), sns.axes_style( "whitegrid", {"grid.linestyle": "--"} ): fig = plt.figure(figsize=(14, 6)) ax = sns.pointplot(...
_____no_output_____
BSD-2-Clause-Patent
nbs/12_cluster_analysis/pre_analysis/06_02-dbscan-pca.ipynb
greenelab/phenoplier
Generic startnotebook, course on webscraping*By Olav ten Bosch, Dick Windmeijer and Marijn Detiger* Documentation: [Requests.py](http://docs.python-requests.org) [Beautifulsoup.py](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)
# Imports: import requests from bs4 import BeautifulSoup import time # for sleeping between multiple requests #Issue a request: #r1 = requests.get('http://testing-ground.scraping.pro') #print(r1.status_code, r1.headers['content-type'], r1.encoding, r1.text) #Issue a request with dedicated user-ag...
_____no_output_____
CC-BY-4.0
20200907/GenericStartNotebook.ipynb
SNStatComp/CBSAcademyBD
Multi Investment OptimizationIn the following, we show how PyPSA can deal with multi-investment optimization, also known as multi-horizon optimization. Here, the total set of snapshots is divided into investment periods. For the model, this translates into multi-indexed snapshots with the first level being the investm...
import pypsa import pandas as pd import numpy as np import matplotlib.pyplot as plt
_____no_output_____
MIT
examples/notebooks/multi-investment-optimisation.ipynb
p-glaum/PyPSA
We set up the network with investment periods and snapshots.
n = pypsa.Network() years = [2020, 2030, 2040, 2050] freq = "24" snapshots = pd.DatetimeIndex([]) for year in years: period = pd.date_range( start="{}-01-01 00:00".format(year), freq="{}H".format(freq), periods=8760 / float(freq), ) snapshots = snapshots.append(period) # convert to...
_____no_output_____
MIT
examples/notebooks/multi-investment-optimisation.ipynb
p-glaum/PyPSA
Set the years and objective weighting per investment period. For the objective weighting, we consider a discount rate defined by $$ D(t) = \dfrac{1}{(1+r)^t} $$ where $r$ is the discount rate. For each period we sum up all discounts rates of the corresponding years which gives us the effective objective weighting.
n.investment_period_weightings["years"] = list(np.diff(years)) + [10] r = 0.01 T = 0 for period, nyears in n.investment_period_weightings.years.items(): discounts = [(1 / (1 + r) ** t) for t in range(T, T + nyears)] n.investment_period_weightings.at[period, "objective"] = sum(discounts) T += nyears n.inves...
_____no_output_____
MIT
examples/notebooks/multi-investment-optimisation.ipynb
p-glaum/PyPSA
Add the components
for i in range(3): n.add("Bus", "bus {}".format(i)) # add three lines in a ring n.add( "Line", "line 0->1", bus0="bus 0", bus1="bus 1", ) n.add( "Line", "line 1->2", bus0="bus 1", bus1="bus 2", capital_cost=10, build_year=2030, ) n.add( "Line", "line 2->0", bus...
_____no_output_____
MIT
examples/notebooks/multi-investment-optimisation.ipynb
p-glaum/PyPSA
Add the load
load_var = pd.Series( 100 * np.random.rand(len(n.snapshots)), index=n.snapshots, name="load" ) n.add("Load", "load 2", bus="bus 2", p_set=load_var) load_fix = pd.Series(75, index=n.snapshots, name="load") n.add("Load", "load 1", bus="bus 1", p_set=load_fix)
_____no_output_____
MIT
examples/notebooks/multi-investment-optimisation.ipynb
p-glaum/PyPSA
Run the optimization
n.loads_t.p_set n.lopf(pyomo=False, multi_investment_periods=True) c = "Generator" df = pd.concat( { period: n.get_active_assets(c, period) * n.df(c).p_nom_opt for period in n.investment_periods }, axis=1, ) df.T.plot.bar( stacked=True, edgecolor="white", width=1, ylabel="Cap...
_____no_output_____
MIT
examples/notebooks/multi-investment-optimisation.ipynb
p-glaum/PyPSA
Intro**This is Lesson 3 in the [Deep Learning](https://www.kaggle.com/education/machine-learning) track** At the end of this lesson, you will be able to write TensorFlow and Keras code to use one of the best models in computer vision. Lesson
from IPython.display import YouTubeVideo YouTubeVideo('sDG5tPtsbSA', width=800, height=450)
_____no_output_____
MIT
deep learning and computer vision/kaggle-learn-tensorflow-exercise.ipynb
DrDarbin/Kaggle-learn-tasks-solutions
Sample Code Choose Images to Work With
from os.path import join image_dir = '../input/dog-breed-identification/train/' img_paths = [join(image_dir, filename) for filename in ['0246f44bb123ce3f91c939861eb97fb7.jpg', '84728e78632c0910a69d33f82e62638c.jpg', '8825e914555803f4c6...
_____no_output_____
MIT
deep learning and computer vision/kaggle-learn-tensorflow-exercise.ipynb
DrDarbin/Kaggle-learn-tasks-solutions
Function to Read and Prep Images for Modeling
import numpy as np from tensorflow.python.keras.applications.resnet50 import preprocess_input from tensorflow.python.keras.preprocessing.image import load_img, img_to_array image_size = 224 def read_and_prep_images(img_paths, img_height=image_size, img_width=image_size): imgs = [load_img(img_path, target_size=(im...
_____no_output_____
MIT
deep learning and computer vision/kaggle-learn-tensorflow-exercise.ipynb
DrDarbin/Kaggle-learn-tasks-solutions
Create Model with Pre-Trained Weights File. Make Predictions
from tensorflow.python.keras.applications import ResNet50 my_model = ResNet50(weights='../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels.h5') test_data = read_and_prep_images(img_paths) preds = my_model.predict(test_data)
_____no_output_____
MIT
deep learning and computer vision/kaggle-learn-tensorflow-exercise.ipynb
DrDarbin/Kaggle-learn-tasks-solutions
Visualize Predictions
from learntools.deep_learning.decode_predictions import decode_predictions from IPython.display import Image, display most_likely_labels = decode_predictions(preds, top=3, class_list_path='../input/resnet50/imagenet_class_index.json') for i, img_path in enumerate(img_paths): display(Image(img_path)) print(mos...
_____no_output_____
MIT
deep learning and computer vision/kaggle-learn-tensorflow-exercise.ipynb
DrDarbin/Kaggle-learn-tasks-solutions
Rhetorical relations classification used in tree building: ESIMPrepare data and model-related scripts.Evaluate models.Make and evaluate ansembles for ESIM and BiMPM model / ESIM and feature-based model.Output: - ``models/relation_predictor_esim/*``
%load_ext autoreload %autoreload 2 import os import glob import pandas as pd import numpy as np import pickle from utils.file_reading import read_edus, read_gold, read_negative, read_annotation
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
Make a directory
MODEL_PATH = 'models/label_predictor_esim' ! mkdir $MODEL_PATH TRAIN_FILE_PATH = os.path.join(MODEL_PATH, 'nlabel_cf_train.tsv') DEV_FILE_PATH = os.path.join(MODEL_PATH, 'nlabel_cf_dev.tsv') TEST_FILE_PATH = os.path.join(MODEL_PATH, 'nlabel_cf_test.tsv')
mkdir: cannot create directory ‘models/label_predictor_esim’: File exists
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
Prepare train/test sets
IN_PATH = 'data_labeling' train_samples = pd.read_pickle(os.path.join(IN_PATH, 'train_samples.pkl')) dev_samples = pd.read_pickle(os.path.join(IN_PATH, 'dev_samples.pkl')) test_samples = pd.read_pickle(os.path.join(IN_PATH, 'test_samples.pkl')) counts = train_samples['relation'].value_counts(normalize=False).values NU...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
Modify model (Add F1, concatenated encoding)
%%writefile models/bimpm_custom_package/model/esim.py from typing import Dict, List, Any, Optional import numpy import torch from allennlp.common.checks import check_dimensions_match from allennlp.data import TextFieldTensors, Vocabulary from allennlp.models.model import Model from allennlp.modules import FeedForwar...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
2. Generate config files ELMo
%%writefile $MODEL_PATH/config_elmo.json local NUM_EPOCHS = 200; local LR = 1e-3; local LSTM_ENCODER_HIDDEN = 25; { "dataset_reader": { "type": "quora_paraphrase", "tokenizer": { "type": "just_spaces" }, "token_indexers": { "token_characters": { "type": "characters", "min...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
3. Scripts for training/prediction Option 1. Directly from the config Train a model
%%writefile models/train_label_predictor_esim.sh # usage: # $ cd models # $ sh train_label_predictor.sh {bert|elmo} result_30 export METHOD=${1} export RESULT_DIR=${2} export DEV_FILE_PATH="nlabel_cf_dev.tsv" export TEST_FILE_PATH="nlabel_cf_test.tsv" rm -r label_predictor_esim/${RESULT_DIR}/ allennlp train -s label...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
Predict on dev&test
%%writefile models/eval_label_predictor_esim.sh # usage: # $ cd models # $ sh train_label_predictor.sh {bert|elmo} result_30 export METHOD=${1} export RESULT_DIR=${2} export DEV_FILE_PATH="nlabel_cf_dev.tsv" export TEST_FILE_PATH="nlabel_cf_test.tsv" allennlp predict --use-dataset-reader --silent \ --output-file...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
(optional) predict on train
%%writefile models/eval_label_predictor_train.sh # usage: # $ cd models # $ sh eval_label_predictor_train.sh {bert|elmo} result_30 export METHOD=${1} export RESULT_DIR=${2} export TEST_FILE_PATH="nlabel_cf_train.tsv" allennlp predict --use-dataset-reader --silent \ --output-file label_predictor_bimpm/${RESULT_DI...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
Option 2. Using wandb for parameters adjustment
%%writefile ../../../maintenance_rst/models/wandb_label_predictor_esim.yaml name: label_predictor_esim program: wandb_allennlp # this is a wrapper console script around allennlp commands. It is part of wandb-allennlp method: bayes ## Do not for get to use the command keyword to specify the following command structure ...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
3. Run training ``wandb sweep wandb_label_predictor_esim.yaml``(returns %sweepname1)``wandb sweep wandb_label_predictor2.yaml``(returns %sweepname2)``wandb agent --count 1 %sweepname1 && wandb agent --count 1 %sweepname2`` Move the best model in label_predictor_bimpm
! ls -laht models/wandb ! cp -r models/wandb/run-20201218_123424-kcphaqhi/training_dumps models/label_predictor_esim/esim_elmo
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
**Or** load from wandb by %sweepname
import wandb api = wandb.Api() run = api.run("tchewik/tmp/7hum4oom") for file in run.files(): file.download(replace=True) ! cp -r training_dumps models/label_predictor_bimpm/toasty-sweep-1
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
And run evaluation from shell``sh eval_label_predictor_esim.sh {elmo|elmo_fasttext} toasty-sweep-1`` 4. Evaluate classifier
def load_predictions(path): result = [] vocab = [] with open(path, 'r') as file: for line in file.readlines(): line = json.loads(line) if line.get("label"): result.append(line.get("label")) elif line.get("label_probs"): if not ...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
On dev set
import pandas as pd import json true = pd.read_csv(DEV_FILE_PATH, sep='\t', header=None)[0].values.tolist() pred = load_predictions(f'{MODEL_PATH}/{RESULT_DIR}/predictions_dev.json') from sklearn.metrics import classification_report print(classification_report(true[:len(pred)], pred, digits=4)) test_metrics = classif...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
On train set (optional)
import pandas as pd import json true = pd.read_csv('models/label_predictor_bimpm/nlabel_cf_train.tsv', sep='\t', header=None)[0].values.tolist() pred = load_predictions(f'{MODEL_PATH}/{RESULT_DIR}/predictions_train.json') print(classification_report(true[:len(pred)], pred, digits=4)) file = 'models/label_predictor_ls...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
On test set
import pandas as pd import json true = pd.read_csv(TEST_FILE_PATH, sep='\t', header=None)[0].values.tolist() pred = load_predictions(f'{MODEL_PATH}/{RESULT_DIR}/predictions_test.json') print(classification_report(true[:len(pred)], pred, digits=4)) test_metrics = classification_report(true[:len(pred)], pred, digits=4,...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
Ensemble: (Logreg+Catboost) + ESIM
! ls models/label_predictor_esim import json model_vocab = open(MODEL_PATH + '/' + RESULT_DIR + '/vocabulary/labels.txt', 'r').readlines() model_vocab = [label.strip() for label in model_vocab] catboost_vocab = [ 'attribution_NS', 'attribution_SN', 'background_NS', 'cause-effect_NS', 'cause-effect_SN', 'compari...
/opt/.pyenv/versions/3.7.4/lib/python3.7/site-packages/sklearn/base.py:318: UserWarning: Trying to unpickle estimator Pipeline from version 0.22.2.post1 when using version 0.22.1. This might lead to breaking code or invalid results. Use at your own risk. UserWarning) /opt/.pyenv/versions/3.7.4/lib/python3.7/site-pack...
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
On dev set
from sklearn import metrics TARGET = 'relation' y_dev, X_dev = dev_samples['relation'].to_frame(), dev_samples.drop('relation', axis=1).drop( columns=drop_columns + ['category_id', 'index']) X_scaled_np = scaler.transform(X_dev) X_dev = pd.DataFrame(X_scaled_np, index=X_dev.index) catboost_predictions = load_s...
weighted f1: 0.5413872373769657 macro f1: 0.5354738926873194 accuracy: 0.5389321468298109 precision recall f1-score support attribution_NS 0.8409 0.9024 0.8706 82 attribution_SN 0.8424 0.8564 0.8493 181 ...
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
On test set
_test_samples = test_samples[:] test_samples = _test_samples[:] mask = test_samples.filename.str.contains('news') test_samples = test_samples[test_samples['filename'].str.contains('news')] mask.shape test_samples.shape def mask_predictions(predictions, mask): result = [] mask = mask.values for i, prediction...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
Ensemble: BiMPM + ESIM On dev set
!ls models/label_predictor_bimpm/ from sklearn import metrics TARGET = 'relation' y_dev, X_dev = dev_samples['relation'].to_frame(), dev_samples.drop('relation', axis=1).drop( columns=drop_columns + ['category_id', 'index']) X_scaled_np = scaler.transform(X_dev) X_dev = pd.DataFrame(X_scaled_np, index=X_dev.ind...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
On test set
TARGET = 'relation' y_test, X_test = test_samples[TARGET].to_frame(), test_samples.drop(TARGET, axis=1).drop( columns=drop_columns + ['category_id', 'index']) X_scaled_np = scaler.transform(X_test) X_test = pd.DataFrame(X_scaled_np, index=X_test.index) bimpm = load_neural_predictions(f'models/label_predictor_bim...
_____no_output_____
MIT
src/maintenance/3.5_relations_classification_esim.ipynb
tchewik/isanlp_rst
Quantitative Value Strategy"Value investing" means investing in the stocks that are cheapest relative to common measures of business value (like earnings or assets).For this project, we're going to build an investing strategy that selects the 50 stocks with the best value metrics. From there, we will calculate recomme...
import numpy as np import pandas as pd import xlsxwriter import requests from scipy import stats import math
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
Importing Our List of Stocks & API TokenAs before, we'll need to import our list of stocks and our API token before proceeding. Make sure the .csv file is still in your working directory and import it with the following command:
stocks = pd.read_csv('sp_500_stocks.csv') from secrets import IEX_CLOUD_API_TOKEN
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
Making Our First API CallIt's now time to make the first version of our value screener!We'll start by building a simple value screener that ranks securities based on a single metric (the price-to-earnings ratio).
symbol = 'aapl' api_url = f"https://sandbox.iexapis.com/stable/stock/{symbol}/quote?token={IEX_CLOUD_API_TOKEN}" data = requests.get(api_url).json()
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
Parsing Our API CallThis API call has the metric we need - the price-to-earnings ratio.Here is an example of how to parse the metric from our API call:
price = data['latestPrice'] pe_ratio = data['peRatio'] pe_ratio
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
Executing A Batch API Call & Building Our DataFrameJust like in our first project, it's now time to execute several batch API calls and add the information we need to our DataFrame.We'll start by running the following code cell, which contains some code we already built last time that we can re-use for this project. M...
# Function sourced from # https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n] symbol_groups = list(chunks(stocks['Ticker'], 100)) sy...
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
Now we need to create a blank DataFrame and add our data to the data frame one-by-one.
df = pd.DataFrame(columns = my_columns) for batch in symbol_strings: batch_api_call_url = f"https://sandbox.iexapis.com/stable/stock/market/batch?symbols={batch}&types=quote&token={IEX_CLOUD_API_TOKEN}" data = requests.get(batch_api_call_url).json() for symbol in batch.split(','): df = df.append( ...
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
Removing Glamour StocksThe opposite of a "value stock" is a "glamour stock". Since the goal of this strategy is to identify the 50 best value stocks from our universe, our next step is to remove glamour stocks from the DataFrame.We'll sort the DataFrame by the stocks' price-to-earnings ratio, and drop all stocks outsi...
df.sort_values('Price-to-Earnings Ratio', ascending=False, inplace=True) df = df[df['Price-to-Earnings Ratio'] > 0] df = df[:50] df.reset_index(inplace=True, drop=True) df
/var/folders/q_/gmxdkf893w3bm9wxvh6635t80000gp/T/ipykernel_89390/1321168316.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df.sor...
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
Calculating the Number of Shares to BuyWe now need to calculate the number of shares we need to buy. To do this, we will use the `portfolio_input` function that we created in our momentum project.I have included this function below.
def portfolio_input(): global portfolio_size portfolio_size = input("Enter the value of your portfolio:") try: portfolio_size = float(portfolio_size) except ValueError: print("That's not a number! \n Try again:") portfolio_size = input("Enter the value of your portfolio:")
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
Use the `portfolio_input` function to accept a `portfolio_size` variable from the user of this script.
portfolio_input()
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
You can now use the global `portfolio_size` variable to calculate the number of shares that our strategy should purchase.
position_size = portfolio_size/len(df.index) for row in df.index: df.loc[row, 'Number of Shares to Buy'] = math.floor(position_size/df.loc[row, 'Price']) df
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python
Building a Better (and More Realistic) Value StrategyEvery valuation metric has certain flaws.For example, the price-to-earnings ratio doesn't work well with stocks with negative earnings.Similarly, stocks that buyback their own shares are difficult to value using the price-to-book ratio.Investors typically use a `com...
symbol = 'AAPL' batch_api_call_url = f"https://sandbox.iexapis.com/stable/stock/market/batch?symbols={symbol}&types=quote,advanced-stats&token={IEX_CLOUD_API_TOKEN}" data = requests.get(batch_api_call_url).json() # * Price-to-earnings ratio pe_ratio = data[symbol]['quote']['peRatio'] # * Price-to-book ratio pb_ratio = ...
_____no_output_____
MIT
003_quantitative_value_strategy.ipynb
gyalpodongo/algorithmic_trading_python