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 |
|---|---|---|---|---|---|
We can make a forward shift by using **minus** for the periods. Here we use **(-1)** to shift the data one day forward: | TS.shift(-1) | _____no_output_____ | MIT | 14.5 Shifting Data Through Time (Lagging and Leading).ipynb | SiamakMushakhian/Numpy-Pandas-Seaborn |
Usually when dealing with time series, we create a shifted data and attach it as a new column in the time series, like this: | TS['lag1'] = TS['apple'].shift(1)
TS | _____no_output_____ | MIT | 14.5 Shifting Data Through Time (Lagging and Leading).ipynb | SiamakMushakhian/Numpy-Pandas-Seaborn |
Shifting data in time series generates **missing values**, we can delete these missing values using the function **dropna()**, and to make the changes reflected in the original times series we use the argument **inplace = True**: | TS.dropna(inplace = True)
TS | _____no_output_____ | MIT | 14.5 Shifting Data Through Time (Lagging and Leading).ipynb | SiamakMushakhian/Numpy-Pandas-Seaborn |
For example we can calculate the daily percent change for stock prices using the **shift()** function like this: | TS['percent_change'] = ( TS['apple'] / TS['apple'].shift(1) ) -1
TS | _____no_output_____ | MIT | 14.5 Shifting Data Through Time (Lagging and Leading).ipynb | SiamakMushakhian/Numpy-Pandas-Seaborn |
Again here we can delete the missing values like this: | TS.dropna(inplace = True)
TS | _____no_output_____ | MIT | 14.5 Shifting Data Through Time (Lagging and Leading).ipynb | SiamakMushakhian/Numpy-Pandas-Seaborn |
Set Up | from pythonosc import dispatcher, osc_server
from pythonosc.udp_client import SimpleUDPClient
import time
from bitalino import BITalino
import biofeatures
bitalino_ip = '192.168.0.101'
bitalino_port = 31000
actuator_ip = '192.168.0.100'
actuator_port = 12000
osc_client = SimpleUDPClient(actuator_ip, actuator_port)
... | _____no_output_____ | ISC | notebooks/alternative_resp_v1.ipynb | malfarasplux/biofeatures |
from torchvision import datasets, transforms
import numpy
transform = transforms.Compose([transforms.Lambda(lambda pil_im: numpy.array(pil_im))])
transform = None
testset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
from PIL import Image
import numpy as np
import cv2
import imuti... | _____no_output_____ | MIT | extra/Base_colors_detection.ipynb | Gan4x4/hse-cv2019 | |
Author: **Lee Surprenant** lmsurpre@us.ibm.com- [Section 1: The FHIR HTTP API](Section-1.-The-FHIR-REST-API)- [Section 2: FHIR Search](Section-2:-FHIR-Search)- [Section 3: Search paramater types](Section-3:-Search-parameter-types)- [Section 4: Chaining and includes](Section-4:-Chaining-and-includes)- [Section 5: Putti... | # save the base url of the FHIR server
base = 'https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open'
# setup imports
import os
from requests import get
from requests import post
from requests import put
from requests import delete
from requests import head
from IPython.... | /opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/secretstorage/dhcrypto.py:16: CryptographyDeprecationWarning: int_from_bytes is deprecated, use int.from_bytes instead
from cryptography.utils import int_from_bytes
/opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/secretstorage/util.py:25: Cryptog... | Apache-2.0 | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter |
Section 1. The FHIR REST API | # HL7 FHIR defines a set of "resources" for exchanging information.
IFrame('https://www.hl7.org/fhir/resourcelist.html#tabs', width=1200, height=330)
# Each resource type supports the same set of interactions, categorized in the spec into "instance-level" and "type-level" interactions.
IFrame('https://www.hl7.org/fhir/... | Response code: 200
Server: IBM FHIR Server 4.8.0
Security: {'cors': True}
Supported types:
Measure: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']
MedicinalProductIndication: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']
O... | Apache-2.0 | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter |
Section 2: FHIR Search | # Now that we know our server supports the "search-type" interaction on all resource types, lets start working with the Patient endpoint.
# query for all Patient resources, then print the HTTP status code and the first 25 lines of the response
response = get(base + '/Patient')
print('Response code: ' + str(response.st... | male: 15450
female: 17204
missing gender: 1
| Apache-2.0 | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter |
Section 3: Search parameter types | # search parameters have types
# gender is considered a "token" search parameter
# Token search
# this parameter type is common for 'coded' values (Code, Coding, and CodeableConcept) and identifiers
# token values consist of a system and a code, although sometimes the system is implicit (like in the case of gender)
#... | Conditions for patient 17598beef3c-73a65dab-c8e5-4756-a60a-69bbc48cef4f:
{'coding': [{'system': 'http://snomed.info/sct', 'code': '10509002', 'display': 'Acute bronchitis (disorder)'}], 'text': 'Acute bronchitis (disorder)'}
{'coding': [{'system': 'http://snomed.info/sct', 'code': '195662009', 'display': 'Acute viral p... | Apache-2.0 | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter |
Section 4: Chaining and includes | # Chaining
# where reference parameters get really interesting is when you want to query one resource type based on a property of another resource to which its linked
# for example, here is a search for Type II Diabetes in female patients
response = get(base + '/Condition' + '?' + 'code=http://snomed.info/sct|44054006... | Response contains both Patients and Conditions, but only the Patients are counted in the page size and total:
Total: 17204
Patient: 17598bf36c7-fedcedc3-b78c-4688-82ef-622e0cc71b22
Patient: 17598bf4a5d-185e291b-d0e3-42d3-9b70-eeae60debeec
Condition: 17598bf36c8-5800bd67-4c08-4a68-8968-054c670ef2a6
Condition: 17598bf36... | Apache-2.0 | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter |
Section 5: Putting it together | response = get(base + '/Condition' + '?' + 'code=http://snomed.info/sct|44054006' + '&_count=1')
print('Patients with Type II Diabetes: ' + str(response.json().get('total')))
# SNOMED concepts for comorbidities of Type II Diabetes
#coronary heart disease (CHD), 53741008
#chronic kidney disease (CKD), 709044004
#atrial... | CHD:
Total: 30
1759a06f11a-77b7ee76-ae8d-47a8-9a8e-17e7278e4137, 1759bccd5dc-a4192660-b224-4d88-acf6-bfb538fc0052, 1759c042626-da786c63-fcd4-4a86-aaec-54ec28458861, 1759c7179ab-cdc927fb-ec72-4c10-961e-a424bb8241f3, 1759c906bce-6fcc151d-240e-441f-aa3f-3a8123222d0c, 1759c9d0e32-10946dda-2ac9-4f8e-a6ba-eade9aba6ac8, 175b9... | Apache-2.0 | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter |
Section 6: Bulk export | # To perform deeper analysis of the data, it can be useful to export some or all of the data into "bulk fhir" format
export_response = get(base + '/$export' + '?' + '_type=Patient,Condition')
print('Response code: ' + str(export_response.status_code))
print(export_response.headers)
import time
# poll the status endpoi... | _____no_output_____ | Apache-2.0 | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter |
Tabular data preprocessing | from fastai.gen_doc.nbdoc import *
from fastai.tabular import *
from fastai import * | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Overview This package contains the basic class to define a transformation for preprocessing dataframes of tabular data, as well as basic [`TabularTransform`](/tabular.transform.htmlTabularTransform). Preprocessing includes things like- replacing non-numerical variables by categories, then their ids,- filling missing v... | path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv')
train_df, valid_df = df[:800].copy(),df[800:].copy()
train_df.head() | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
We see it contains numerical variables (like `age` or `education-num`) as well as categorical ones (like `workclass` or `relationship`). The original dataset is clean, but we removed a few values to give examples of dealing with missing variables. | cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country']
cont_names = ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week'] | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Transforms for tabular data | show_doc(TabularTransform, doc_string=False) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Base class for creating transforms for dataframes with categorical variables `cat_names` and continuous variables `cont_names`. Note that any column not in one of those lists won't be touched. | show_doc(TabularTransform.__call__) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
This simply calls `apply_test` if `test` or `apply_train` otherwise. Those functions apply the changes in place. | show_doc(TabularTransform.apply_train, doc_string=False) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Must be implemented by an inherited class with the desired transformation logic. | show_doc(TabularTransform.apply_test, doc_string=False) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
If not implemented by an inherited class, defaults to calling `apply_train`. The following [`TabularTransform`](/tabular.transform.htmlTabularTransform) are implemented in the fastai library. Note that the replacement from categories to codes as well as the normalization of continuous variables are automatically done i... | show_doc(Categorify, doc_string=False) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Changes the categorical variables in `cat_names` in categories. Variables in `cont_names` aren't affected. | show_doc(Categorify.apply_train, doc_string=False) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Transforms the variable in the `cat_names` columns in categories. The category codes are the unique values in these columns. | show_doc(Categorify.apply_test, doc_string=False) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Transforms the variable in the `cat_names` columns in categories. The category codes are the ones used for the training set, new categories are replaced by NaN. | tfm = Categorify(cat_names, cont_names)
tfm(train_df)
tfm(valid_df, test=True) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Since we haven't changed the categories by their codes, nothing visible has changed in the dataframe yet, but we can check that the variables are now categorical and view their corresponding codes. | train_df['workclass'].cat.categories | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
The test set will be given the same category codes as the training set. | valid_df['workclass'].cat.categories
show_doc(FillMissing, doc_string=False) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Transform that fills the missing values in `cont_names`. `cat_names` variables are left untouched (their missing value will be raplced by code 0 in the [`TabularDataset`](/tabular.data.htmlTabularDataset)). [`fill_strategy`](FillStrategy) is adopted to replace those nans and if `add_col` is True, whenever a column `c` ... | show_doc(FillMissing.apply_train, doc_string=False) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Fills the missing values in the `cont_names` columns. | show_doc(FillMissing.apply_test, doc_string=False) | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Fills the missing values in the `cont_names` columns with the ones picked during train. | train_df[cont_names].head()
tfm = FillMissing(cat_names, cont_names)
tfm(train_df)
tfm(valid_df, test=True)
train_df[cont_names].head() | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Values issing in the `education-num` column are replaced by 10, which is the median of the column in `train_df`. Categorical variables are not changed, since `nan` is simply used as another category. | valid_df[cont_names].head()
%reload_ext autoreload
%autoreload 2
%matplotlib inline
show_doc(FillStrategy, alt_doc_string='Enum flag represents determines how `FillMissing` should handle missing/nan values', arg_comments={
'MEDIAN':'nans are replaced by the median value of the column',
'COMMON': 'nans are repla... | _____no_output_____ | Apache-2.0 | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs |
Automatic Differentiation of PDE solvers with JAX and dolfin-adjointDerivative information is the crucial requirement for using effective algorithms for design optimization, parameter estimation, optimal control, modelreduction and experimental design, and other tasks. This notebook gives an example how to use JAX tog... | # Let's import all needed stuff
import jax
from jax.config import config
import jax.numpy as np
import numpy as onp
from scipy.optimize import minimize
# Library for automated PDE solution
import fenics
# Library for automated derivative computation of FEniCS programs
import fenics_adjoint
# UFL is domain specific l... | _____no_output_____ | MIT | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint |
PDEs are spatial models and require a domain to be defined on. Here we choose the domain to be a unit square and it is triangulated for finite element discretization. | # Create mesh
n = 16
mesh = fenics_adjoint.UnitSquareMesh(n, n)
fenics.plot(mesh) | _____no_output_____ | MIT | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint |
Another important part of the Poisson variational problem is the function space $V$. This object is resposible for representation of the disretized functions on the chosen mesh. Here we choose the function space to consist of piece-wise linear functions (P1 in finite element terminology, or CG1 for Continuous Galerkin ... | # Define discrete function spaces and functions
V = fenics.FunctionSpace(mesh, "CG", 1)
W = fenics.FunctionSpace(mesh, "DG", 0) | _____no_output_____ | MIT | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint |
JAX-FEniCS interface needs an auxilary information to be able to freely convert data between the libraries, therefore we need "templates" which represent what is the expected input to FEniCS function. | solve_templates = (fenics_adjoint.Function(W),) | _____no_output_____ | MIT | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint |
Now we define the `fenics_solve` function which takes a function `f` which lives in the function space `W` and outputs the solution `u` to the Poisson equation.`build_jax_fem_eval` is a wrapper decorator that registers `fenics_solve` for JAX. | # Define and solve the Poisson equation
@build_jax_fem_eval(solve_templates)
def fenics_solve(f):
u = fenics.TrialFunction(V)
v = fenics.TestFunction(V)
inner, grad, dx = ufl.inner, ufl.grad, ufl.dx
# Compare this code to the mathematical formulation above
a = inner(grad(u), grad(v)) * dx
L = f ... | _____no_output_____ | MIT | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint |
Here comes the JAX specific part. Having defined a mapping from $f$ to $u$ we can differentiate it. For example calculating vector-Jacobian product with `jax.vjp`: | %%time
u, vjp_fun = jax.vjp(fenics_solve, f)
g = np.ones_like(u)
vjp_result = vjp_fun(g)
vjp_result_fenics = from_jax(*vjp_result, fenics.Function(W))
c = fenics.plot(vjp_result_fenics)
plt.colorbar(c) | _____no_output_____ | MIT | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint |
It is also possible to calculate the full (dense) Jacobian matrix $\frac{du}{df}$ with `jax.jacrev`: | %%time
dudf = jax.jacrev(fenics_solve)(f)
# function `fenics_solve` maps R^512 (dimension of W) to R^289 (dimension of V)
# therefore the Jacobian matrix dimension is dim V x dim W
assert dudf.shape == (V.dim(), W.dim()) | _____no_output_____ | MIT | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint |
The same Jacobian matrix can be calculated using finite-differences, for example with `fdm` library. However, it takes considerably more time because it requires a lot of `fenics_solve` calls. The difference is even more drastic for larger models. `jaxfenics_adjoint` library makes it possible to combine FEniCS programs... | # stax is JAX's mini-library for neural networks
from jax.experimental import stax
from jax.experimental.stax import Dense, Relu
from jax import random
# Use stax to set up network initialization and evaluation functions
# Define R^2 -> R^1 function
net_init, net_apply = stax.serial(
Dense(2), Relu,
Dense(10),... | CPU times: user 340 ms, sys: 7.82 ms, total: 348 ms
Wall time: 337 ms
| MIT | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint |
© Copyright Quantopian Inc.© Modifications Copyright QuantRocket LLCLicensed under the [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/legalcode).Disclaimer Introduction to pandasby Maxwell Margenot pandas is a Python library that provides a collection of powerful data structures to bett... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
With pandas, it is easy to store, visualize, and perform calculations on your data. With only a few lines of code we can modify our data and present it in an easily-understandable way. Here we simulate some returns in NumPy, put them into a pandas `DataFrame`, and perform calculations to turn them into prices and plot ... | returns = pd.DataFrame(np.random.normal(1.0, 0.03, (100, 10)))
prices = returns.cumprod()
prices.plot()
plt.title('Randomly-generated Prices')
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend(loc=0); | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
So let's have a look at how we actually build up to this point! pandas Data Structures `Series`A pandas `Series` is a 1-dimensional array with labels that can contain any data type. We primarily use them for handling time series data. Creating a `Series` is as easy as calling `pandas.Series()` on a Python list or NumP... | s = pd.Series([1, 2, np.nan, 4, 5])
print(s) | 0 1.0
1 2.0
2 NaN
3 4.0
4 5.0
dtype: float64
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Every `Series` has a name. We can give the series a name as a parameter or we can define it afterwards by directly accessing the name attribute. In this case, we have given our time series no name so the attribute should be empty. | print(s.name) | None
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
This name can be directly modified with no repercussions. | s.name = "Toy Series"
print(s.name) | Toy Series
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We call the collected axis labels of a `Series` its index. An index can either passed to a `Series` as a parameter or added later, similarly to its name. In the absence of an index, a `Series` will simply contain an index composed of integers, starting at $0$, as in the case of our "Toy Series". | print(s.index) | RangeIndex(start=0, stop=5, step=1)
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
pandas has a built-in function specifically for creating date indices, `date_range()`. We use the function here to create a new index for `s`. | new_index = pd.date_range("2016-01-01", periods=len(s), freq="D")
print(new_index) | DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04',
'2016-01-05'],
dtype='datetime64[ns]', freq='D')
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
An index must be exactly the same length as the `Series` itself. Each index must match one-to-one with each element of the `Series`. Once this is satisfied, we can directly modify the `Series` index, as with the name, to use our new and more informative index (relatively speaking). | s.index = new_index
print(s.index) | DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04',
'2016-01-05'],
dtype='datetime64[ns]', freq='D')
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
The index of the `Series` is crucial for handling time series, which we will get into a little later. Accessing `Series` Elements`Series` are typically accessed using the `iloc[]` and `loc[]` methods. We use `iloc[]` to access elements by integer index and we use `loc[]` to access the index of the Series. | print("First element of the series:", s.iloc[0])
print("Last element of the series:", s.iloc[len(s)-1]) | First element of the series: 1.0
Last element of the series: 5.0
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can slice a `Series` similarly to our favorite collections, Python lists and NumPy arrays. We use the colon operator to indicate the slice. | s.iloc[:2] | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
When creating a slice, we have the options of specifying a beginning, an end, and a step. The slice will begin at the start index, and take steps of size `step` until it passes the end index, not including the end. | start = 0
end = len(s) - 1
step = 1
s.iloc[start:end:step] | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can even reverse a `Series` by specifying a negative step size. Similarly, we can index the start and end with a negative integer value. | s.iloc[::-1] | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
This returns a slice of the series that starts from the second to last element and ends at the third to last element (because the fourth to last is not included, taking steps of size $1$). | s.iloc[-2:-4:-1] | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can also access a series by using the values of its index. Since we indexed `s` with a collection of dates (`Timestamp` objects) we can look at the value contained in `s` for a particular date. | s.loc['2016-01-01'] | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Or even for a range of dates! | s.loc['2016-01-02':'2016-01-04'] | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
With `Series`, we *can* just use the brackets (`[]`) to access elements, but this is not best practice. The brackets are ambiguous because they can be used to access `Series` (and `DataFrames`) using both index and integer values and the results will change based on context (especially with `DataFrames`). Boolean Inde... | print(s < 3) | 2016-01-01 True
2016-01-02 True
2016-01-03 False
2016-01-04 False
2016-01-05 False
Freq: D, Name: Toy Series, dtype: bool
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can pass *this* `Series` back into the original `Series` to filter out only the elements for which our condition is `True`. | print(s.loc[s < 3]) | 2016-01-01 1.0
2016-01-02 2.0
Freq: D, Name: Toy Series, dtype: float64
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
If we so desire, we can group multiple conditions together using the logical operators `&`, `|`, and `~` (and, or, and not, respectively). | print(s.loc[(s < 3) & (s > 1)]) | 2016-01-02 2.0
Freq: D, Name: Toy Series, dtype: float64
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
This is very convenient for getting only elements of a `Series` that fulfill specific criteria that we need. It gets even more convenient when we are handling `DataFrames`. Indexing and Time SeriesSince we use `Series` for handling time series, it's worth covering a little bit of how we handle the time component. For ... | from quantrocket.master import get_securities
securities = get_securities(symbols='XOM', fields=['Sid','Symbol','Exchange'], vendors='usstock')
securities
from quantrocket import get_prices
XOM = securities.index[0]
start = "2012-01-01"
end = "2016-01-01"
prices = get_prices("usstock-free-1min", data_frequency="daily",... | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can display the first few elements of our series by using the `head()` method and specifying the number of elements that we want. The analogous method for the last few elements is `tail()`. | print(type(prices))
prices.head(5) | <class 'pandas.core.series.Series'>
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
As with our toy example, we can specify a name for our time series, if only to clarify the name the `get_pricing()` provides us. | print('Old name:', prices.name)
prices.name = "XOM"
print('New name:', prices.name) | Old name: FIBBG000GZQ728
New name: XOM
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Let's take a closer look at the `DatetimeIndex` of our `prices` time series. | print(prices.index)
print("tz:", prices.index.tz) | DatetimeIndex(['2012-01-03', '2012-01-04', '2012-01-05', '2012-01-06',
'2012-01-09', '2012-01-10', '2012-01-11', '2012-01-12',
'2012-01-13', '2012-01-17',
...
'2015-12-17', '2015-12-18', '2015-12-21', '2015-12-22',
'2015-12-23', '2015-12-24', '2... | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Notice that this `DatetimeIndex` has a collection of associated information. In particular it has an associated frequency (`freq`) and an associated timezone (`tz`). The frequency indicates whether the data is daily vs monthly vs some other period while the timezone indicates what locale this index is relative to. We c... | monthly_prices = prices.resample('M').last()
monthly_prices.head(10) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
In the above example we use the last value of the lower level data to create the higher level data. We can specify how else we might want the down-sampling to be calculated, for example using the median. | monthly_prices_med = prices.resample('M').median()
monthly_prices_med.head(10) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can even specify how we want the calculation of the new period to be done. Here we create a `custom_resampler()` function that will return the first value of the period. In our specific case, this will return a `Series` where the monthly value is the first value of that month. | def custom_resampler(array_like):
""" Returns the first value of the period """
return array_like[0]
first_of_month_prices = prices.resample('M').apply(custom_resampler)
first_of_month_prices.head(10) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can also adjust the timezone of a `Series` to adapt the time of real-world data. In our case, our time series isn't localized to a timezone, but let's say that we want to localize the time to be 'America/New_York'. In this case we use the `tz_localize()` method, since the time isn't already localized. | eastern_prices = prices.tz_localize('America/New_York')
eastern_prices.head(10) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
In addition to the capacity for timezone and frequency management, each time series has a built-in `reindex()` method that we can use to realign the existing data according to a new set of index labels. If data does not exist for a particular label, the data will be filled with a placeholder value. This is typically `n... | calendar_dates = pd.date_range(start=start, end=end, freq='D')
print(calendar_dates) | DatetimeIndex(['2012-01-01', '2012-01-02', '2012-01-03', '2012-01-04',
'2012-01-05', '2012-01-06', '2012-01-07', '2012-01-08',
'2012-01-09', '2012-01-10',
...
'2015-12-23', '2015-12-24', '2015-12-25', '2015-12-26',
'2015-12-27', '2015-12-28', '2... | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Now let's use this new set of dates to reindex our time series. We tell the function that the fill method that we want is `ffill`. This denotes "forward fill". Any `NaN` values will be filled by the *last value* listed. So the price on the weekend or on a holiday will be listed as the price on the last market day that ... | calendar_prices = prices.reindex(calendar_dates, method='ffill')
calendar_prices.head(15) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
You'll notice that we still have a couple of `NaN` values right at the beginning of our time series. This is because the first of January in 2012 was a Sunday and the second was a market holiday! Because these are the earliest data points and we don't have any information from before them, they cannot be forward-filled... | meanfilled_prices = calendar_prices.fillna(calendar_prices.mean())
meanfilled_prices.head(10) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Using `fillna()` is fairly easy. It is just a matter of indicating the value that you want to fill the spaces with. Unfortunately, this particular case doesn't make a whole lot of sense, for reasons discussed in the lecture on stationarity in the Lecture series. We could fill them with with $0$, simply, but that's simi... | bfilled_prices = calendar_prices.fillna(method='bfill')
bfilled_prices.head(10) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
But again, this is a bad idea for the same reasons as the previous option. Both of these so-called solutions take into account *future data* that was not available at the time of the data points that we are trying to fill. In the case of using the mean or the median, these summary statistics are calculated by taking in... | dropped_prices = calendar_prices.dropna()
dropped_prices.head(10) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Now our time series is cleaned for the calendar year, with all of our `NaN` values properly handled. It is time to talk about how to actually do time series analysis with pandas data structures. Time Series Analysis with pandasLet's do some basic time series analysis on our original prices. Each pandas `Series` has a ... | prices.plot();
# We still need to add the axis labels and title ourselves
plt.title("XOM Prices")
plt.ylabel("Price")
plt.xlabel("Date"); | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
As well as some built-in descriptive statistics. We can either calculate these individually or using the `describe()` method. | print("Mean:", prices.mean())
print("Standard deviation:", prices.std())
print("Summary Statistics")
print(prices.describe()) | Summary Statistics
count 1006.000000
mean 86.777275
std 6.800729
min 68.116000
25% 82.356500
50% 85.377000
75% 91.559500
max 102.762000
Name: XOM, dtype: float64
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can easily modify `Series` with scalars using our basic mathematical operators. | modified_prices = prices * 2 - 10
modified_prices.head(5) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
And we can create linear combinations of `Series` themselves using the basic mathematical operators. pandas will group up matching indices and perform the calculations elementwise to produce a new `Series`. | noisy_prices = prices + 5 * pd.Series(np.random.normal(0, 5, len(prices)), index=prices.index) + 20
noisy_prices.head(5) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
If there are no matching indices, however, we may get an empty `Series` in return. | empty_series = prices + pd.Series(np.random.normal(0, 1, len(prices)))
empty_series.head(5) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Rather than looking at a time series itself, we may want to look at its first-order differences or percent change (in order to get additive or multiplicative returns, in our particular case). Both of these are built-in methods. | add_returns = prices.diff()[1:]
mult_returns = prices.pct_change()[1:]
plt.title("Multiplicative returns of XOM")
plt.xlabel("Date")
plt.ylabel("Percent Returns")
mult_returns.plot(); | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
pandas has convenient functions for calculating rolling means and standard deviations, as well! | rolling_mean = prices.rolling(30).mean()
rolling_mean.name = "30-day rolling mean"
prices.plot()
rolling_mean.plot()
plt.title("XOM Price")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend();
rolling_std = prices.rolling(30).std()
rolling_std.name = "30-day rolling volatility"
rolling_std.plot()
plt.title(rolling_std.... | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Many NumPy functions will work on `Series` the same way that they work on 1-dimensional NumPy arrays. | print(np.median(mult_returns)) | -0.000332104546511
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
The majority of these functions, however, are already implemented directly as `Series` and `DataFrame` methods. | print(mult_returns.median()) | -0.0003321045465112249
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
In every case, using the built-in pandas method will be better than using the NumPy function on a pandas data structure due to improvements in performance. Make sure to check out the `Series` [documentation](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html) before resorting to other calculations... | dict_data = {
'a' : [1, 2, 3, 4, 5],
'b' : ['L', 'K', 'J', 'M', 'Z'],
'c' : np.random.normal(0, 1, 5)
}
print(dict_data) | {'a': [1, 2, 3, 4, 5], 'b': ['L', 'K', 'J', 'M', 'Z'], 'c': array([-0.56478731, -0.54468815, -0.97128315, 0.73563591, -0.02876649])}
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Each `DataFrame` has a few key attributes that we need to keep in mind. The first of these is the index attribute. We can easily include an index of `Timestamp` objects like we did with `Series`. | frame_data = pd.DataFrame(dict_data, index=pd.date_range('2016-01-01', periods=5))
print(frame_data) | a b c
2016-01-01 1 L -0.564787
2016-01-02 2 K -0.544688
2016-01-03 3 J -0.971283
2016-01-04 4 M 0.735636
2016-01-05 5 Z -0.028766
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
As mentioned above, we can combine `Series` into `DataFrames`. Concatatenating `Series` like this will match elements up based on their corresponding index. As the following `Series` do not have an index assigned, they each default to an integer index. | s_1 = pd.Series([2, 4, 6, 8, 10], name='Evens')
s_2 = pd.Series([1, 3, 5, 7, 9], name="Odds")
numbers = pd.concat([s_1, s_2], axis=1)
print(numbers) | Evens Odds
0 2 1
1 4 3
2 6 5
3 8 7
4 10 9
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We will use `pandas.concat()` again later to combine multiple `DataFrame`s into one. Each `DataFrame` also has a `columns` attribute. These can either be assigned when we call `pandas.DataFrame` or they can be modified directly like the index. Note that when we concatenated the two `Series` above, the column names wer... | print(numbers.columns) | Index(['Evens', 'Odds'], dtype='object')
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
To modify the columns after object creation, we need only do the following: | numbers.columns = ['Shmevens', 'Shmodds']
print(numbers) | Shmevens Shmodds
0 2 1
1 4 3
2 6 5
3 8 7
4 10 9
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
In the same vein, the index of a `DataFrame` can be changed after the fact. | print(numbers.index)
numbers.index = pd.date_range("2016-01-01", periods=len(numbers))
print(numbers) | Shmevens Shmodds
2016-01-01 2 1
2016-01-02 4 3
2016-01-03 6 5
2016-01-04 8 7
2016-01-05 10 9
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Separate from the columns and index of a `DataFrame`, we can also directly access the values they contain by looking at the values attribute. | numbers.values | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
This returns a NumPy array. | type(numbers.values) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Accessing `DataFrame` elementsAgain we see a lot of carryover from `Series` in how we access the elements of `DataFrames`. The key sticking point here is that everything has to take into account multiple dimensions now. The main way that this happens is through the access of the columns of a `DataFrame`, either indivi... | securities = get_securities(symbols=['XOM', 'JNJ', 'MON', 'KKD'], vendors='usstock')
securities | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Since `get_securities` returns sids in the index, we can call the index's `tolist()` method to pass a list of sids to `get_prices`: | start = "2012-01-01"
end = "2017-01-01"
prices = get_prices("usstock-free-1min", data_frequency="daily", sids=securities.index.tolist(), start_date=start, end_date=end, fields="Close")
prices = prices.loc["Close"]
prices.head() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
For the purpose of this tutorial, it will be more convenient to reference the data by symbol instead of sid. To do this, we can create a Python dictionary mapping sid to symbol, and use the dictionary to rename the columns, using the DataFrame's `rename` method: | sids_to_symbols = securities.Symbol.to_dict()
prices = prices.rename(columns=sids_to_symbols)
prices.head() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Here we directly access the `XOM` column. Note that this style of access will only work if your column name has no spaces or unfriendly characters in it. | prices.XOM.head() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can also access the column using the column name in brackets: | prices["XOM"].head() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can also use `loc[]` to access an individual column like so. | prices.loc[:, 'XOM'].head() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Accessing an individual column will return a `Series`, regardless of how we get it. | print(type(prices.XOM))
print(type(prices.loc[:, 'XOM'])) | <class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
| CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Notice how we pass a tuple into the `loc[]` method? This is a key difference between accessing a `Series` and accessing a `DataFrame`, grounded in the fact that a `DataFrame` has multiple dimensions. When you pass a 2-dimensional tuple into a `DataFrame`, the first element of the tuple is applied to the rows and the se... | prices.loc[:, ['XOM', 'JNJ']].head() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can also simply access the `DataFrame` by index value using `loc[]`, as with `Series`. | prices.loc['2015-12-15':'2015-12-22'] | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
This plays nicely with lists of columns, too. | prices.loc['2015-12-15':'2015-12-22', ['XOM', 'JNJ']] | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Using `iloc[]` also works similarly, allowing you to access parts of the `DataFrame` by integer index. | prices.iloc[0:2, 1]
# Access prices with integer index in
# [1, 3, 5, 7, 9, 11, 13, ..., 99]
# and in column 0 or 2
prices.iloc[[1, 3, 5] + list(range(7, 100, 2)), [0, 2]].head(20) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Boolean indexingAs with `Series`, sometimes we want to filter a `DataFrame` according to a set of criteria. We do this by indexing our `DataFrame` with boolean values. | prices.loc[prices.MON > prices.JNJ].head() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can add multiple boolean conditions by using the logical operators `&`, `|`, and `~` (and, or, and not, respectively) again! | prices.loc[(prices.MON > prices.JNJ) & ~(prices.XOM > 66)].head() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.