prompt
stringlengths
19
1.03M
completion
stringlengths
4
2.12k
api
stringlengths
8
90
import collections.abc from pathlib import Path import pandas as pd import xml.etree.ElementTree as ET from io import BytesIO from typing import List, Union, Dict, Iterator from pandas import DataFrame from .types import UploadException, UploadedFile from .config import column_names import logging logger = logging.getLogger(__name__) class _BufferedUploadedFile(collections.abc.Mapping): def __init__(self, file, name, description): self.name = name self.description = description self.file = Path(file) if not self.file.is_file(): raise FileNotFoundError(f"{self.file} not found.") def __getitem__(self, k): if k == "name": return self.name elif k == "description": return self.description elif k == "fileText": with open(self.file, 'rb') as file: return file.read() else: raise AttributeError(f'{k} not found') def __len__(self) -> int: return 3 def __iter__(self) -> Iterator: pass def read_from_text(raw_files: List[UploadedFile]) -> Dict[str, DataFrame]: """ Reads from a raw list of files passed from javascript. These files are of the form e.g. [ {name: 'filename.csv', fileText: <file contents>, description: <upload metadata>} ] This function will try to catch most basic upload errors, and dispatch other errors to either the csv or xml reader based on the file extension. """ if len(raw_files) == 0: raise UploadException('No files uploaded!') extensions = list(set([f["name"][-3:].lower() for f in raw_files])) if len(extensions) != 1: raise UploadException(f'Mix of CSV and XML files found ({extensions})! Please reupload.') else: if extensions[0] == 'csv': return read_csvs_from_text(raw_files) elif extensions[0] == 'xml': return read_xml_from_text(raw_files[0]['fileText']) else: raise UploadException(f'Unknown file type {extensions[0]} found.') def read_files(files: Union[str, Path]) -> List[UploadedFile]: uploaded_files: List[_BufferedUploadedFile] = [] for filename in files: uploaded_files.append(_BufferedUploadedFile(file=filename, name=filename, description="This year")) return uploaded_files def read_csvs_from_text(raw_files: List[UploadedFile]) -> Dict[str, DataFrame]: def _get_file_type(df) -> str: for table_name, expected_columns in column_names.items(): if set(df.columns) == set(expected_columns): logger.info(f'Loaded {table_name} from CSV. ({len(df)} rows)') return table_name else: raise UploadException(f'Failed to match provided data ({list(df.columns)}) to known column names!') files = {} for file_data in raw_files: csv_file = BytesIO(file_data["fileText"]) df = pd.read_csv(csv_file) file_name = _get_file_type(df) if 'This year' in file_data['description']: name = file_name elif 'Prev year' in file_data['description']: name = file_name + '_last' else: raise UploadException(f'Unrecognized file description {file_data["description"]}') files[name] = df return files def read_xml_from_text(xml_string) -> Dict[str, DataFrame]: header_df = [] episodes_df = [] uasc_df = [] oc2_df = [] oc3_df = [] ad1_df = [] reviews_df = [] sbpfa_df = [] prev_perm_df = [] missing_df = [] def read_data(table): # The CHILDID tag needs to be renamed to CHILD to match the CSV # The PL tag needs to be renamed to PLACE to match the CSV conversions = { 'CHILDID': 'CHILD', 'PL': 'PLACE', } return { conversions.get(node.tag, node.tag): node.text for node in table.iter() if len(node) == 0 } def get_fields_for_table(all_data, table_name): def read_value(k): val = all_data.get(k, None) try: val = int(val) except: pass return val return pd.Series({k: read_value(k) for k in column_names[table_name]}) for child in ET.fromstring(xml_string): all_data = read_data(child) header_df.append(get_fields_for_table(all_data, 'Header')) if all_data.get('UASC', None) is not None: uasc_df.append(get_fields_for_table(all_data, 'UASC')) if all_data.get('IN_TOUCH', None) is not None: oc3_df.append(get_fields_for_table(all_data, 'OC3')) if all_data.get('DATE_INT', None) is not None: ad1_df.append(get_fields_for_table(all_data, 'AD1')) for table in child: if table.tag == 'EPISODE': data = read_data(table) episodes_df.append(get_fields_for_table({**all_data, **data}, 'Episodes')) elif table.tag == 'HEADER': for child_table in table: if child_table.tag == 'AREVIEW': data = read_data(child_table) reviews_df.append(get_fields_for_table({**all_data, **data}, 'Reviews')) elif child_table.tag == 'AMISSING': data = read_data(child_table) missing_df.append(get_fields_for_table({**all_data, **data}, 'Missing')) elif child_table.tag == 'OC2': data = read_data(child_table) oc2_df.append(get_fields_for_table({**all_data, **data}, 'OC2')) elif child_table.tag == 'PERMANENCE': data = read_data(child_table) prev_perm_df.append(get_fields_for_table({**all_data, **data}, 'PrevPerm')) elif child_table.tag == 'AD_PLACED': data = read_data(child_table) sbpfa_df.append(get_fields_for_table({**all_data, **data}, 'PlacedAdoption')) data = { 'Header':
pd.DataFrame(header_df)
pandas.DataFrame
import pandas as pd from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.cluster import KMeans from yellowbrick.cluster import KElbowVisualizer def principal_component_analysis(dragon_subset): ''' :param dragon_subset: Input Feature for Dragon data :return: Variance Captured across Principal Components ''' pipeline = Pipeline([('scaling', StandardScaler()), ('pca', PCA(n_components=200))]) X_PC = pipeline.fit_transform(dragon_subset) df_pc = pd.DataFrame(X_PC, columns=['PC_{}'.format(_) for _ in range(1, 201)])[['PC_1', 'PC_2']] df_pc.to_csv('df_principal_components.csv', index=False) df_variance = pd.DataFrame({'principal_component': ['PC_{}'.format(_) for _ in range(1, 201)], 'variance_captured': [round(_ * 100, 3) for _ in pipeline['pca'].explained_variance_ratio_]}) df_variance.to_csv('data/df_percent_variance_captured_in_PCA.csv', index=False) def kmeans(dragon_subset, target): ''' :param dragon_subset: Input Feature for Dragon data :param target: Output Feature (Density) :return: Data-Frame with Clusters ''' scaler_ = StandardScaler() scaler_.fit(dragon_subset) x_scaled = scaler_.transform(dragon_subset) k_means = KMeans() visualizer = KElbowVisualizer(k_means, k=(2, 11)) visualizer.fit(x_scaled) visualizer.show() kmeans_ = KMeans(n_clusters=4, random_state=42).fit(x_scaled) df_cluster = pd.concat([target,
pd.DataFrame({'label': kmeans_.labels_})
pandas.DataFrame
import tensorflow as tf import sys import json import numpy as np import pandas as pd #from hdfs.ext.kerberos import KerberosClient import os #import io #import gzip #import distkeras LEARNING_DECAY = 0.0 ADAMBETA1 = 0.9 ADAMBETA2 = 0.999 MOMENTUM = 0.0 model_file_path = sys.argv[1] loss = sys.argv[2] optimizer = sys.argv[3] data_path = sys.argv[4] select_status = sys.argv[5] epochs = int(sys.argv[6]) valid_rate = float(sys.argv[7]) learning_rate = float(sys.argv[8]) bagging_num = int(sys.argv[9]) if sys.argv[10] in ['false', 'False']: bagging_replace = False else: bagging_replace = True bagging_sample_rate = float(sys.argv[11]) print("Your NormalizedData Path is " + data_path + '\n') if optimizer == "sgd": optimizer = tf.keras.optimizers.SGD(lr=learning_rate,momentum=MOMENTUM,decay=LEARNING_DECAY) elif optimizer == "adam": optimizer = tf.keras.optimizers.Adam(lr=learning_rate, beta_1=ADAMBETA1, beta_2=ADAMBETA2, decay=LEARNING_DECAY) elif optimizer == "adagrad": optimizer = tf.keras.optimizers.Adagrad(lr=learning_rate, decay=LEARNING_DECAY) elif optimizer == "rmsprop": optimizer = tf.keras.optimizers.RMSprop(lr=learning_rate, decay=LEARNING_DECAY) elif optimizer == "nadam": optimizer = tf.keras.optimizers.Nadam(lr=learning_rate, beta_1=ADAMBETA1, beta_2=ADAMBETA2) if loss == "squared": loss = "mean_squared_error" elif loss == "absolute": loss = "mean_absolute_error" elif loss == "log": loss = "mean_squared_logarithmic_error" elif loss == "hinge": loss = "hinge" model = tf.keras.models.model_from_json(json.dumps(json.load(open(model_file_path)))) model.compile(optimizer=optimizer,loss=loss) data = pd.DataFrame() #client_hdfs = KerberosClient('http://' + os.environ['IP_HDFS'] + ':50070') #index = 1 for file in os.listdir(data_path): #if file.endswith('.gz'): # with client_hdfs.read(data_path+'/'+file) as reader: # reader=gzip.GzipFile(fileobj=io.BytesIO(reader.read())) tmp_data =
pd.read_csv(data_path+'/'+file, sep='|', header=None, dtype=np.float32)
pandas.read_csv
from typing import List import pandas as pd from shapely.geometry import Polygon import matplotlib.pyplot as plt import geopy.distance import pypsa from epippy.geographics import get_shapes, get_subregions from epippy.topologies.core.plot import plot_topology from epippy.technologies import get_costs def upgrade_topology(net: pypsa.Network, regions: List[str], plot: bool = False, ac_carrier: str = "HVAC_OHL", dc_carrier: str = "HVDC_GLIS") -> pypsa.Network: buses =
pd.DataFrame(columns=["x", "y", "country", "onshore_region", "offshore_region"])
pandas.DataFrame
# coding: utf-8 # In[1]: #I import the libraries I may need import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn as skl import json import gzip # #### Loading and preparing the dataset # In[2]: f = gzip.open("C:/Users/Marta/Desktop/AppDataScience_data.gz", "rb") print(type(f)) # In[3]: #Opening the file, it is a string with gzip.open("C:/Users/Marta/Desktop/AppDataScience_data.gz", "rb") as f: data = json.loads(json.dumps(f.read().decode("ascii"))) type(data) # In[4]: #Lets have a look. It is a string, we want to end up with a list of dictionaries print(data[0:600]) print('\n') print(data[-600:-1]) # In[5]: #We split into a list datalist = data.split('\n') # In[6]: #Lets check the beggining and the end; we do not like the end. print(datalist[0],'\n',datalist[-1]) # In[7]: #Removing the last one, and checking it looks ok now datalist = datalist[:-1] print(datalist[0],'\n',datalist[-1]) # In[8]: #We change the data to a list of dictionaries import ast dictlist = [ast.literal_eval(i) for i in datalist] # In[9]: #Checking all is at it should... print(dictlist[0],'\n',dictlist[-1]) # In[10]: #going to dataframe and having a first look dataframe = pd.DataFrame(dictlist) print(dataframe.head(5),'\n\n', dataframe.tail(5),'\n') print(type(dataframe),'\n',dataframe.shape,'\n',dataframe.dtypes) # In[11]: #Lets check if there are missing values, null, na or nan. There are not! dataframe.isnull().sum().sum() # In[12]: #We have 1664 distinct client ids len(dataframe.client_id.unique()) # In[13]: #And those are the distinct event types print(dataframe.event_type.unique(),'\n',len(dataframe.event_type.unique())) # ## First question: # A toplist of different event_types where we count number of unique # client_ids per event_type # In[14]: clients_per_event = dataframe.groupby('event_type')['client_id'].nunique() type(clients_per_event) # In[15]: #Here are the distinct event types sorted per number of distinct client id clients_per_event.sort_values(ascending= False) # In[16]: # A top 10 list in proportion sortedlist = clients_per_event.sort_values(ascending= False)/len(dataframe.client_id.unique()) sortedlist.head(10) # ## Second question: # For how long does the median user use the app? # In[17]: #what I made up for puting 0 as the first event we have from a particular user, as example anuser = dataframe[dataframe['client_id']=='f64a315b07']['timestamp'] anuser_normsort = ((anuser-anuser.min())/3600000.0).sort_values() anuser_normsort.hist(bins=60 ,xlabelsize=10) plt.show() # In[18]: #I want to put it in an array, and take the difference in time between actions anuser_array = anuser_normsort.values diff = anuser_array[1:]-anuser_array[:-1] # In[19]: #Now, for an user, I can obtain the mean time in the app, considering that no action during 30 min implies no use #Without kwoing more details about the app, I can not judge if 30 minutes is reasonable; maybe 10 o even 5 minutes of #no activity is already a new login, and the results can change a lot... alterate the command "sep" with the number #of minutes you consider reasonable for a "new use of the app" j = 1 smallsum = 0 bigsum = 0 sep = 30 for i in diff: if i < (sep/60): smallsum=smallsum+i else: bigsum=bigsum+smallsum j=j+1 smallsum=0 usermean=(bigsum+smallsum)/j print(usermean*60)#This is in minutes #To see the differences in time pd.Series(diff).hist(bins=244 ,xlabelsize=10) plt.show() # The previous was a particular case for me to understand the data and identify potential problems. Now, we generalize: # In[20]: dataframe['client_id'].unique() # In[21]: #for any particular user #As a rule of thumb and with some robutness criterias, I have end up considering inactivity of more than 5 minutes #as new ussage usermeanlist = [] for i in dataframe['client_id'].unique(): anuser = dataframe[dataframe['client_id']== i ]['timestamp'] anuser_normsort = ((anuser-anuser.min())/3600000.0).sort_values() anuser_array = anuser_normsort.values diff = anuser_array[1:]-anuser_array[:-1] j = 1 smallsum = 0 bigsum = 0 sep = 5 #This parameter is the numer of minutes of innactivity we allow until consider "new ussage" for k in diff: if k < (sep/60): smallsum=smallsum+k else: bigsum=bigsum+smallsum j=j+1 smallsum=0 usermean=(bigsum+smallsum)/j usermeanlist.append(usermean*60) #to have it in minutes # In[22]: #I calculate the mean and standard deviation, to have an idea of the scale and robustness a = np.array(usermeanlist).mean() b = np.array(usermeanlist).std() print(a,b) # In[23]: #To see the differences in time. It is exponential, that was expected.
pd.Series(usermeanlist)
pandas.Series
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import os import re from concurrent.futures import ProcessPoolExecutor import matplotlib.pyplot as plt import pandas as pd from pmdarima import arima from pmdarima.model_selection import train_test_split from sklearn.metrics import r2_score def adjust_date(s): t = s.split("/") return f"20{t[2]}-{int(t[0]):02d}-{int(t[1]):02d}" def adjust_name(s): return re.sub(r"\*|\,|\(|\)|\*|\ |\'", "_", s) def draw(country): draw_(country, True) draw_(country, False) def draw_(country, isDaily): # 模型训练 model = arima.AutoARIMA( start_p=0, max_p=4, d=None, start_q=0, max_q=1, start_P=0, max_P=1, D=None, start_Q=0, max_Q=1, m=7, seasonal=True, test="kpss", trace=True, error_action="ignore", suppress_warnings=True, stepwise=True, ) if isDaily: data = df[country].diff().dropna() model.fit(data) else: data = df[country] model.fit(data) # 模型验证 train, test = train_test_split(data, train_size=0.8) pred_test = model.predict_in_sample(start=train.shape[0], dynamic=False) validating = pd.Series(pred_test, index=test.index) r2 = r2_score(test, pred_test) # 开始预测 pred, pred_ci = model.predict(n_periods=14, return_conf_int=True) idx = pd.date_range(data.index.max() +
pd.Timedelta("1D")
pandas.Timedelta
# import libraries import sys from sqlalchemy import create_engine import pandas as pd import numpy as np import re from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer import nltk nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger','stopwords']) from sklearn.multioutput import MultiOutputClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, precision_recall_fscore_support from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.base import BaseEstimator, TransformerMixin from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer import pickle def load_data(database_filepath): """ function: Load data from database input: database_filepath: file name and path of data table output: X: 1D dataframe containing messages Y: 2D dataframe containing numeric category labels category_names: List of category names """ # load data from database engine = create_engine('sqlite:///{}'.format(database_filepath)) # check table names in the database print(engine.table_names()) # find the data table name path_str=database_filepath.split('/') for name in path_str : if name.find('.db'): datatable_name=name.split('.')[0] print(datatable_name) # read table from database df = pd.read_sql_table(datatable_name, engine) # close the connection to the database conn = engine.raw_connection() conn.close() # Extract X and Y X = df['message'] # Drop non-category features Y = df.drop(['id', 'message','original', 'genre'], axis = 1) # Replace "2" in Y to "0" to simplify classification Y[Y>=2]=0 ## Y=Y.replace(to_replace ='2', value ='0') # if Y.dtypes is not int # Get category names category_names = Y.columns return X, Y, category_names def tokenize(text): """ function: Tokenize text input: text: text string output: clean_tokens: list of clean text tokens """ url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' detected_urls = re.findall(url_regex, text) for url in detected_urls: text = text.replace(url, "urlplaceholder") # Only consider word which is alphanumeric and not in stopwords tokens = [ w for w in word_tokenize(text) if (w.isalnum()) & (w not in nltk.corpus.stopwords.words("english")) ] lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok = lemmatizer.lemmatize(tok).lower().strip() clean_tokens.append(clean_tok) return clean_tokens class StartingVerbExtractor(BaseEstimator, TransformerMixin): """ class: part-of-speach tagging """ def starting_verb(self, text): """ function: Tokenize text and assign numeric tags 0/1 to each token input: text: text string output: 0/1: integer tag """ sentence_list = nltk.sent_tokenize(text) for sentence in sentence_list: pos_tags = nltk.pos_tag(tokenize(sentence)) # part-of-speech tagging if pos_tags != []: # skip one-letter text with no tag first_word, first_tag = pos_tags[0] if first_tag in ['VB', 'VBP'] or first_word == 'RT': return 1 return 0 def fit(self, x, y=None): """ function: fit StartingVerbExtractor model """ return self def transform(self, X): """ function: transform text input into numeric tags in dataframe input: X: dataframe containing text output: X_tagged: dataframe containing numeric tags """ X_tagged =
pd.Series(X)
pandas.Series
#!/usr/bin/env python # coding: utf-8 # ## Compile dataset of clones resistant to other drugs # # **<NAME>, 2021** # # **<NAME>, 2021** # # This script is modified from Greg Way's original scripts of 8.compile-otherclone-dataset. # # This dataset includes new batches of 24~27 including WT (10, 12-15, parental) and Bz-resistant (6-10, A&E) clones. # They are DMSO-treated clones to later apply the bortezomib resistance signature. These clone types are either sensitive (WT) or resistance (BZ) to bortezomib. Clones A and E as resistant to bortezomib, and the WT parental would score somewhere in the "sensitive to bortezomib" range, since they are a heterogenous population but should mostly be composed of sensitive cells. # In[1]: import sys import pathlib import numpy as np import pandas as pd from pycytominer.cyto_utils import infer_cp_features sys.path.insert(0, "../2.describe-data/scripts") from processing_utils import load_data # In[2]: np.random.seed(1234) # In[3]: data_dir = pathlib.Path("../0.generate-profiles/profiles") cell_count_dir = pathlib.Path("../0.generate-profiles/cell_counts/") output_dir = pathlib.Path("data") profile_suffix = "normalized.csv.gz" # In[4]: datasets_val = { "2021_08_02_Batch24": ["221057"], "2021_08_02_Batch25": ["221058"], "2021_08_03_Batch26": ["221093"], "2021_08_03_Batch27": ["221094"], } # In[5]: #added 'val' to each original variable names from 8.0 full_df_val = [] for dataset_val in datasets_val: dataset_df_val = [] for batch in datasets_val: plates = datasets_val[batch] df_val = load_data( batch=batch, plates=plates, profile_dir=data_dir, suffix=profile_suffix, combine_dfs=True, harmonize_cols=True, add_cell_count=True, cell_count_dir=cell_count_dir ) # Add important metadata features df_val = df_val.assign( Metadata_dataset=dataset_val, Metadata_batch=batch, Metadata_clone_type="resistant", Metadata_clone_type_indicator=1, Metadata_model_split="otherclone" ) df_val.loc[df_val.Metadata_clone_number.str.contains("WT"), "Metadata_clone_type"] = "sensitive" df_val.loc[df_val.Metadata_clone_number.str.contains("WT"), "Metadata_clone_type_indicator"] = 0 dataset_df_val.append(df_val) # Merge plates of the same dataset together dataset_df_val = pd.concat(dataset_df_val, axis="rows", sort=False).reset_index(drop=True) # Generate a unique sample ID # (This will be used in singscore calculation) dataset_df_val = dataset_df_val.assign( Metadata_unique_sample_name=[f"profile_{x}_{dataset_val}" for x in range(0, dataset_df_val.shape[0])] ) full_df_val.append(dataset_df_val) #remove other clone types from the df full_df_val = pd.concat(full_df_val, axis="rows", sort=False).reset_index(drop=True) tx_clones = [ "TX clone 2", "TX clone 3", "TX clone 4", "TX clone 5", "TX clone 6", ] full_df_val = full_df_val.query("Metadata_clone_number not in @tx_clones") # In[6]: full_df_val.head() # In[7]: # Reorder features common_metadata = infer_cp_features(full_df_val, metadata=True) morph_features = infer_cp_features(full_df_val) full_df_val = full_df_val.reindex(common_metadata + morph_features, axis="columns") print(full_df_val.shape) # In[8]:
pd.crosstab(full_df_val.Metadata_clone_type_indicator, full_df_val.Metadata_model_split)
pandas.crosstab
""" Copyright 2019 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import datetime import datetime as dt import os from typing import Union import numpy as np import pandas as pd import pytest import pytz from gs_quant.target.common import XRef, PricingLocation, Currency as CurrEnum from numpy.testing import assert_allclose from pandas.testing import assert_series_equal from pandas.tseries.offsets import CustomBusinessDay from pytz import timezone from testfixtures import Replacer from testfixtures.mock import Mock import gs_quant.timeseries.measures as tm import gs_quant.timeseries.measures_rates as tm_rates from gs_quant.api.gs.assets import GsTemporalXRef, GsAssetApi, GsIdType, IdList, GsAsset from gs_quant.api.gs.data import GsDataApi, MarketDataResponseFrame from gs_quant.api.gs.data import QueryType from gs_quant.data.core import DataContext from gs_quant.data.dataset import Dataset from gs_quant.data.fields import Fields from gs_quant.errors import MqError, MqValueError, MqTypeError from gs_quant.markets.securities import AssetClass, Cross, Index, Currency, SecurityMaster, Stock, \ Swap, CommodityNaturalGasHub from gs_quant.session import GsSession, Environment from gs_quant.test.timeseries.utils import mock_request from gs_quant.timeseries import Returns from gs_quant.timeseries.measures import BenchmarkType _index = [pd.Timestamp('2019-01-01')] _test_datasets = ('TEST_DATASET',) def mock_empty_market_data_response(): df = MarketDataResponseFrame() df.dataset_ids = () return df def map_identifiers_default_mocker(input_type: Union[GsIdType, str], output_type: Union[GsIdType, str], ids: IdList, as_of: dt.datetime = None, multimap: bool = False, limit: int = None, **kwargs ) -> dict: if "USD-LIBOR-BBA" in ids: return {"USD-LIBOR-BBA": "MAPDB7QNB2TZVQ0E"} elif "EUR-EURIBOR-TELERATE" in ids: return {"EUR-EURIBOR-TELERATE": "MAJNQPFGN1EBDHAE"} elif "GBP-LIBOR-BBA" in ids: return {"GBP-LIBOR-BBA": "MAFYB8Z4R1377A19"} elif "JPY-LIBOR-BBA" in ids: return {"JPY-LIBOR-BBA": "MABMVE27EM8YZK33"} elif "EUR OIS" in ids: return {"EUR OIS": "MARFAGXDQRWM07Y2"} def map_identifiers_swap_rate_mocker(input_type: Union[GsIdType, str], output_type: Union[GsIdType, str], ids: IdList, as_of: dt.datetime = None, multimap: bool = False, limit: int = None, **kwargs ) -> dict: if "USD-3m" in ids: return {"USD-3m": "MAAXGV0GZTW4GFNC"} elif "EUR-6m" in ids: return {"EUR-6m": "MA5WM2QWRVMYKDK0"} elif "KRW" in ids: return {"KRW": 'MAJ6SEQH3GT0GA2Z'} def map_identifiers_inflation_mocker(input_type: Union[GsIdType, str], output_type: Union[GsIdType, str], ids: IdList, as_of: dt.datetime = None, multimap: bool = False, limit: int = None, **kwargs ) -> dict: if "CPI-UKRPI" in ids: return {"CPI-UKRPI": "MAQ7ND0MBP2AVVQW"} elif "CPI-CPXTEMU" in ids: return {"CPI-CPXTEMU": "MAK1FHKH5P5GJSHH"} def map_identifiers_cross_basis_mocker(input_type: Union[GsIdType, str], output_type: Union[GsIdType, str], ids: IdList, as_of: dt.datetime = None, multimap: bool = False, limit: int = None, **kwargs ) -> dict: if "USD-3m/JPY-3m" in ids: return {"USD-3m/JPY-3m": "MA99N6C1KF9078NM"} elif "EUR-3m/USD-3m" in ids: return {"EUR-3m/USD-3m": "MAXPKTXW2D4X6MFQ"} elif "GBP-3m/USD-3m" in ids: return {"GBP-3m/USD-3m": "MA8BZHQV3W32V63B"} def get_data_policy_rate_expectation_mocker( start: Union[dt.date, dt.datetime] = None, end: Union[dt.date, dt.datetime] = None, as_of: dt.datetime = None, since: dt.datetime = None, fields: Union[str, Fields] = None, asset_id_type: str = None, **kwargs) -> pd.DataFrame: if 'meetingNumber' in kwargs: if kwargs['meetingNumber'] == 0: return mock_meeting_spot() elif 'meeting_date' in kwargs: if kwargs['meeting_date'] == dt.date(2019, 10, 24): return mock_meeting_spot() return mock_meeting_expectation() def test_parse_meeting_date(): assert tm.parse_meeting_date(5) == '' assert tm.parse_meeting_date('') == '' assert tm.parse_meeting_date('test') == '' assert tm.parse_meeting_date('2019-09-01') == dt.date(2019, 9, 1) def test_currency_to_default_benchmark_rate(mocker): mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(GsAssetApi, 'map_identifiers', side_effect=map_identifiers_default_mocker) asset_id_list = ["MAZ7RWC904JYHYPS", "MAJNQPFGN1EBDHAE", "MA66CZBQJST05XKG", "MAK1FHKH5P5GJSHH", "MA4J1YB8XZP2BPT8", "MA4B66MW5E27U8P32SB"] correct_mapping = ["MAPDB7QNB2TZVQ0E", "MAJNQPFGN1EBDHAE", "MAFYB8Z4R1377A19", "MABMVE27EM8YZK33", "MA4J1YB8XZP2BPT8", "MA4B66MW5E27U8P32SB"] with tm.PricingContext(dt.date.today()): for i in range(len(asset_id_list)): correct_id = tm.currency_to_default_benchmark_rate(asset_id_list[i]) assert correct_id == correct_mapping[i] def test_currency_to_default_swap_rate_asset(mocker): mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(GsAssetApi, 'map_identifiers', side_effect=map_identifiers_swap_rate_mocker) asset_id_list = ['MAZ7RWC904JYHYPS', 'MAJNQPFGN1EBDHAE', 'MAJ6SEQH3GT0GA2Z'] correct_mapping = ['MAAXGV0GZTW4GFNC', 'MA5WM2QWRVMYKDK0', 'MAJ6SEQH3GT0GA2Z'] with tm.PricingContext(dt.date.today()): for i in range(len(asset_id_list)): correct_id = tm.currency_to_default_swap_rate_asset(asset_id_list[i]) assert correct_id == correct_mapping[i] def test_currency_to_inflation_benchmark_rate(mocker): mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(GsAssetApi, 'map_identifiers', side_effect=map_identifiers_inflation_mocker) asset_id_list = ["MA66CZBQJST05XKG", "MAK1FHKH5P5GJSHH", "MA4J1YB8XZP2BPT8"] correct_mapping = ["MAQ7ND0MBP2AVVQW", "MAK1FHKH5P5GJSHH", "MA4J1YB8XZP2BPT8"] with tm.PricingContext(dt.date.today()): for i in range(len(asset_id_list)): correct_id = tm.currency_to_inflation_benchmark_rate(asset_id_list[i]) assert correct_id == correct_mapping[i] # Test that the same id is returned when a TypeError is raised mocker.patch.object(GsAssetApi, 'map_identifiers', side_effect=TypeError('Test')) assert tm.currency_to_inflation_benchmark_rate('MA66CZBQJST05XKG') == 'MA66CZBQJST05XKG' def test_cross_to_basis(mocker): mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(GsAssetApi, 'map_identifiers', side_effect=map_identifiers_cross_basis_mocker) asset_id_list = ["MAYJPCVVF2RWXCES", "MA4B66MW5E27U8P32SB", "nobbid"] correct_mapping = ["MA99N6C1KF9078NM", "MA4B66MW5E27U8P32SB", "nobbid"] with tm.PricingContext(dt.date.today()): for i in range(len(asset_id_list)): correct_id = tm.cross_to_basis(asset_id_list[i]) assert correct_id == correct_mapping[i] # Test that the same id is returned when a TypeError is raised mocker.patch.object(GsAssetApi, 'map_identifiers', side_effect=TypeError('Test')) assert tm.cross_to_basis('MAYJPCVVF2RWXCES') == 'MAYJPCVVF2RWXCES' def test_currency_to_tdapi_swap_rate_asset(mocker): replace = Replacer() mocker.patch.object(GsSession.__class__, 'current', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(SecurityMaster, 'get_asset', side_effect=mock_request) bbid_mock = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) with tm.PricingContext(dt.date.today()): asset = Currency('MA25DW5ZGC1BSC8Y', 'NOK') bbid_mock.return_value = 'NOK' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) asset = Currency('MAZ7RWC904JYHYPS', 'USD') bbid_mock.return_value = 'USD' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MAFRSWPAF5QPNTP2' == correct_id bbid_mock.return_value = 'CHF' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MAW25BGQJH9P6DPT' == correct_id bbid_mock.return_value = 'EUR' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MAA9MVX15AJNQCVG' == correct_id bbid_mock.return_value = 'GBP' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MA6QCAP9B7ABS9HA' == correct_id bbid_mock.return_value = 'JPY' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MAEE219J5ZP0ZKRK' == correct_id bbid_mock.return_value = 'SEK' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MAETMVTPNP3199A5' == correct_id bbid_mock.return_value = 'HKD' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MABRNGY8XRFVC36N' == correct_id bbid_mock.return_value = 'NZD' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MAH16NHE1HBN0FBZ' == correct_id bbid_mock.return_value = 'AUD' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MAY8147CRK0ZP53B' == correct_id bbid_mock.return_value = 'CAD' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MANJ8SS88WJ6N28Q' == correct_id bbid_mock.return_value = 'KRW' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MAP55AXG5SQVS6C5' == correct_id bbid_mock.return_value = 'INR' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MA20JHJXN1PD5HGE' == correct_id bbid_mock.return_value = 'CNY' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MA4K1D8HH2R0RQY5' == correct_id bbid_mock.return_value = 'SGD' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MA5CQFHYBPH9E5BS' == correct_id bbid_mock.return_value = 'DKK' correct_id = tm_rates._currency_to_tdapi_swap_rate_asset(asset) assert 'MAF131NKWVRESFYA' == correct_id asset = Currency('MA890', 'PLN') bbid_mock.return_value = 'PLN' assert 'MA890' == tm_rates._currency_to_tdapi_swap_rate_asset(asset) replace.restore() def test_currency_to_tdapi_basis_swap_rate_asset(mocker): replace = Replacer() mocker.patch.object(GsSession.__class__, 'current', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(SecurityMaster, 'get_asset', side_effect=mock_request) bbid_mock = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) with tm.PricingContext(dt.date.today()): asset = Currency('MA890', 'NOK') bbid_mock.return_value = 'NOK' assert 'MA890' == tm_rates._currency_to_tdapi_basis_swap_rate_asset(asset) asset = Currency('MAZ7RWC904JYHYPS', 'USD') bbid_mock.return_value = 'USD' correct_id = tm_rates._currency_to_tdapi_basis_swap_rate_asset(asset) assert 'MAQB1PGEJFCET3GG' == correct_id bbid_mock.return_value = 'EUR' correct_id = tm_rates._currency_to_tdapi_basis_swap_rate_asset(asset) assert 'MAGRG2VT11GQ2RQ9' == correct_id bbid_mock.return_value = 'GBP' correct_id = tm_rates._currency_to_tdapi_basis_swap_rate_asset(asset) assert 'MAHCYNB3V75JC5Q8' == correct_id bbid_mock.return_value = 'JPY' correct_id = tm_rates._currency_to_tdapi_basis_swap_rate_asset(asset) assert 'MAXVRBEZCJVH0C4V' == correct_id replace.restore() def test_check_clearing_house(): assert tm_rates._ClearingHouse.LCH == tm_rates._check_clearing_house('lch') assert tm_rates._ClearingHouse.CME == tm_rates._check_clearing_house(tm_rates._ClearingHouse.CME) assert tm_rates._ClearingHouse.LCH == tm_rates._check_clearing_house(None) invalid_ch = ['NYSE'] for ch in invalid_ch: with pytest.raises(MqError): tm_rates._check_clearing_house(ch) def test_get_swap_csa_terms(): euribor_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['EUR'][BenchmarkType.EURIBOR.value] usd_libor_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD'][BenchmarkType.LIBOR.value] fed_funds_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD'][BenchmarkType.Fed_Funds.value] estr_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['EUR'][BenchmarkType.EUROSTR.value] assert dict(csaTerms='USD-1') == tm_rates._get_swap_csa_terms('USD', fed_funds_index) assert dict(csaTerms='EUR-EuroSTR') == tm_rates._get_swap_csa_terms('EUR', estr_index) assert {} == tm_rates._get_swap_csa_terms('EUR', euribor_index) assert {} == tm_rates._get_swap_csa_terms('USD', usd_libor_index) def test_get_basis_swap_csa_terms(): euribor_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['EUR'][BenchmarkType.EURIBOR.value] usd_libor_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD'][BenchmarkType.LIBOR.value] fed_funds_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD'][BenchmarkType.Fed_Funds.value] sofr_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD'][BenchmarkType.SOFR.value] estr_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['EUR'][BenchmarkType.EUROSTR.value] eonia_index = tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['EUR'][BenchmarkType.EONIA.value] assert dict(csaTerms='USD-1') == tm_rates._get_basis_swap_csa_terms('USD', fed_funds_index, sofr_index) assert dict(csaTerms='EUR-EuroSTR') == tm_rates._get_basis_swap_csa_terms('EUR', estr_index, eonia_index) assert {} == tm_rates._get_basis_swap_csa_terms('EUR', eonia_index, euribor_index) assert {} == tm_rates._get_basis_swap_csa_terms('USD', fed_funds_index, usd_libor_index) def test_match_floating_tenors(): swap_args = dict(asset_parameters_payer_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD']['LIBOR'], asset_parameters_payer_designated_maturity='3m', asset_parameters_receiver_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD']['SOFR'], asset_parameters_receiver_designated_maturity='1y') assert '3m' == tm_rates._match_floating_tenors(swap_args)['asset_parameters_receiver_designated_maturity'] swap_args = dict(asset_parameters_payer_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD']['SOFR'], asset_parameters_payer_designated_maturity='1y', asset_parameters_receiver_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD']['LIBOR'], asset_parameters_receiver_designated_maturity='3m') assert '3m' == tm_rates._match_floating_tenors(swap_args)['asset_parameters_payer_designated_maturity'] swap_args = dict(asset_parameters_payer_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['GBP']['SONIA'], asset_parameters_payer_designated_maturity='1y', asset_parameters_receiver_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['GBP']['LIBOR'], asset_parameters_receiver_designated_maturity='3m') assert '3m' == tm_rates._match_floating_tenors(swap_args)['asset_parameters_payer_designated_maturity'] swap_args = dict(asset_parameters_payer_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['GBP']['LIBOR'], asset_parameters_payer_designated_maturity='3m', asset_parameters_receiver_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['GBP']['SONIA'], asset_parameters_receiver_designated_maturity='1y') assert '3m' == tm_rates._match_floating_tenors(swap_args)['asset_parameters_receiver_designated_maturity'] swap_args = dict(asset_parameters_payer_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD']['LIBOR'], asset_parameters_payer_designated_maturity='3m', asset_parameters_receiver_rate_option=tm_rates.CURRENCY_TO_SWAP_RATE_BENCHMARK['USD']['LIBOR'], asset_parameters_receiver_designated_maturity='6m') assert swap_args == tm_rates._match_floating_tenors(swap_args) def test_get_term_struct_date(mocker): today = datetime.datetime.today() biz_day = CustomBusinessDay() assert today == tm_rates._get_term_struct_date(tenor=today, index=today, business_day=biz_day) date_index = datetime.datetime(2020, 7, 31, 0, 0) assert date_index == tm_rates._get_term_struct_date(tenor='2020-07-31', index=date_index, business_day=biz_day) assert date_index == tm_rates._get_term_struct_date(tenor='0b', index=date_index, business_day=biz_day) assert datetime.datetime(2021, 7, 30, 0, 0) == tm_rates._get_term_struct_date(tenor='1y', index=date_index, business_day=biz_day) def test_cross_stored_direction_for_fx_vol(mocker): mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(GsSession.current, '_post', side_effect=mock_request) asset_id_list = ["MAYJPCVVF2RWXCES", "MATGYV0J9MPX534Z"] correct_mapping = ["MATGYV0J9MPX534Z", "MATGYV0J9MPX534Z"] with tm.PricingContext(dt.date.today()): for i in range(len(asset_id_list)): correct_id = tm.cross_stored_direction_for_fx_vol(asset_id_list[i]) assert correct_id == correct_mapping[i] def test_cross_to_usd_based_cross_for_fx_forecast(mocker): mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(GsSession.current, '_post', side_effect=mock_request) asset_id_list = ["MAYJPCVVF2RWXCES", "MATGYV0J9MPX534Z"] correct_mapping = ["MATGYV0J9MPX534Z", "MATGYV0J9MPX534Z"] with tm.PricingContext(dt.date.today()): for i in range(len(asset_id_list)): correct_id = tm.cross_to_usd_based_cross(asset_id_list[i]) assert correct_id == correct_mapping[i] def test_cross_to_used_based_cross(mocker): mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(GsSession.current, '_post', side_effect=mock_request) mocker.patch.object(SecurityMaster, 'get_asset', side_effect=TypeError('unsupported')) replace = Replacer() bbid_mock = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) bbid_mock.return_value = 'HELLO' assert 'FUN' == tm.cross_to_usd_based_cross(Cross('FUN', 'EURUSD')) replace.restore() def test_cross_stored_direction(mocker): mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', side_effect=mock_request) mocker.patch.object(GsSession.current, '_post', side_effect=mock_request) mocker.patch.object(SecurityMaster, 'get_asset', side_effect=TypeError('unsupported')) replace = Replacer() bbid_mock = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) bbid_mock.return_value = 'HELLO' assert 'FUN' == tm.cross_stored_direction_for_fx_vol(Cross('FUN', 'EURUSD')) replace.restore() def test_get_tdapi_rates_assets(mocker): mock_asset_1 = GsAsset(asset_class='Rate', id='MAW25BGQJH9P6DPT', type_='Swap', name='Test_asset') mock_asset_2 = GsAsset(asset_class='Rate', id='MAA9MVX15AJNQCVG', type_='Swap', name='Test_asset') mock_asset_3 = GsAsset(asset_class='Rate', id='MANQHVYC30AZFT7R', type_='BasisSwap', name='Test_asset') replace = Replacer() assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1] assert 'MAW25BGQJH9P6DPT' == tm_rates._get_tdapi_rates_assets() replace.restore() assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1, mock_asset_2] kwargs = dict(asset_parameters_termination_date='10y', asset_parameters_effective_date='0b') with pytest.raises(MqValueError): tm_rates._get_tdapi_rates_assets(**kwargs) replace.restore() assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [] with pytest.raises(MqValueError): tm_rates._get_tdapi_rates_assets() replace.restore() assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1, mock_asset_2] kwargs = dict() assert ['MAW25BGQJH9P6DPT', 'MAA9MVX15AJNQCVG'] == tm_rates._get_tdapi_rates_assets(**kwargs) replace.restore() # test case will test matching sofr maturity with libor leg and flipping legs to get right asset kwargs = dict(type='BasisSwap', asset_parameters_termination_date='10y', asset_parameters_payer_rate_option=BenchmarkType.LIBOR, asset_parameters_payer_designated_maturity='3m', asset_parameters_receiver_rate_option=BenchmarkType.SOFR, asset_parameters_receiver_designated_maturity='1y', asset_parameters_clearing_house='lch', asset_parameters_effective_date='Spot', asset_parameters_notional_currency='USD', pricing_location='NYC') assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_3] assert 'MANQHVYC30AZFT7R' == tm_rates._get_tdapi_rates_assets(**kwargs) replace.restore() def test_get_swap_leg_defaults(): result_dict = dict(currency=CurrEnum.JPY, benchmark_type='JPY-LIBOR-BBA', floating_rate_tenor='6m', pricing_location=PricingLocation.TKO) defaults = tm_rates._get_swap_leg_defaults(CurrEnum.JPY) assert result_dict == defaults result_dict = dict(currency=CurrEnum.USD, benchmark_type='USD-LIBOR-BBA', floating_rate_tenor='3m', pricing_location=PricingLocation.NYC) defaults = tm_rates._get_swap_leg_defaults(CurrEnum.USD) assert result_dict == defaults result_dict = dict(currency=CurrEnum.EUR, benchmark_type='EUR-EURIBOR-TELERATE', floating_rate_tenor='6m', pricing_location=PricingLocation.LDN) defaults = tm_rates._get_swap_leg_defaults(CurrEnum.EUR) assert result_dict == defaults result_dict = dict(currency=CurrEnum.SEK, benchmark_type='SEK-STIBOR-SIDE', floating_rate_tenor='6m', pricing_location=PricingLocation.LDN) defaults = tm_rates._get_swap_leg_defaults(CurrEnum.SEK) assert result_dict == defaults def test_check_forward_tenor(): valid_tenors = [datetime.date(2020, 1, 1), '1y', 'imm2', 'frb2', '1m', '0b'] for tenor in valid_tenors: assert tenor == tm_rates._check_forward_tenor(tenor) invalid_tenors = ['5yr', 'imm5', 'frb0'] for tenor in invalid_tenors: with pytest.raises(MqError): tm_rates._check_forward_tenor(tenor) def mock_commod(_cls, _q): d = { 'price': [30, 30, 30, 30, 35.929686, 35.636039, 27.307498, 23.23177, 19.020833, 18.827291, 17.823749, 17.393958, 17.824999, 20.307603, 24.311249, 25.160103, 25.245728, 25.736873, 28.425206, 28.779789, 30.519996, 34.896348, 33.966973, 33.95489, 33.686348, 34.840307, 32.674163, 30.261665, 30, 30, 30] } df = MarketDataResponseFrame(data=d, index=pd.date_range('2019-05-01', periods=31, freq='H', tz=timezone('UTC'))) df.dataset_ids = _test_datasets return df def mock_forward_price(_cls, _q): d = { 'forwardPrice': [ 22.0039, 24.8436, 24.8436, 11.9882, 14.0188, 11.6311, 18.9234, 21.3654, 21.3654, ], 'quantityBucket': [ "PEAK", "PEAK", "PEAK", "7X8", "7X8", "7X8", "2X16H", "2X16H", "2X16H", ], 'contract': [ "J20", "K20", "M20", "J20", "K20", "M20", "J20", "K20", "M20", ] } df = MarketDataResponseFrame(data=d, index=pd.to_datetime([datetime.date(2019, 1, 2)] * 9)) df.dataset_ids = _test_datasets return df def mock_fair_price(_cls, _q): d = { 'fairPrice': [ 2.880, 2.844, 2.726, ], 'contract': [ "F21", "G21", "H21", ] } df = MarketDataResponseFrame(data=d, index=pd.to_datetime([datetime.date(2019, 1, 2)] * 3)) df.dataset_ids = _test_datasets return df def mock_natgas_forward_price(_cls, _q): d = { 'forwardPrice': [ 2.880, 2.844, 2.726, ], 'contract': [ "F21", "G21", "H21", ] } df = MarketDataResponseFrame(data=d, index=pd.to_datetime([datetime.date(2019, 1, 2)] * 3)) df.dataset_ids = _test_datasets return df def mock_fair_price_swap(_cls, _q): d = {'fairPrice': [2.880]} df = MarketDataResponseFrame(data=d, index=pd.to_datetime([datetime.date(2019, 1, 2)])) df.dataset_ids = _test_datasets return df def mock_implied_volatility(_cls, _q): d = { 'impliedVolatility': [ 2.880, 2.844, 2.726, ], 'contract': [ "F21", "G21", "H21", ] } df = MarketDataResponseFrame(data=d, index=pd.to_datetime([datetime.date(2019, 1, 2)] * 3)) df.dataset_ids = _test_datasets return df def mock_missing_bucket_forward_price(_cls, _q): d = { 'forwardPrice': [ 22.0039, 24.8436, 24.8436, 11.9882, 14.0188, 18.9234, 21.3654, 21.3654, ], 'quantityBucket': [ "PEAK", "PEAK", "PEAK", "7X8", "7X8", "2X16H", "2X16H", "2X16H", ], 'contract': [ "J20", "K20", "M20", "J20", "K20", "J20", "K20", "M20", ] } return pd.DataFrame(data=d, index=pd.to_datetime([datetime.date(2019, 1, 2)] * 8)) def mock_fx_vol(_cls, q): queries = q.get('queries', []) if len(queries) > 0 and 'Last' in queries[0]['measures']: return MarketDataResponseFrame({'impliedVolatility': [3]}, index=[pd.Timestamp('2019-01-04T12:00:00Z')]) d = { 'strikeReference': ['delta', 'spot', 'forward'], 'relativeStrike': [25, 100, 100], 'impliedVolatility': [5, 1, 2], 'forecast': [1.1, 1.1, 1.1] } df = MarketDataResponseFrame(data=d, index=pd.date_range('2019-01-01', periods=3, freq='D')) df.dataset_ids = _test_datasets return df def mock_fx_forecast(_cls, _q): d = { 'fxForecast': [1.1, 1.1, 1.1] } df = MarketDataResponseFrame(data=d, index=_index * 3) df.dataset_ids = _test_datasets return df def mock_fx_delta(_cls, _q): d = { 'relativeStrike': [25, -25, 0], 'impliedVolatility': [1, 5, 2], 'forecast': [1.1, 1.1, 1.1] } df = MarketDataResponseFrame(data=d, index=_index * 3) df.dataset_ids = _test_datasets return df def mock_fx_empty(_cls, _q): d = { 'strikeReference': [], 'relativeStrike': [], 'impliedVolatility': [] } df = MarketDataResponseFrame(data=d, index=[]) df.dataset_ids = _test_datasets return df def mock_fx_switch(_cls, _q, _n): replace = Replacer() replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx_empty) replace.restore() return Cross('MA1889', 'ABC/XYZ') def mock_curr(_cls, _q): d = { 'swapAnnuity': [1, 2, 3], 'swapRate': [1, 2, 3], 'basisSwapRate': [1, 2, 3], 'swaptionVol': [1, 2, 3], 'atmFwdRate': [1, 2, 3], 'midcurveVol': [1, 2, 3], 'capFloorVol': [1, 2, 3], 'spreadOptionVol': [1, 2, 3], 'inflationSwapRate': [1, 2, 3], 'midcurveAtmFwdRate': [1, 2, 3], 'capFloorAtmFwdRate': [1, 2, 3], 'spreadOptionAtmFwdRate': [1, 2, 3], 'strike': [0.25, 0.5, 0.75] } df = MarketDataResponseFrame(data=d, index=_index * 3) df.dataset_ids = _test_datasets return df def mock_cross(_cls, _q): d = { 'basis': [1, 2, 3], } df = MarketDataResponseFrame(data=d, index=_index * 3) df.dataset_ids = _test_datasets return df def mock_eq(_cls, _q): d = { 'relativeStrike': [0.75, 0.25, 0.5], 'impliedVolatility': [5, 1, 2], 'impliedCorrelation': [5, 1, 2], 'realizedCorrelation': [3.14, 2.71828, 1.44], 'averageImpliedVolatility': [5, 1, 2], 'averageImpliedVariance': [5, 1, 2], 'averageRealizedVolatility': [5, 1, 2], 'impliedVolatilityByDeltaStrike': [5, 1, 2], 'fundamentalMetric': [5, 1, 2] } df = MarketDataResponseFrame(data=d, index=_index * 3) df.dataset_ids = _test_datasets return df def mock_eq_vol(_cls, q): queries = q.get('queries', []) if len(queries) > 0 and 'Last' in queries[0]['measures']: idx = [pd.Timestamp(datetime.datetime.now(pytz.UTC))] return MarketDataResponseFrame({'impliedVolatility': [3]}, index=idx) d = { 'impliedVolatility': [5, 1, 2], } end = datetime.datetime.now(pytz.UTC).date() - datetime.timedelta(days=1) df = MarketDataResponseFrame(data=d, index=pd.date_range(end=end, periods=3, freq='D')) df.dataset_ids = _test_datasets return df def mock_eq_vol_last_err(_cls, q): queries = q.get('queries', []) if len(queries) > 0 and 'Last' in queries[0]['measures']: raise MqValueError('error while getting last') d = { 'impliedVolatility': [5, 1, 2], } end = datetime.date.today() - datetime.timedelta(days=1) df = MarketDataResponseFrame(data=d, index=pd.date_range(end=end, periods=3, freq='D')) df.dataset_ids = _test_datasets return df def mock_eq_vol_last_empty(_cls, q): queries = q.get('queries', []) if len(queries) > 0 and 'Last' in queries[0]['measures']: return MarketDataResponseFrame() d = { 'impliedVolatility': [5, 1, 2], } end = datetime.date.today() - datetime.timedelta(days=1) df = MarketDataResponseFrame(data=d, index=pd.date_range(end=end, periods=3, freq='D')) df.dataset_ids = _test_datasets return df def mock_eq_norm(_cls, _q): d = { 'relativeStrike': [-4.0, 4.0, 0], 'impliedVolatility': [5, 1, 2] } df = MarketDataResponseFrame(data=d, index=_index * 3) df.dataset_ids = _test_datasets return df def mock_eq_spot(_cls, _q): d = { 'relativeStrike': [0.75, 1.25, 1.0], 'impliedVolatility': [5, 1, 2] } df = MarketDataResponseFrame(data=d, index=_index * 3) df.dataset_ids = _test_datasets return df def mock_inc(_cls, _q): d = { 'relativeStrike': [0.25, 0.75], 'impliedVolatility': [5, 1] } df = MarketDataResponseFrame(data=d, index=_index * 2) df.dataset_ids = _test_datasets return df def mock_meeting_expectation(): data_dict = MarketDataResponseFrame({'date': [dt.date(2019, 12, 6)], 'assetId': ['MARFAGXDQRWM07Y2'], 'location': ['NYC'], 'rateType': ['Meeting Forward'], 'startingDate': [dt.date(2020, 1, 29)], 'endingDate': [dt.date(2020, 1, 29)], 'meetingNumber': [2], 'valuationDate': [dt.date(2019, 12, 6)], 'meetingDate': [dt.date(2020, 1, 23)], 'value': [-0.004550907771] }) data_dict.dataset_ids = _test_datasets return data_dict def mock_meeting_spot(): data_dict = MarketDataResponseFrame({'date': [dt.date(2019, 12, 6)], 'assetId': ['MARFAGXDQRWM07Y2'], 'location': ['NYC'], 'rateType': ['Meeting Forward'], 'startingDate': [dt.date(2019, 10, 30)], 'endingDate': [dt.date(2019, 12, 18)], 'meetingNumber': [0], 'valuationDate': [dt.date(2019, 12, 6)], 'meetingDate': [dt.date(2019, 10, 24)], 'value': [-0.004522570525] }) data_dict.dataset_ids = _test_datasets return data_dict def mock_meeting_absolute(): data_dict = MarketDataResponseFrame({'date': [datetime.date(2019, 12, 6), datetime.date(2019, 12, 6)], 'assetId': ['MARFAGXDQRWM07Y2', 'MARFAGXDQRWM07Y2'], 'location': ['NYC', 'NYC'], 'rateType': ['Meeting Forward', 'Meeting Forward'], 'startingDate': [datetime.date(2019, 10, 30), datetime.date(2020, 1, 29)], 'endingDate': [datetime.date(2019, 10, 30), datetime.date(2020, 1, 29)], 'meetingNumber': [0, 2], 'valuationDate': [datetime.date(2019, 12, 6), datetime.date(2019, 12, 6)], 'meetingDate': [datetime.date(2019, 10, 24), datetime.date(2020, 1, 23)], 'value': [-0.004522570525, -0.004550907771] }) data_dict.dataset_ids = _test_datasets return data_dict def mock_ois_spot(): data_dict = MarketDataResponseFrame({'date': [datetime.date(2019, 12, 6)], 'assetId': ['MARFAGXDQRWM07Y2'], 'location': ['NYC'], 'rateType': ['Spot'], 'startingDate': [datetime.date(2019, 12, 6)], 'endingDate': [datetime.date(2019, 12, 7)], 'meetingNumber': [-1], 'valuationDate': [datetime.date(2019, 12, 6)], 'meetingDate': [datetime.date(2019, 12, 6)], 'value': [-0.00455] }) data_dict.dataset_ids = _test_datasets return data_dict def mock_esg(_cls, _q): d = { "esNumericScore": [2, 4, 6], "esNumericPercentile": [81.2, 75.4, 65.7], "esPolicyScore": [2, 4, 6], "esPolicyPercentile": [81.2, 75.4, 65.7], "esScore": [2, 4, 6], "esPercentile": [81.2, 75.4, 65.7], "esProductImpactScore": [2, 4, 6], "esProductImpactPercentile": [81.2, 75.4, 65.7], "gScore": [2, 4, 6], "gPercentile": [81.2, 75.4, 65.7], "esMomentumScore": [2, 4, 6], "esMomentumPercentile": [81.2, 75.4, 65.7], "gRegionalScore": [2, 4, 6], "gRegionalPercentile": [81.2, 75.4, 65.7], "controversyScore": [2, 4, 6], "controversyPercentile": [81.2, 75.4, 65.7], "esDisclosurePercentage": [49.2, 55.7, 98.4] } df = MarketDataResponseFrame(data=d, index=_index * 3) df.dataset_ids = _test_datasets return df def mock_index_positions_data( asset_id, start_date, end_date, fields=None, position_type=None ): return [ {'underlyingAssetId': 'MA3', 'netWeight': 0.1, 'positionType': 'close', 'assetId': 'MA890', 'positionDate': '2020-01-01' }, {'underlyingAssetId': 'MA1', 'netWeight': 0.6, 'positionType': 'close', 'assetId': 'MA890', 'positionDate': '2020-01-01' }, {'underlyingAssetId': 'MA2', 'netWeight': 0.3, 'positionType': 'close', 'assetId': 'MA890', 'positionDate': '2020-01-01' } ] def mock_rating(_cls, _q): d = { 'rating': ['Buy', 'Sell', 'Buy', 'Neutral'], 'convictionList': [1, 0, 0, 0] } df = MarketDataResponseFrame(data=d, index=pd.to_datetime([datetime.date(2020, 8, 13), datetime.date(2020, 8, 14), datetime.date(2020, 8, 17), datetime.date(2020, 8, 18)])) df.dataset_ids = _test_datasets return df def mock_gsdeer_gsfeer(_cls, assetId, start_date): d = { 'gsdeer': [1, 1.2, 1.1], 'gsfeer': [2, 1.8, 1.9], 'year': [2000, 2010, 2020], 'quarter': ['Q1', 'Q2', 'Q3'] } df = MarketDataResponseFrame(data=d, index=_index * 3) return df def mock_factor_profile(_cls, _q): d = { 'growthScore': [0.238, 0.234, 0.234, 0.230], 'financialReturnsScore': [0.982, 0.982, 0.982, 0.982], 'multipleScore': [0.204, 0.192, 0.190, 0.190], 'integratedScore': [0.672, 0.676, 0.676, 0.674] } df = MarketDataResponseFrame(data=d, index=pd.to_datetime([datetime.date(2020, 8, 13), datetime.date(2020, 8, 14), datetime.date(2020, 8, 17), datetime.date(2020, 8, 18)])) df.dataset_ids = _test_datasets return df def mock_commodity_forecast(_cls, _q): d = { 'forecastPeriod': ['3m', '3m', '3m', '3m'], 'forecastType': ['spotReturn', 'spotReturn', 'spotReturn', 'spotReturn'], 'commodityForecast': [1700, 1400, 1500, 1600] } df = MarketDataResponseFrame(data=d, index=pd.to_datetime([datetime.date(2020, 8, 13), datetime.date(2020, 8, 14), datetime.date(2020, 8, 17), datetime.date(2020, 8, 18)])) df.dataset_ids = _test_datasets return df def test_skew(): replace = Replacer() mock_spx = Index('MA890', AssetClass.Equity, 'SPX') replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq) actual = tm.skew(mock_spx, '1m', tm.SkewReference.DELTA, 25) assert_series_equal(pd.Series([2.0], index=_index, name='impliedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq_norm) actual = tm.skew(mock_spx, '1m', tm.SkewReference.NORMALIZED, 4) assert_series_equal(pd.Series([2.0], index=_index, name='impliedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq_spot) actual = tm.skew(mock_spx, '1m', tm.SkewReference.SPOT, 25) assert_series_equal(pd.Series([2.0], index=_index, name='impliedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets mock = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock()) mock.return_value = mock_empty_market_data_response() actual = tm.skew(mock_spx, '1m', tm.SkewReference.SPOT, 25) assert actual.empty replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_inc) with pytest.raises(MqError): tm.skew(mock_spx, '1m', tm.SkewReference.DELTA, 25) replace.restore() with pytest.raises(MqError): tm.skew(mock_spx, '1m', None, 25) def test_skew_fx(): replace = Replacer() cross = Cross('MAA0NE9QX2ABETG6', 'USD/EUR') xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock()) xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='EURUSD', ))] replace('gs_quant.markets.securities.SecurityMaster.get_asset', Mock()).return_value = cross replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx_delta) mock = cross actual = tm.skew(mock, '1m', tm.SkewReference.DELTA, 25) assert_series_equal(pd.Series([2.0], index=_index, name='impliedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(MqError): tm.skew(mock, '1m', tm.SkewReference.DELTA, 25, real_time=True) with pytest.raises(MqError): tm.skew(mock, '1m', tm.SkewReference.SPOT, 25) with pytest.raises(MqError): tm.skew(mock, '1m', tm.SkewReference.FORWARD, 25) with pytest.raises(MqError): tm.skew(mock, '1m', tm.SkewReference.NORMALIZED, 25) with pytest.raises(MqError): tm.skew(mock, '1m', None, 25) replace.restore() def test_implied_vol(): replace = Replacer() mock_spx = Index('MA890', AssetClass.Equity, 'SPX') replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq_vol) idx = pd.date_range(end=datetime.datetime.now(pytz.UTC).date(), periods=4, freq='D') actual = tm.implied_volatility(mock_spx, '1m', tm.VolReference.DELTA_CALL, 25) assert_series_equal(pd.Series([5, 1, 2, 3], index=idx, name='impliedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.implied_volatility(mock_spx, '1m', tm.VolReference.DELTA_PUT, 75) assert_series_equal(pd.Series([5, 1, 2, 3], index=idx, name='impliedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(MqError): tm.implied_volatility(mock_spx, '1m', tm.VolReference.DELTA_NEUTRAL) with pytest.raises(MqError): tm.implied_volatility(mock_spx, '1m', tm.VolReference.DELTA_CALL) replace.restore() def test_implied_vol_no_last(): replace = Replacer() mock_spx = Index('MA890', AssetClass.Equity, 'SPX') idx = pd.date_range(end=datetime.date.today() - datetime.timedelta(days=1), periods=3, freq='D') replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq_vol_last_err) actual = tm.implied_volatility(mock_spx, '1m', tm.VolReference.DELTA_CALL, 25) assert_series_equal(pd.Series([5, 1, 2], index=idx, name='impliedVolatility'), pd.Series(actual)) actual = tm.implied_volatility(mock_spx, '1m', tm.VolReference.DELTA_PUT, 75) assert_series_equal(pd.Series([5, 1, 2], index=idx, name='impliedVolatility'), pd.Series(actual)) replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq_vol_last_empty) actual = tm.implied_volatility(mock_spx, '1m', tm.VolReference.DELTA_CALL, 25) assert_series_equal(pd.Series([5, 1, 2], index=idx, name='impliedVolatility'), pd.Series(actual)) actual = tm.implied_volatility(mock_spx, '1m', tm.VolReference.DELTA_PUT, 75) assert_series_equal(pd.Series([5, 1, 2], index=idx, name='impliedVolatility'), pd.Series(actual)) replace.restore() def test_implied_vol_fx(): replace = Replacer() mock = Cross('MAA0NE9QX2ABETG6', 'USD/EUR') xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock()) xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='EURUSD', ))] replace('gs_quant.markets.securities.SecurityMaster.get_asset', Mock()).return_value = mock # for different delta strikes replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx_vol) actual = tm.implied_volatility(mock, '1m', tm.VolReference.DELTA_CALL, 25) expected = pd.Series([5, 1, 2, 3], index=pd.date_range('2019-01-01', periods=4, freq='D'), name='impliedVolatility') assert_series_equal(expected, pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.implied_volatility(mock, '1m', tm.VolReference.DELTA_PUT, 25) assert_series_equal(expected, pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.implied_volatility(mock, '1m', tm.VolReference.DELTA_NEUTRAL) assert_series_equal(expected, pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.implied_volatility(mock, '1m', tm.VolReference.FORWARD, 100) assert_series_equal(expected, pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.implied_volatility(mock, '1m', tm.VolReference.SPOT, 100) assert_series_equal(expected, pd.Series(actual)) assert actual.dataset_ids == _test_datasets # NORMALIZED not supported with pytest.raises(MqError): tm.implied_volatility(mock, '1m', tm.VolReference.DELTA_CALL) with pytest.raises(MqError): tm.implied_volatility(mock, '1m', tm.VolReference.NORMALIZED, 25) with pytest.raises(MqError): tm.implied_volatility(mock, '1m', tm.VolReference.SPOT, 25) with pytest.raises(MqError): tm.implied_volatility(mock, '1m', tm.VolReference.FORWARD, 25) replace.restore() def test_fx_forecast(): replace = Replacer() mock = Cross('MAA0NE9QX2ABETG6', 'USD/EUR') xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock()) xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='EURUSD', ))] replace('gs_quant.markets.securities.SecurityMaster.get_asset', Mock()).return_value = mock replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx_forecast) actual = tm.fx_forecast(mock, '12m') assert_series_equal(pd.Series([1.1, 1.1, 1.1], index=_index * 3, name='fxForecast'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.fx_forecast(mock, '3m') assert_series_equal(pd.Series([1.1, 1.1, 1.1], index=_index * 3, name='fxForecast'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.fx_forecast(mock, '3m', real_time=True) replace.restore() def test_fx_forecast_inverse(): replace = Replacer() get_cross = replace('gs_quant.timeseries.measures.cross_to_usd_based_cross', Mock()) get_cross.return_value = "MATGYV0J9MPX534Z" replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx_forecast) mock = Cross("MAYJPCVVF2RWXCES", 'USD/JPY') actual = tm.fx_forecast(mock, '3m') assert_series_equal(pd.Series([1 / 1.1, 1 / 1.1, 1 / 1.1], index=_index * 3, name='fxForecast'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets replace.restore() def test_vol_smile(): replace = Replacer() mock_spx = Index('MA890', AssetClass.Equity, 'SPX') replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq) actual = tm.vol_smile(mock_spx, '1m', tm.VolSmileReference.FORWARD, '5d') assert_series_equal(pd.Series([5, 1, 2], index=[0.75, 0.25, 0.5]), pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.vol_smile(mock_spx, '1m', tm.VolSmileReference.SPOT, '5d') assert_series_equal(pd.Series([5, 1, 2], index=[0.75, 0.25, 0.5]), pd.Series(actual)) assert actual.dataset_ids == _test_datasets market_mock = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock()) market_mock.return_value = mock_empty_market_data_response() actual = tm.vol_smile(mock_spx, '1m', tm.VolSmileReference.SPOT, '1d') assert actual.empty assert actual.dataset_ids == () market_mock.assert_called_once() with pytest.raises(NotImplementedError): tm.vol_smile(mock_spx, '1m', tm.VolSmileReference.SPOT, '1d', real_time=True) replace.restore() def test_impl_corr(): replace = Replacer() mock_spx = Index('MA890', AssetClass.Equity, 'SPX') replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq) actual = tm.implied_correlation(mock_spx, '1m', tm.EdrDataReference.DELTA_CALL, 25) assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='impliedCorrelation'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.implied_correlation(mock_spx, '1m', tm.EdrDataReference.DELTA_PUT, 75) assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='impliedCorrelation'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.implied_correlation(..., '1m', tm.EdrDataReference.DELTA_PUT, 75, real_time=True) with pytest.raises(MqError): tm.implied_correlation(..., '1m', tm.EdrDataReference.DELTA_CALL, 50, '') replace.restore() def test_impl_corr_n(): spx = Index('MA4B66MW5E27U8P32SB', AssetClass.Equity, 'SPX') with pytest.raises(MqValueError): tm.implied_correlation(spx, '1m', tm.EdrDataReference.DELTA_CALL, 0.5, composition_date=datetime.date.today()) with pytest.raises(MqValueError): tm.implied_correlation(spx, '1m', tm.EdrDataReference.DELTA_CALL, 0.5, 200) resources = os.path.join(os.path.dirname(__file__), '..', 'resources') i_vol = pd.read_csv(os.path.join(resources, 'SPX_50_icorr_in.csv')) i_vol.index = pd.to_datetime(i_vol['date']) weights = pd.read_csv(os.path.join(resources, 'SPX_50_weights.csv')) weights.set_index('underlyingAssetId', inplace=True) replace = Replacer() market_data = replace('gs_quant.timeseries.econometrics.GsDataApi.get_market_data', Mock()) market_data.return_value = i_vol constituents = replace('gs_quant.timeseries.measures._get_index_constituent_weights', Mock()) constituents.return_value = weights expected = pd.read_csv(os.path.join(resources, 'SPX_50_icorr_out.csv')) expected.index = pd.to_datetime(expected['date']) expected = expected['value'] actual = tm.implied_correlation(spx, '1m', tm.EdrDataReference.DELTA_CALL, 0.5, 50, datetime.date(2020, 8, 31), source='PlotTool') pd.testing.assert_series_equal(actual, expected, check_names=False) replace.restore() def test_real_corr(): spx = Index('MA4B66MW5E27U8P32SB', AssetClass.Equity, 'SPX') with pytest.raises(NotImplementedError): tm.realized_correlation(spx, '1m', real_time=True) replace = Replacer() replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq) actual = tm.realized_correlation(spx, '1m') assert_series_equal(pd.Series([3.14, 2.71828, 1.44], index=_index * 3), pd.Series(actual), check_names=False) assert actual.dataset_ids == _test_datasets replace.restore() def test_real_corr_missing(): spx = Index('MA4B66MW5E27U8P32SB', AssetClass.Equity, 'SPX') d = { 'assetId': ['MA4B66MW5E27U8P32SB'] * 3, 'spot': [3000, 3100, 3050], } df = MarketDataResponseFrame(data=d, index=pd.date_range('2020-08-01', periods=3, freq='D')) resources = os.path.join(os.path.dirname(__file__), '..', 'resources') weights = pd.read_csv(os.path.join(resources, 'SPX_50_weights.csv')) weights.set_index('underlyingAssetId', inplace=True) replace = Replacer() replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', lambda *args, **kwargs: df) constituents = replace('gs_quant.timeseries.measures._get_index_constituent_weights', Mock()) constituents.return_value = weights with pytest.raises(MqValueError): tm.realized_correlation(spx, '1m', 50) replace.restore() def test_real_corr_n(): spx = Index('MA4B66MW5E27U8P32SB', AssetClass.Equity, 'SPX') with pytest.raises(MqValueError): tm.realized_correlation(spx, '1m', composition_date=datetime.date.today()) with pytest.raises(MqValueError): tm.realized_correlation(spx, '1m', 200) resources = os.path.join(os.path.dirname(__file__), '..', 'resources') r_vol = pd.read_csv(os.path.join(resources, 'SPX_50_rcorr_in.csv')) r_vol.index = pd.to_datetime(r_vol['date']) weights = pd.read_csv(os.path.join(resources, 'SPX_50_weights.csv')) weights.set_index('underlyingAssetId', inplace=True) replace = Replacer() market_data = replace('gs_quant.timeseries.econometrics.GsDataApi.get_market_data', Mock()) market_data.return_value = r_vol constituents = replace('gs_quant.timeseries.measures._get_index_constituent_weights', Mock()) constituents.return_value = weights expected = pd.read_csv(os.path.join(resources, 'SPX_50_rcorr_out.csv')) expected.index = pd.to_datetime(expected['date']) expected = expected['value'] actual = tm.realized_correlation(spx, '1m', 50, datetime.date(2020, 8, 31), source='PlotTool') pd.testing.assert_series_equal(actual, expected, check_names=False) replace.restore() def test_cds_implied_vol(): replace = Replacer() mock_cds = Index('MA890', AssetClass.Equity, 'CDS') replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq) actual = tm.cds_implied_volatility(mock_cds, '1m', '5y', tm.CdsVolReference.DELTA_CALL, 10) assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatilityByDeltaStrike'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.cds_implied_volatility(mock_cds, '1m', '5y', tm.CdsVolReference.FORWARD, 100) assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatilityByDeltaStrike'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.cds_implied_volatility(..., '1m', '5y', tm.CdsVolReference.DELTA_PUT, 75, real_time=True) replace.restore() def test_avg_impl_vol(): replace = Replacer() mock_spx = Index('MA890', AssetClass.Equity, 'SPX') replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq) actual = tm.average_implied_volatility(mock_spx, '1m', tm.EdrDataReference.DELTA_CALL, 25) assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='averageImpliedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets actual = tm.average_implied_volatility(mock_spx, '1m', tm.EdrDataReference.DELTA_PUT, 75) assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='averageImpliedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets replace.restore() df1 = pd.DataFrame(data={'impliedVolatility': [1, 2, 3], 'assetId': ['MA1', 'MA1', 'MA1']}, index=pd.date_range(start='2020-01-01', periods=3)) df2 = pd.DataFrame(data={'impliedVolatility': [2, 3, 4], 'assetId': ['MA2', 'MA2', 'MA2']}, index=pd.date_range(start='2020-01-01', periods=3)) df3 = pd.DataFrame(data={'impliedVolatility': [2, 5], 'assetId': ['MA3', 'MA3']}, index=pd.date_range(start='2020-01-01', periods=2)) replace('gs_quant.api.gs.assets.GsAssetApi.get_asset_positions_data', mock_index_positions_data) market_data_mock = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock()) mock_implied_vol = MarketDataResponseFrame(pd.concat([df1, df2, df3], join='inner')) mock_implied_vol.dataset_ids = _test_datasets market_data_mock.return_value = mock_implied_vol actual = tm.average_implied_volatility(mock_spx, '1m', tm.EdrDataReference.DELTA_CALL, 25, 3, '1d') assert_series_equal(pd.Series([1.4, 2.6, 3.33333], index=pd.date_range(start='2020-01-01', periods=3), name='averageImpliedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.average_implied_volatility(..., '1m', tm.EdrDataReference.DELTA_PUT, 75, real_time=True) with pytest.raises(MqValueError): tm.average_implied_volatility(mock_spx, '1m', tm.EdrDataReference.DELTA_PUT, 75, top_n_of_index=None, composition_date='1d') with pytest.raises(NotImplementedError): tm.average_implied_volatility(mock_spx, '1m', tm.EdrDataReference.DELTA_PUT, 75, top_n_of_index=101) replace.restore() def test_avg_realized_vol(): replace = Replacer() mock_spx = Index('MA890', AssetClass.Equity, 'SPX') replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq) actual = tm.average_realized_volatility(mock_spx, '1m') assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='averageRealizedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets replace.restore() df1 = pd.DataFrame(data={'spot': [1, 2, 3], 'assetId': ['MA1', 'MA1', 'MA1']}, index=pd.date_range(start='2020-01-01', periods=3)) df2 = pd.DataFrame(data={'spot': [2, 3, 4], 'assetId': ['MA2', 'MA2', 'MA2']}, index=pd.date_range(start='2020-01-01', periods=3)) df3 = pd.DataFrame(data={'spot': [2, 5], 'assetId': ['MA3', 'MA3']}, index=pd.date_range(start='2020-01-01', periods=2)) mock_spot = MarketDataResponseFrame(pd.concat([df1, df2, df3], join='inner')) mock_spot.dataset_ids = _test_datasets replace('gs_quant.api.gs.assets.GsAssetApi.get_asset_positions_data', mock_index_positions_data) market_data_mock = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock()) market_data_mock.return_value = mock_spot actual = tm.average_realized_volatility(mock_spx, '2d', Returns.SIMPLE, 3, '1d') assert_series_equal(pd.Series([392.874026], index=pd.date_range(start='2020-01-03', periods=1), name='averageRealizedVolatility'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.average_realized_volatility(mock_spx, '1w', real_time=True) with pytest.raises(MqValueError): tm.average_realized_volatility(mock_spx, '1w', composition_date='1d') with pytest.raises(NotImplementedError): tm.average_realized_volatility(mock_spx, '1w', Returns.LOGARITHMIC) with pytest.raises(NotImplementedError): tm.average_realized_volatility(mock_spx, '1w', Returns.SIMPLE, 201) replace.restore() empty_positions_data_mock = replace('gs_quant.api.gs.assets.GsAssetApi.get_asset_positions_data', Mock()) empty_positions_data_mock.return_value = [] with pytest.raises(MqValueError): tm.average_realized_volatility(mock_spx, '1w', Returns.SIMPLE, 5) replace.restore() def test_avg_impl_var(): replace = Replacer() mock_spx = Index('MA890', AssetClass.Equity, 'SPX') replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq) actual = tm.average_implied_variance(mock_spx, '1m', tm.EdrDataReference.DELTA_CALL, 25) assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='averageImpliedVariance'), pd.Series(actual)) actual = tm.average_implied_variance(mock_spx, '1m', tm.EdrDataReference.DELTA_PUT, 75) assert actual.dataset_ids == _test_datasets assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='averageImpliedVariance'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.average_implied_variance(..., '1m', tm.EdrDataReference.DELTA_PUT, 75, real_time=True) replace.restore() def test_basis_swap_spread(mocker): replace = Replacer() args = dict(swap_tenor='10y', spread_benchmark_type=None, spread_tenor=None, reference_benchmark_type=None, reference_tenor=None, forward_tenor='0b', real_time=False) mock_nok = Currency('MA891', 'NOK') xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'NOK' args['asset'] = mock_nok with pytest.raises(NotImplementedError): tm_rates.basis_swap_spread(**args) mock_usd = Currency('MAZ7RWC904JYHYPS', 'USD') args['asset'] = mock_usd xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' with pytest.raises(NotImplementedError): tm_rates.basis_swap_spread(..., '1y', real_time=True) args['swap_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.basis_swap_spread(**args) args['swap_tenor'] = '6y' args['spread_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.basis_swap_spread(**args) args['spread_tenor'] = '3m' args['reference_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.basis_swap_spread(**args) args['reference_tenor'] = '6m' args['forward_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.basis_swap_spread(**args) args['forward_tenor'] = None args['spread_benchmark_type'] = BenchmarkType.STIBOR with pytest.raises(MqValueError): tm_rates.basis_swap_spread(**args) args['spread_benchmark_type'] = BenchmarkType.LIBOR args['reference_benchmark_type'] = 'libor_3m' with pytest.raises(MqValueError): tm_rates.basis_swap_spread(**args) args['reference_benchmark_type'] = BenchmarkType.LIBOR xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' identifiers = replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets', Mock()) identifiers.return_value = {'MAQB1PGEJFCET3GG'} mocker.patch.object(GsDataApi, 'get_market_data', return_value=mock_curr(None, None)) actual = tm_rates.basis_swap_spread(**args) expected = tm.ExtendedSeries([1, 2, 3], index=_index * 3, name='basisSwapRate') expected.dataset_ids = _test_datasets assert_series_equal(expected, actual) assert actual.dataset_ids == expected.dataset_ids args['reference_benchmark_type'] = BenchmarkType.SOFR args['reference_tenor'] = '1y' args['reference_benchmark_type'] = BenchmarkType.LIBOR args['reference_tenor'] = '3m' xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' identifiers = replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets', Mock()) identifiers.return_value = {'MA06ATQ9CM0DCZFC'} mocker.patch.object(GsDataApi, 'get_market_data', return_value=mock_curr(None, None)) actual = tm_rates.basis_swap_spread(**args) expected = tm.ExtendedSeries([1, 2, 3], index=_index * 3, name='basisSwapRate') expected.dataset_ids = _test_datasets assert_series_equal(expected, actual) assert actual.dataset_ids == expected.dataset_ids replace.restore() def test_swap_rate(mocker): replace = Replacer() args = dict(swap_tenor='10y', benchmark_type=None, floating_rate_tenor=None, forward_tenor='0b', real_time=False) mock_usd = Currency('MAZ7RWC904JYHYPS', 'USD') args['asset'] = mock_usd xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' args['swap_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.swap_rate(**args) args['swap_tenor'] = '10y' args['floating_rate_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.swap_rate(**args) args['floating_rate_tenor'] = '1y' args['forward_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.swap_rate(**args) args['forward_tenor'] = None args['benchmark_type'] = BenchmarkType.STIBOR with pytest.raises(MqValueError): tm_rates.swap_rate(**args) args['benchmark_type'] = 'sonia' with pytest.raises(MqValueError): tm_rates.swap_rate(**args) args['benchmark_type'] = 'fed_funds' xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' identifiers = replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets', Mock()) identifiers.return_value = {'MAZ7RWC904JYHYPS'} mocker.patch.object(GsDataApi, 'get_market_data', return_value=mock_curr(None, None)) actual = tm_rates.swap_rate(**args) expected = tm.ExtendedSeries([1, 2, 3], index=_index * 3, name='swapRate') expected.dataset_ids = _test_datasets assert_series_equal(expected, actual) assert actual.dataset_ids == _test_datasets xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'EUR' identifiers = replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets', Mock()) identifiers.return_value = {'MAJNQPFGN1EBDHAE'} mocker.patch.object(GsDataApi, 'get_market_data', return_value=mock_curr(None, None)) args['asset'] = Currency('MAJNQPFGN1EBDHAE', 'EUR') args['benchmark_type'] = 'estr' actual = tm_rates.swap_rate(**args) expected = tm.ExtendedSeries([1, 2, 3], index=_index * 3, name='swapRate') expected.dataset_ids = _test_datasets assert_series_equal(expected, actual) assert actual.dataset_ids == _test_datasets replace.restore() def test_swap_annuity(mocker): replace = Replacer() args = dict(swap_tenor='10y', benchmark_type=None, floating_rate_tenor=None, forward_tenor='0b', real_time=False) mock_nok = Currency('MA891', 'PLN') xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'PLN' args['asset'] = mock_nok with pytest.raises(NotImplementedError): tm_rates.swap_annuity(**args) mock_usd = Currency('MAZ7RWC904JYHYPS', 'USD') args['asset'] = mock_usd xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' with pytest.raises(NotImplementedError): tm_rates.swap_annuity(..., '1y', real_time=True) args['swap_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.swap_annuity(**args) args['swap_tenor'] = '10y' args['floating_rate_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.swap_annuity(**args) args['floating_rate_tenor'] = '1y' args['forward_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.swap_annuity(**args) args['forward_tenor'] = None args['benchmark_type'] = BenchmarkType.STIBOR with pytest.raises(MqValueError): tm_rates.swap_annuity(**args) args['benchmark_type'] = BenchmarkType.SOFR xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' identifiers = replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets', Mock()) identifiers.return_value = {'MAZ7RWC904JYHYPS'} mocker.patch.object(GsDataApi, 'get_market_data', return_value=mock_curr(None, None)) actual = tm_rates.swap_annuity(**args) expected = abs(tm.ExtendedSeries([1.0, 2.0, 3.0], index=_index * 3, name='swapAnnuity') * 1e4 / 1e8) expected.dataset_ids = _test_datasets assert_series_equal(expected, actual) assert actual.dataset_ids == expected.dataset_ids replace.restore() def test_swap_term_structure(): replace = Replacer() args = dict(benchmark_type=None, floating_rate_tenor=None, tenor_type=tm_rates._SwapTenorType.FORWARD_TENOR, tenor='0b', real_time=False) mock_nok = Currency('MA891', 'PLN') xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'PLN' args['asset'] = mock_nok with pytest.raises(NotImplementedError): tm_rates.swap_term_structure(**args) mock_usd = Currency('MAZ7RWC904JYHYPS', 'USD') args['asset'] = mock_usd xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' with pytest.raises(NotImplementedError): tm_rates.swap_term_structure(..., '1y', real_time=True) args['floating_rate_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.swap_term_structure(**args) args['floating_rate_tenor'] = '3m' args['tenor_type'] = 'expiry' with pytest.raises(MqValueError): tm_rates.swap_term_structure(**args) args['tenor_type'] = None args['tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.swap_term_structure(**args) args['tenor'] = None args['benchmark_type'] = BenchmarkType.STIBOR with pytest.raises(MqValueError): tm_rates.swap_term_structure(**args) args['benchmark_type'] = BenchmarkType.LIBOR bd_mock = replace('gs_quant.data.dataset.Dataset.get_data', Mock()) bd_mock.return_value = pd.DataFrame(data=dict(date="2020-04-10", exchange="NYC", description="Good Friday"), index=[pd.Timestamp('2020-04-10')]) args['pricing_date'] = datetime.date(2020, 4, 10) with pytest.raises(MqValueError): tm_rates.swap_term_structure(**args) args['pricing_date'] = None xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' identifiers_empty = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) identifiers_empty.return_value = {} with pytest.raises(MqValueError): tm_rates.swap_term_structure(**args) identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) mock_asset = Currency('USD', name='USD') mock_asset.id = 'MAEMPCXQG3T716EX' mock_asset.exchange = 'OTC' identifiers.return_value = [mock_asset] d = { 'terminationTenor': ['1y', '2y', '3y', '4y'], 'swapRate': [1, 2, 3, 4], 'assetId': ['MAEMPCXQG3T716EX', 'MAFRSWPAF5QPNTP2', 'MA88BXZ3TCTXTFW1', 'MAC4KAG9B9ZAZHFT'] } pricing_date_mock = replace('gs_quant.timeseries.measures_rates._range_from_pricing_date', Mock()) pricing_date_mock.return_value = [datetime.date(2019, 1, 1), datetime.date(2019, 1, 1)] bd_mock.return_value = pd.DataFrame() market_data_mock = replace('gs_quant.timeseries.measures_rates._market_data_timed', Mock()) market_data_mock.return_value = pd.DataFrame() df = pd.DataFrame(data=d, index=_index * 4) assert tm_rates.swap_term_structure(**args).empty market_data_mock.return_value = df with DataContext('2019-01-01', '2025-01-01'): actual = tm_rates.swap_term_structure(**args) actual.dataset_ids = _test_datasets expected = tm.ExtendedSeries([1, 2, 3, 4], index=pd.to_datetime(['2020-01-01', '2021-01-01', '2021-12-31', '2022-12-30'])) expected.dataset_ids = _test_datasets assert_series_equal(expected, actual, check_names=False) assert actual.dataset_ids == expected.dataset_ids df = pd.DataFrame(data={'effectiveTenor': ['1y'], 'swapRate': [1], 'assetId': ['MAEMPCXQG3T716EX']}, index=_index) market_data_mock.return_value = df args['tenor_type'] = 'swap_tenor' args['tenor'] = '5y' with DataContext('2019-01-01', '2025-01-01'): actual = tm_rates.swap_term_structure(**args) actual.dataset_ids = _test_datasets expected = tm.ExtendedSeries([1], index=pd.to_datetime(['2020-01-01'])) expected.dataset_ids = _test_datasets assert_series_equal(expected, actual, check_names=False) assert actual.dataset_ids == expected.dataset_ids d = { 'effectiveTenor': ['1y', '2y', '3y', '4y'], 'swapRate': [1, 2, 3, 4], 'assetId': ['MAEMPCXQG3T716EX', 'MAFRSWPAF5QPNTP2', 'MA88BXZ3TCTXTFW1', 'MAC4KAG9B9ZAZHFT'] } df = pd.DataFrame(data=d, index=_index * 4) market_data_mock.return_value = df args['tenor_type'] = 'swap_tenor' args['tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.swap_term_structure(**args) args['tenor'] = '5y' market_data_mock.return_value = pd.DataFrame() df = pd.DataFrame(data=d, index=_index * 4) assert tm_rates.swap_term_structure(**args).empty market_data_mock.return_value = df with DataContext('2019-01-01', '2025-01-01'): actual = tm_rates.swap_term_structure(**args) actual.dataset_ids = _test_datasets expected = tm.ExtendedSeries([1, 2, 3, 4], index=pd.to_datetime(['2020-01-01', '2021-01-01', '2021-12-31', '2022-12-30'])) expected.dataset_ids = _test_datasets assert_series_equal(expected, actual, check_names=False) assert actual.dataset_ids == expected.dataset_ids replace.restore() def test_basis_swap_term_structure(): replace = Replacer() range_mock = replace('gs_quant.timeseries.measures_rates._range_from_pricing_date', Mock()) range_mock.return_value = [datetime.date(2019, 1, 1), datetime.date(2019, 1, 1)] args = dict(spread_benchmark_type=None, spread_tenor=None, reference_benchmark_type=None, reference_tenor=None, tenor_type=tm_rates._SwapTenorType.FORWARD_TENOR, tenor='0b', real_time=False) mock_nok = Currency('MA891', 'NOK') xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'NOK' args['asset'] = mock_nok with pytest.raises(NotImplementedError): tm_rates.basis_swap_term_structure(**args) mock_usd = Currency('MAZ7RWC904JYHYPS', 'USD') args['asset'] = mock_usd xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' with pytest.raises(NotImplementedError): tm_rates.basis_swap_term_structure(..., '1y', real_time=True) args['spread_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.basis_swap_term_structure(**args) args['spread_tenor'] = '3m' args['reference_tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.basis_swap_term_structure(**args) args['reference_tenor'] = '6m' args['tenor_type'] = 'expiry' with pytest.raises(MqValueError): tm_rates.basis_swap_term_structure(**args) args['tenor_type'] = 'forward_tenor' args['tenor'] = '5yr' with pytest.raises(MqValueError): tm_rates.basis_swap_term_structure(**args) args['tenor'] = None args['spread_benchmark_type'] = BenchmarkType.STIBOR with pytest.raises(MqValueError): tm_rates.basis_swap_term_structure(**args) args['spread_benchmark_type'] = BenchmarkType.LIBOR args['reference_benchmark_type'] = BenchmarkType.STIBOR with pytest.raises(MqValueError): tm_rates.basis_swap_term_structure(**args) args['reference_benchmark_type'] = BenchmarkType.LIBOR bd_mock = replace('gs_quant.data.dataset.Dataset.get_data', Mock()) bd_mock.return_value = pd.DataFrame(data=dict(date="2020-04-10", exchange="NYC", description="Good Friday"), index=[pd.Timestamp('2020-04-10')]) args['pricing_date'] = datetime.date(2020, 4, 10) with pytest.raises(MqValueError): tm_rates.basis_swap_term_structure(**args) args['pricing_date'] = None xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'USD' identifiers_empty = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) identifiers_empty.return_value = {} with pytest.raises(MqValueError): tm_rates.basis_swap_term_structure(**args) identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) mock_asset = Currency('USD', name='USD') mock_asset.id = 'MAEMPCXQG3T716EX' mock_asset.exchange = 'OTC' identifiers.return_value = [mock_asset] d = { 'terminationTenor': ['1y', '2y', '3y', '4y'], 'basisSwapRate': [1, 2, 3, 4], 'assetId': ['MAEMPCXQG3T716EX', 'MAFRSWPAF5QPNTP2', 'MA88BXZ3TCTXTFW1', 'MAC4KAG9B9ZAZHFT'] } pricing_date_mock = replace('gs_quant.timeseries.measures_rates._range_from_pricing_date', Mock()) pricing_date_mock.return_value = [datetime.date(2019, 1, 1), datetime.date(2019, 1, 1)] bd_mock.return_value = pd.DataFrame() market_data_mock = replace('gs_quant.timeseries.measures_rates._market_data_timed', Mock()) market_data_mock.return_value = pd.DataFrame() assert tm_rates.basis_swap_term_structure(**args).empty df = pd.DataFrame(data=d, index=_index * 4) market_data_mock.return_value = df with DataContext('2019-01-01', '2025-01-01'): actual = tm_rates.basis_swap_term_structure(**args) actual.dataset_ids = _test_datasets expected = tm.ExtendedSeries([1, 2, 3, 4], index=pd.to_datetime(['2020-01-01', '2021-01-01', '2021-12-31', '2022-12-30'])) expected.dataset_ids = _test_datasets assert_series_equal(expected, actual, check_names=False) assert actual.dataset_ids == expected.dataset_ids d = { 'effectiveTenor': ['1y', '2y', '3y', '4y'], 'basisSwapRate': [1, 2, 3, 4], 'assetId': ['MAEMPCXQG3T716EX', 'MAFRSWPAF5QPNTP2', 'MA88BXZ3TCTXTFW1', 'MAC4KAG9B9ZAZHFT'] } bd_mock.return_value = pd.DataFrame() market_data_mock = replace('gs_quant.timeseries.measures_rates._market_data_timed', Mock()) df = pd.DataFrame(data=d, index=_index * 4) market_data_mock.return_value = df args['tenor_type'] = tm_rates._SwapTenorType.SWAP_TENOR args['tenor'] = '5y' with DataContext('2019-01-01', '2025-01-01'): actual = tm_rates.basis_swap_term_structure(**args) actual.dataset_ids = _test_datasets expected = tm.ExtendedSeries([1, 2, 3, 4], index=pd.to_datetime(['2020-01-01', '2021-01-01', '2021-12-31', '2022-12-30'])) expected.dataset_ids = _test_datasets assert_series_equal(expected, actual, check_names=False) assert actual.dataset_ids == expected.dataset_ids df = pd.DataFrame(data={'effectiveTenor': ['1y'], 'basisSwapRate': [1], 'assetId': ['MAEMPCXQG3T716EX']}, index=_index) market_data_mock.return_value = df with DataContext('2019-01-01', '2025-01-01'): actual = tm_rates.basis_swap_term_structure(**args) actual.dataset_ids = _test_datasets expected = tm.ExtendedSeries([1], index=pd.to_datetime(['2020-01-01'])) expected.dataset_ids = _test_datasets assert_series_equal(expected, actual, check_names=False) assert actual.dataset_ids == expected.dataset_ids replace.restore() def test_cap_floor_vol(): replace = Replacer() mock_usd = Currency('MA890', 'USD') xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock()) xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='USD', ))] identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock()) identifiers.return_value = {'USD-LIBOR-BBA': 'MA123'} replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_curr) actual = tm.cap_floor_vol(mock_usd, '5y', 50) assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='capFloorVol'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.cap_floor_vol(..., '5y', 50, real_time=True) replace.restore() def test_cap_floor_atm_fwd_rate(): replace = Replacer() mock_usd = Currency('MA890', 'USD') xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock()) xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='USD', ))] identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock()) identifiers.return_value = {'USD-LIBOR-BBA': 'MA123'} replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_curr) actual = tm.cap_floor_atm_fwd_rate(mock_usd, '5y') assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='capFloorAtmFwdRate'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.cap_floor_atm_fwd_rate(..., '5y', real_time=True) replace.restore() def test_spread_option_vol(): replace = Replacer() mock_usd = Currency('MA890', 'USD') xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock()) xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='USD', ))] identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock()) identifiers.return_value = {'USD-LIBOR-BBA': 'MA123'} replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_curr) actual = tm.spread_option_vol(mock_usd, '3m', '10y', '5y', 50) assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='spreadOptionVol'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.spread_option_vol(..., '3m', '10y', '5y', 50, real_time=True) replace.restore() def test_spread_option_atm_fwd_rate(): replace = Replacer() mock_usd = Currency('MA890', 'USD') xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock()) xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='USD', ))] identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock()) identifiers.return_value = {'USD-LIBOR-BBA': 'MA123'} replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_curr) actual = tm.spread_option_atm_fwd_rate(mock_usd, '3m', '10y', '5y') assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='spreadOptionAtmFwdRate'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.spread_option_atm_fwd_rate(..., '3m', '10y', '5y', real_time=True) replace.restore() def test_zc_inflation_swap_rate(): replace = Replacer() mock_gbp = Currency('MA890', 'GBP') xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock()) xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='GBP', ))] identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock()) identifiers.return_value = {'CPI-UKRPI': 'MA123'} replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_curr) actual = tm.zc_inflation_swap_rate(mock_gbp, '1y') assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='inflationSwapRate'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.zc_inflation_swap_rate(..., '1y', real_time=True) replace.restore() def test_basis(): replace = Replacer() mock_jpyusd = Cross('MA890', 'USD/JPY') xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock()) xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='JPYUSD', ))] identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock()) identifiers.return_value = {'USD-3m/JPY-3m': 'MA123'} replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_cross) actual = tm.basis(mock_jpyusd, '1y') assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='basis'), pd.Series(actual)) assert actual.dataset_ids == _test_datasets with pytest.raises(NotImplementedError): tm.basis(..., '1y', real_time=True) replace.restore() def test_td(): cases = {'3d': pd.DateOffset(days=3), '9w': pd.DateOffset(weeks=9), '2m': pd.DateOffset(months=2), '10y': pd.DateOffset(years=10) } for k, v in cases.items(): actual = tm._to_offset(k) assert v == actual, f'expected {v}, got actual {actual}' with pytest.raises(ValueError): tm._to_offset('5z') def test_pricing_range(): import datetime given = datetime.date(2019, 4, 20) s, e = tm._range_from_pricing_date('NYSE', given) assert s == e == given class MockDate(datetime.date): @classmethod def today(cls): return cls(2019, 5, 25) # mock replace = Replacer() cbd = replace('gs_quant.timeseries.measures._get_custom_bd', Mock()) cbd.return_value = pd.tseries.offsets.BusinessDay() today = replace('gs_quant.timeseries.measures.pd.Timestamp.today', Mock()) today.return_value = pd.Timestamp(2019, 5, 25) gold = datetime.date datetime.date = MockDate # cases s, e = tm._range_from_pricing_date('ANY') assert s == pd.Timestamp(2019, 5, 24) assert e == pd.Timestamp(2019, 5, 24) s, e = tm._range_from_pricing_date('ANY', '3m') assert s == pd.Timestamp(2019, 2, 22) assert e == pd.Timestamp(2019, 2, 24) s, e = tm._range_from_pricing_date('ANY', '3b') assert s == e == pd.Timestamp(2019, 5, 22) # restore datetime.date = gold replace.restore() def test_var_swap_tenors(): session = GsSession.get(Environment.DEV, token='<PASSWORD>') replace = Replacer() get_mock = replace('gs_quant.session.GsSession._get', Mock()) get_mock.return_value = { 'data': [ { 'dataField': 'varSwap', 'filteredFields': [ { 'field': 'tenor', 'values': ['abc', 'xyc'] } ] } ] } with session: actual = tm._var_swap_tenors(Index('MAXXX', AssetClass.Equity, 'XXX')) assert actual == ['abc', 'xyc'] get_mock.return_value = { 'data': [] } with pytest.raises(MqError): with session: tm._var_swap_tenors(Index('MAXXX', AssetClass.Equity, 'XXX')) replace.restore() def test_tenor_to_month(): with pytest.raises(MqError): tm._tenor_to_month('1d') with pytest.raises(MqError): tm._tenor_to_month('2w') assert tm._tenor_to_month('3m') == 3 assert tm._tenor_to_month('4y') == 48 def test_month_to_tenor(): assert tm._month_to_tenor(36) == '3y' assert tm._month_to_tenor(18) == '18m' def test_forward_var_term(): idx = pd.DatetimeIndex([datetime.date(2020, 4, 1), datetime.date(2020, 4, 2)] * 6) data = { 'varSwap': [1.1, 1, 2.1, 2, 3.1, 3, 4.1, 4, 5.1, 5, 6.1, 6], 'tenor': ['1w', '1w', '1m', '1m', '5w', '5w', '2m', '2m', '3m', '3m', '5m', '5m'] } out = MarketDataResponseFrame(data=data, index=idx) out.dataset_ids = _test_datasets replace = Replacer() market_mock = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock()) market_mock.return_value = out # Equity expected = pd.Series([np.nan, 5.29150, 6.55744], name='forwardVarTerm', index=pd.DatetimeIndex(['2020-05-01', '2020-06-02', '2020-07-02'], name='expirationDate')) with DataContext('2020-01-01', '2020-07-31'): actual = tm.forward_var_term(Index('MA123', AssetClass.Equity, '123'), datetime.date(2020, 4, 2)) assert_series_equal(expected, pd.Series(actual)) assert actual.dataset_ids == _test_datasets market_mock.assert_called_once() # FX expected_fx = pd.Series([np.nan, 5.29150, 6.55744, 7.24569], name='forwardVarTerm', index=pd.DatetimeIndex(['2020-05-01', '2020-06-02', '2020-07-02', '2020-09-02'], name='expirationDate')) with DataContext('2020-01-01', '2020-09-02'): actual_fx = tm.forward_var_term(Cross('ABCDE', 'EURUSD')) assert_series_equal(expected_fx, pd.Series(actual_fx)) assert actual_fx.dataset_ids == _test_datasets # no data market_mock.reset_mock() market_mock.return_value = mock_empty_market_data_response() actual = tm.forward_var_term(Index('MA123', AssetClass.Equity, '123')) assert actual.empty # real-time with pytest.raises(NotImplementedError): tm.forward_var_term(..., real_time=True) replace.restore() def _mock_var_swap_data(_cls, q): queries = q.get('queries', []) if len(queries) > 0 and 'Last' in queries[0]['measures']: return MarketDataResponseFrame({'varSwap': [4]}, index=[pd.Timestamp('2019-01-04T12:00:00Z')]) idx = pd.date_range(start="2019-01-01", periods=3, freq="D") data = { 'varSwap': [1, 2, 3] } out = MarketDataResponseFrame(data=data, index=idx) out.dataset_ids = _test_datasets return out def test_var_swap(): replace = Replacer() replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', _mock_var_swap_data) expected = pd.Series([1, 2, 3, 4], name='varSwap', index=
pd.date_range("2019-01-01", periods=4, freq="D")
pandas.date_range
# -*- coding: utf-8 -*- """ Created on Wed Dec 1 19:58:26 2021 @author: <NAME> and <NAME> """ import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import numpy as np import pandas as pd import matplotlib.pyplot as plt import pyomo.environ as pyo import utils as pu def init(): import matplotlib matplotlib.pyplot.rcdefaults() matplotlib.pyplot.style.use(u"config/project.mplstyle") matplotlib.pyplot.close("all") class EVChargingLoadModel(): """ This is the main class that contains all necessary variables and functions related to the EV charging load model. """ def __init__(self, configfile): self.configfile = configfile self.read_config() self.def_general_variables() self.read_base_elec_rate() self.read_base_charg_load() self.read_target_charg_load() # print(self.df.head()) def __str__(self): return "\nmodel info:\n\tname = {0:s} \ \n\tstartdate = {1} \ \n\tenddate = {2} \ \n\ttime step = {3:.0f} minute(s) \ \n\tbase_elec_rate_file = {4:s} \ \n\tbase_charg_load_file = {5:s} \ \n\ttarget_charg_load_file = {6:s}\n".format(self.name, self.startdate, self.enddate, self.time_step, self.base_elec_rate_file, self.base_charg_load_file, self.target_charg_load_file) def get_time_from_bin(self, i): """ Returns the datetime object that corresponds to the time bin with index i. Parameters ---------- i : datetime Time bin index of desired time. """ return self.startdate + pd.Timedelta(hours=24*i/self.n_bins_per_day) def read_config(self): """ Retrieves information from the configuration file (self.configfile) and saves it into the corresponding class variables. """ self.cfg = pu.read_config_file(self.configfile) cfg = self.cfg["General Info"] self.name = cfg["name"] self.folder = cfg["folder"] #output folder or similar self.seed = None if cfg["seed"]=="None" else cfg["seed"] self.solver = cfg["solver"] # self.n_EVs = cfg["n_EVs"] self.startdate = pd.to_datetime(cfg["startdate"]) self.enddate = pd.to_datetime(cfg["enddate"]) self.time_step = int(cfg["time_step"]) #[minutes] self.duration = self.enddate - self.startdate self.n_days = int(np.ceil(self.duration.total_seconds()/(60*60*24))) #number of (partial) days self.n_bins_per_day = int(24*60/self.time_step) #number of bins in one day self.n_bins = int(self.duration.total_seconds() / (self.time_step*60)) #self.n_days * self.n_bins_per_day #number of bins in simulation time frame self.bins = np.array(range(self.n_bins)) self.xticks = [self.startdate + pd.Timedelta(minutes=self.time_step*i) for i in self.bins] # self.alpha = float(cfg["alpha"]) #response rate between electricity rate change and charging load change self.alpha_factor = float(cfg["alpha_factor"]) #factor to be multiplied with alpha_electricity_rate_increases and alpha_electricity_rate_decreases (to potentially enhance the response to price changes) self.alpha_electricity_rate_increases = self.alpha_factor * float(cfg["alpha_electricity_rate_increases"]) self.alpha_electricity_rate_decreases = self.alpha_factor * float(cfg["alpha_electricity_rate_decreases"]) self.tolerance_total_charged_energy_up = float(cfg["tolerance_total_charged_energy_up"]) self.tolerance_total_charged_energy_down = float(cfg["tolerance_total_charged_energy_down"]) self.max_electricity_rate_change_up = float(cfg["max_electricity_rate_change_up"]) self.max_electricity_rate_change_down = float(cfg["max_electricity_rate_change_down"]) self.mu_plugin, self.sigma_plugin = cfg["mu_plugin"], cfg["sigma_plugin"] self.mu_plugout, self.sigma_plugout = cfg["mu_plugout"], cfg["sigma_plugout"] #baseline electricity rate self.base_elec_rate_folder = cfg["base_elec_rate_folder"] self.base_elec_rate_file = cfg["base_elec_rate_file"] self.base_elec_rate_scale = float(cfg["base_elec_rate_scale"]) #baseline charging load self.base_charg_load_folder = cfg["base_charg_load_folder"] self.base_charg_load_file = cfg["base_charg_load_file"] self.base_charg_load_scale = float(cfg["base_charg_load_scale"]) #target charging load self.target_charg_load_folder = cfg["target_charg_load_folder"] self.target_charg_load_file = cfg["target_charg_load_file"] self.target_charg_load_scale = float(cfg["target_charg_load_scale"]) # cfg[""] def def_general_variables(self): """ Defines some general class variables, such as the main DataFrame object (self.df) or colors and labels in plots. Is called only once when instantiating the class object. """ #df self.df = pd.DataFrame(index = self.bins, columns = ["time", "base_elec_rate" , "opt_elec_rate", # "base_n_EVs_charging", # "res_n_EVs_charging", "base_charg_load", "target_charg_load", "res_charg_load"]) self.df["time"] = [self.get_time_from_bin(i) for i in self.df.index] self.df.index += 1 #prepare for pyomo being 1-indexed # self.datecut = str(self.startdate.date())+"_"+str(self.enddate.date()) self.datecut = ( str(self.startdate) + "_" + str(self.enddate) ).replace(":","-") #hardcoded variables self.figsize = (8,4) #legend next to plots self.x = self.df["time"] self.xlabel = "time" self.labels = {"opt_elec_rate": "Optimized electricity rate", "base_elec_rate": "Baseline electricity rate", "res_charg_load": "Resulting charging load", "base_charg_load": "Baseline charging load", "target_charg_load": "Target charging load", "rel_charg_load": r"$\frac{\mathrm{Resulting\;charging\;load}}{\mathrm{Baseline\;charging\;load}} - 1$"} self.labels.update({"CMA_opt_elec_rate": "Optimized electricity rate (CMA)", "CMA_base_elec_rate": "Baseline electricity rate (CMA)", "CMA_res_charg_load": "Resulting charging load (CMA)", "CMA_base_charg_load": "Baseline charging load (CMA)", "CMA_target_charg_load": "Target charging load (CMA)", "CMA_rel_charg_load": r"$\frac{\mathrm{Resulting\;charging\;load}}{\mathrm{Baseline\;charging\;load}} - 1$"}) settings = self.cfg["Plot Settings"] self.colors = {"opt_elec_rate": settings["col_OER"], "base_elec_rate": settings["col_BER"], "res_charg_load": settings["col_RCL"], "base_charg_load": settings["col_BCL"], "target_charg_load": settings["col_TCL"], "rel_charg_load": settings["col_rel_charg_load"]} self.colors.update({"CMA_opt_elec_rate": settings["col_OER"], "CMA_base_elec_rate": settings["col_BER"], "CMA_res_charg_load": settings["col_RCL"], "CMA_base_charg_load": settings["col_BCL"], "CMA_target_charg_load": settings["col_TCL"], "CMA_rel_charg_load": settings["col_rel_charg_load"]}) self.zorders = {"opt_elec_rate": float(settings["zor_OER"]), "base_elec_rate": float(settings["zor_BER"]), "res_charg_load": float(settings["zor_RCL"]), "base_charg_load": float(settings["zor_BCL"]), "target_charg_load": float(settings["zor_TCL"]), "rel_charg_load": float(settings["zor_RCL"])} self.zorders.update({"CMA_opt_elec_rate": float(settings["zor_OER"]), "CMA_base_elec_rate": float(settings["zor_BER"]), "CMA_res_charg_load": float(settings["zor_RCL"]), "CMA_base_charg_load": float(settings["zor_BCL"]), "CMA_target_charg_load": float(settings["zor_TCL"]), "CMA_rel_charg_load": float(settings["zor_RCL"])}) self.elec_rates = ["opt_elec_rate", "base_elec_rate"] self.charg_loads = ["res_charg_load", "base_charg_load", "target_charg_load"] def read_base_elec_rate(self): """ Reads-in the baseline electricity rate from the respective data file (self.base_elec_rate_file), by time of the day. Scales the numbers given in that file with self.base_elec_rate_scale. """ base_elec_rate = pd.read_csv(self.base_elec_rate_folder + self.base_elec_rate_file, sep=";", dtype={"electricity rate": float}) base_elec_rate.index += 1 #prepare for pyomo being 1-indexed if self.time_step > 1: for index in self.df.index: index2 = index - ((index-1)//self.n_bins_per_day)*self.n_bins_per_day self.df.loc[index, "base_elec_rate"] = base_elec_rate.loc[index2*self.time_step, "electricity rate"] else: # for i in range(self.n_days-1): # base_elec_rate = base_elec_rate.append(base_elec_rate, ignore_index=True) # self.df["base_elec_rate"] = base_elec_rate["electricity rate"] base_elec_rate =
pd.concat([base_elec_rate]*self.n_days, ignore_index=True)
pandas.concat
# Copyright (c) Microsoft Corporation and contributors. # Licensed under the MIT License. import logging import numpy as np import pandas as pd import pickle import scipy.optimize as opt from sklearn.dummy import DummyClassifier from time import time from ._constants import _PRECISION, _INDENTATION, _LINE from fairlearn.reductions._moments import ClassificationMoment from fairlearn.reductions._moments import CDF_DemographicParity logger = logging.getLogger(__name__) class _Lagrangian: """Operations related to the Lagrangian. Parameters ---------- X : {numpy.ndarray, pandas.DataFrame} the training features sensitive_features : {numpy.ndarray, pandas.Series, pandas.DataFrame, list} the sensitive features to use for constraints y : {numpy.ndarray, pandas.Series, pandas.DataFrame, list} the training labels estimator : the estimator to fit in every iteration of :meth:`best_h` using a :meth:`fit` method with arguments `X`, `y`, and `sample_weight` constraints : fairlearn.reductions.Moment Object describing the parity constraints. This provides the reweighting and relabelling. B : float bound on the L1-norm of the lambda vector opt_lambda : bool indicates whether to optimize lambda during the calculation of the Lagrangian; optional with default value True """ def __init__(self, X, sensitive_features, y, estimator, constraints, B, opt_lambda=True): self.X = X self.n = self.X.shape[0] self.y = y self.constraints = constraints self.constraints.load_data(X, y, sensitive_features=sensitive_features) self.obj = self.constraints.default_objective() self.obj.load_data(X, y, sensitive_features=sensitive_features) self.pickled_estimator = pickle.dumps(estimator) self.B = B self.opt_lambda = opt_lambda self.hs = pd.Series(dtype="float64") self.predictors = pd.Series(dtype="float64") self.errors =
pd.Series(dtype="float64")
pandas.Series
import pytest import numpy as np import pandas as pd import databricks.koalas as ks from pandas.testing import assert_frame_equal from gators.feature_generation.polynomial_features import PolynomialFeatures ks.set_option('compute.default_index_type', 'distributed-sequence') @pytest.fixture def data_inter(): X = pd.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.float64) obj = PolynomialFeatures( interaction_only=True, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 2.], [3., 4., 5., 12., 15., 20.], [6., 7., 8., 42., 48., 56.]]), columns=['A', 'B', 'C', 'A__x__B', 'A__x__C', 'B__x__C'] ) return obj, X, X_expected @pytest.fixture def data_int16_inter(): X = pd.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.int16) obj = PolynomialFeatures( interaction_only=True, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 2.], [3., 4., 5., 12., 15., 20.], [6., 7., 8., 42., 48., 56.]]), columns=['A', 'B', 'C', 'A__x__B', 'A__x__C', 'B__x__C'] ).astype(np.int16) return obj, X, X_expected @ pytest.fixture def data_all(): X = pd.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.float32) obj = PolynomialFeatures( interaction_only=False, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 0., 1., 2., 4.], [3., 4., 5., 9., 12., 15., 16., 20., 25.], [6., 7., 8., 36., 42., 48., 49., 56., 64.]]), columns=['A', 'B', 'C', 'A__x__A', 'A__x__B', 'A__x__C', 'B__x__B', 'B__x__C', 'C__x__C'] ).astype(np.float32) return obj, X, X_expected @ pytest.fixture def data_degree(): X = pd.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.float64) obj = PolynomialFeatures( interaction_only=False, degree=3, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 0., 1., 2., 4., 0., 0., 0., 0., 0., 0., 1., 2., 4., 8.], [3., 4., 5., 9., 12., 15., 16., 20., 25., 27., 36., 45., 48., 60., 75., 64., 80., 100., 125.], [6., 7., 8., 36., 42., 48., 49., 56., 64., 216., 252., 288., 294., 336., 384., 343., 392., 448., 512.]]), columns=['A', 'B', 'C', 'A__x__A', 'A__x__B', 'A__x__C', 'B__x__B', 'B__x__C', 'C__x__C', 'A__x__A__x__A', 'A__x__A__x__B', 'A__x__A__x__C', 'A__x__B__x__B', 'A__x__B__x__C', 'A__x__C__x__C', 'B__x__B__x__B', 'B__x__B__x__C', 'B__x__C__x__C', 'C__x__C__x__C'] ) return obj, X, X_expected @ pytest.fixture def data_inter_degree(): X = pd.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.float64) obj = PolynomialFeatures( interaction_only=True, degree=3, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 2., 0.], [3., 4., 5., 12., 15., 20., 60.], [6., 7., 8., 42., 48., 56., 336.]]), columns=['A', 'B', 'C', 'A__x__B', 'A__x__C', 'B__x__C', 'A__x__B__x__C'] ) return obj, X, X_expected @ pytest.fixture def data_subset(): X = pd.DataFrame(np.arange(12).reshape( 3, 4), columns=list('ABCD'), dtype=np.float64) obj = PolynomialFeatures( columns=['A', 'B', 'C'], interaction_only=True, degree=2).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 3., 0., 0., 2.], [4., 5., 6., 7., 20., 24., 30.], [8., 9., 10., 11., 72., 80., 90.]]), columns=['A', 'B', 'C', 'D', 'A__x__B', 'A__x__C', 'B__x__C'] ) return obj, X, X_expected @pytest.fixture def data_inter_ks(): X = ks.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.float64) obj = PolynomialFeatures( interaction_only=True, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 2.], [3., 4., 5., 12., 15., 20.], [6., 7., 8., 42., 48., 56.]]), columns=['A', 'B', 'C', 'A__x__B', 'A__x__C', 'B__x__C'] ) return obj, X, X_expected @pytest.fixture def data_int16_inter_ks(): X = ks.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.int16) obj = PolynomialFeatures( interaction_only=True, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 2.], [3., 4., 5., 12., 15., 20.], [6., 7., 8., 42., 48., 56.]]), columns=['A', 'B', 'C', 'A__x__B', 'A__x__C', 'B__x__C'] ).astype(np.int16) return obj, X, X_expected @ pytest.fixture def data_all_ks(): X = ks.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.float32) obj = PolynomialFeatures( interaction_only=False, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 0., 1., 2., 4.], [3., 4., 5., 9., 12., 15., 16., 20., 25.], [6., 7., 8., 36., 42., 48., 49., 56., 64.]]), columns=['A', 'B', 'C', 'A__x__A', 'A__x__B', 'A__x__C', 'B__x__B', 'B__x__C', 'C__x__C'] ).astype(np.float32) return obj, X, X_expected @ pytest.fixture def data_degree_ks(): X = ks.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.float64) obj = PolynomialFeatures( interaction_only=False, degree=3, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 0., 1., 2., 4., 0., 0., 0., 0., 0., 0., 1., 2., 4., 8.], [3., 4., 5., 9., 12., 15., 16., 20., 25., 27., 36., 45., 48., 60., 75., 64., 80., 100., 125.], [6., 7., 8., 36., 42., 48., 49., 56., 64., 216., 252., 288., 294., 336., 384., 343., 392., 448., 512.]]), columns=['A', 'B', 'C', 'A__x__A', 'A__x__B', 'A__x__C', 'B__x__B', 'B__x__C', 'C__x__C', 'A__x__A__x__A', 'A__x__A__x__B', 'A__x__A__x__C', 'A__x__B__x__B', 'A__x__B__x__C', 'A__x__C__x__C', 'B__x__B__x__B', 'B__x__B__x__C', 'B__x__C__x__C', 'C__x__C__x__C'] ) return obj, X, X_expected @ pytest.fixture def data_inter_degree_ks(): X = ks.DataFrame(np.arange(9).reshape( 3, 3), columns=list('ABC'), dtype=np.float64) obj = PolynomialFeatures( interaction_only=True, degree=3, columns=['A', 'B', 'C']).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 0., 0., 2., 0.], [3., 4., 5., 12., 15., 20., 60.], [6., 7., 8., 42., 48., 56., 336.]]), columns=['A', 'B', 'C', 'A__x__B', 'A__x__C', 'B__x__C', 'A__x__B__x__C'] ) return obj, X, X_expected @ pytest.fixture def data_subset_ks(): X = ks.DataFrame(np.arange(12).reshape( 3, 4), columns=list('ABCD'), dtype=np.float64) obj = PolynomialFeatures( columns=['A', 'B', 'C'], interaction_only=True, degree=2).fit(X) X_expected = pd.DataFrame(np.array( [[0., 1., 2., 3., 0., 0., 2.], [4., 5., 6., 7., 20., 24., 30.], [8., 9., 10., 11., 72., 80., 90.]]), columns=['A', 'B', 'C', 'D', 'A__x__B', 'A__x__C', 'B__x__C'] ) return obj, X, X_expected def test_inter_pd(data_inter): obj, X, X_expected = data_inter X_new = obj.transform(X) assert_frame_equal(X_new, X_expected) @pytest.mark.koalas def test_inter_ks(data_inter_ks): obj, X, X_expected = data_inter_ks X_new = obj.transform(X) assert_frame_equal(X_new.to_pandas(), X_expected) def test_inter_pd_np(data_inter): obj, X, X_expected = data_inter X_new = obj.transform_numpy(X.to_numpy()) assert np.allclose(X_new, X_expected) @pytest.mark.koalas def test_inter_ks_np(data_inter_ks): obj, X, X_expected = data_inter_ks X_new = obj.transform_numpy(X.to_numpy()) assert np.allclose(X_new, X_expected) def test_int16_inter_pd(data_int16_inter): obj, X, X_expected = data_int16_inter X_new = obj.transform(X) assert_frame_equal(X_new, X_expected) @pytest.mark.koalas def test_int16_inter_ks(data_int16_inter_ks): obj, X, X_expected = data_int16_inter_ks X_new = obj.transform(X) assert_frame_equal(X_new.to_pandas(), X_expected) def test_int16_inter_pd_np(data_int16_inter): obj, X, X_expected = data_int16_inter X_new = obj.transform_numpy(X.to_numpy()) assert np.allclose(X_new, X_expected) @pytest.mark.koalas def test_int16_inter_ks_np(data_int16_inter_ks): obj, X, X_expected = data_int16_inter_ks X_new = obj.transform_numpy(X.to_numpy()) assert np.allclose(X_new, X_expected) def test_all_pd(data_all): obj, X, X_expected = data_all X_new = obj.transform(X) assert_frame_equal(X_new, X_expected) @pytest.mark.koalas def test_all_ks(data_all_ks): obj, X, X_expected = data_all_ks X_new = obj.transform(X) assert_frame_equal(X_new.to_pandas(), X_expected) def test_all_pd_np(data_all): obj, X, X_expected = data_all X_numpy_new = obj.transform_numpy(X.to_numpy()) X_new = pd.DataFrame(X_numpy_new) X_expected = pd.DataFrame(X_expected.values) assert_frame_equal(X_new, X_expected) @pytest.mark.koalas def test_all_ks_np(data_all_ks): obj, X, X_expected = data_all_ks X_numpy_new = obj.transform_numpy(X.to_numpy()) X_new = pd.DataFrame(X_numpy_new) X_expected = pd.DataFrame(X_expected.values) assert_frame_equal(X_new, X_expected) def test_degree_pd(data_degree): obj, X, X_expected = data_degree X_new = obj.transform(X) assert_frame_equal(X_new, X_expected) @pytest.mark.koalas def test_degree_ks(data_degree_ks): obj, X, X_expected = data_degree_ks X_new = obj.transform(X) assert_frame_equal(X_new.to_pandas(), X_expected) def test_degree_pd_np(data_degree): obj, X, X_expected = data_degree X_numpy_new = obj.transform_numpy(X.to_numpy()) X_new = pd.DataFrame(X_numpy_new) X_expected = pd.DataFrame(X_expected.values) assert_frame_equal(X_new, X_expected) @pytest.mark.koalas def test_degree_ks_np(data_degree_ks): obj, X, X_expected = data_degree_ks X_numpy_new = obj.transform_numpy(X.to_numpy()) X_new = pd.DataFrame(X_numpy_new) X_expected = pd.DataFrame(X_expected.values) assert_frame_equal(X_new, X_expected) def test_inter_degree_pd(data_inter_degree): obj, X, X_expected = data_inter_degree X_new = obj.transform(X) assert_frame_equal(X_new, X_expected) @pytest.mark.koalas def test_inter_degree_ks(data_inter_degree_ks): obj, X, X_expected = data_inter_degree_ks X_new = obj.transform(X) assert_frame_equal(X_new.to_pandas(), X_expected) def test_inter_degree_pd_np(data_inter_degree): obj, X, X_expected = data_inter_degree X_numpy_new = obj.transform_numpy(X.to_numpy()) X_new = pd.DataFrame(X_numpy_new) X_expected = pd.DataFrame(X_expected.values) assert_frame_equal(X_new, X_expected) @pytest.mark.koalas def test_inter_degree_ks_np(data_inter_degree_ks): obj, X, X_expected = data_inter_degree_ks X_numpy_new = obj.transform_numpy(X.to_numpy()) X_new = pd.DataFrame(X_numpy_new) X_expected =
pd.DataFrame(X_expected.values)
pandas.DataFrame
import os import os.path import random from operator import add from datetime import datetime, date, timedelta import numpy as np import pandas as pd from matplotlib import pyplot as plt import seaborn as sns import shutil import ema_workbench import time ## Step 2: Function for initiating the main dictionary of climate stations def create_dic(a): '''Function: creating a dictionary for each climate station''' a = {} keys = ['fM', 'iPot', 'rSnow', 'dSnow', 'cPrec', 'dP', 'elev', 'lat', 'long', 'fileName'] a = {key: None for key in keys} return a def initialize_input_dict (mainFolderSki): ''' This function returns a dictionary , and addresses of 4 folders''' '''Step 1''' rootFolder = mainFolderSki inputFolder = os.path.join(rootFolder,'input') ablationFolder = os.path.join(inputFolder, 'Ablation') accumulationFolder = os.path.join(inputFolder, 'Accumulation') climate_ref_Folder = os.path.join(inputFolder, 'Climate_ref') climate_Ref_Folder_org = os.path.join(inputFolder, 'Climate_ref_no_randomness_0') climate_ref_Folder_rand_1 = os.path.join(inputFolder, 'Climate_ref_randomness_1') climate_ref_Folder_rand_2 = os.path.join(inputFolder, 'Climate_ref_randomness_2') '''Step 2: Reading all files names inside the Ablation, Accumulation, and Climate folders''' ablationFiles = [] for filename in os.walk(ablationFolder): ablationFiles = filename[2] accumulationFiles = list() for filename in os.walk(accumulationFolder): accumulationFiles = filename[2] climate_ref_Files = list() for filename in os.walk(climate_ref_Folder): climate_ref_Files = filename[2] '''Step 3: Reading files inside ablation folder ''' os.chdir(ablationFolder) with open(ablationFiles[0], 'r') as file: FM1 = file.read() with open(ablationFiles[1], 'r') as file: Ipot1 = file.read() with open(ablationFiles[2], 'r') as file: Rsnow1 = file.read() '''Step 4: Reading the lines of files inside ablation folder''' FM1 = FM1.replace('\n', '\t') FM1 = FM1.split('\t') Ipot1 = Ipot1.replace('\n', '\t').split('\t') Rsnow1 = Rsnow1.replace('\n', '\t').split('\t') '''Step 5: Reading the lines of files inside accumulation folder''' os.chdir(accumulationFolder) with open(accumulationFiles[0], 'r') as file: cPrec = file.read() with open(accumulationFiles[1], 'r') as file: dSnow1 = file.read() cPrec = cPrec.replace('\n', '\t') cPrec = cPrec.split('\t') dSnow1 = dSnow1.replace('\n', '\t').split('\t') '''Step 6: Reading the lines of files inside climate folder''' os.chdir(climate_ref_Folder) with open('pcp.txt', 'r') as file: pcpData = file.read() with open('tmp.txt', 'r') as file: tmpData = file.read() pcpData = pcpData.split('\n') for i in range(len(pcpData)): pcpData[i] = pcpData[i].split(',') '''Step 7: Initialazing the input dictionary of climate stations which holds the information of accumulation and ablation, and etc of the stations''' nameStn = [] for file in climate_ref_Files: if 'p.csv' in file: #nameStn.append('n_' + file[-25: -5]) nameStn.append(file[-25: -5]) stnDicts = [] for i in range(len(nameStn)): stnDicts.append(create_dic(nameStn[i])) '''Step 8: Assigning the file names to the dictionary''' for i in range (len(nameStn)): stnDicts[i]['fileName'] = nameStn[i] '''Step 9: Assigning the accumulation and ablation values''' for stnDict in stnDicts: for i, element in enumerate(FM1): if element == stnDict['fileName'][:]: #if element == stnDict['fileName'][2:]: stnDict['fM'] = FM1[i+1] for i, element in enumerate(Ipot1): if element == stnDict['fileName'][:]: #if element == stnDict['fileName'][2:]: stnDict['iPot'] = Ipot1[i+1] for i, element in enumerate(Rsnow1): if element == stnDict['fileName'][:]: #if element == stnDict['fileName'][2:]: stnDict['rSnow'] = Rsnow1[i+1] for i, element in enumerate(dSnow1): if element == stnDict['fileName'][:]: #if element == stnDict['fileName'][2:]: stnDict['dSnow'] = dSnow1[i+1] for i, element in enumerate(cPrec): stnDict['cPrec'] = cPrec[1] stnDict['dP'] = cPrec[3] '''Step 10: Assigning the elevation, Lat and long to the dictionaries''' for i in range(len(stnDicts)): for j in range(1, len(pcpData)): #if pcpData[j][1][2:-1] == stnDicts[i]['fileName'][2:]: if pcpData[j][1][:-1] == stnDicts[i]['fileName'][:]: stnDicts[i]['lat']= pcpData[j][2] stnDicts[i]['long']= pcpData[j][3] stnDicts[i]['elev']= pcpData[j][4] return stnDicts, inputFolder, ablationFolder, accumulationFolder, climate_ref_Folder, climate_Ref_Folder_org, \ climate_ref_Folder_rand_1, climate_ref_Folder_rand_2 # Step 3 Snow Model ## S3.1 Initializiing the main dictionary for a case study caseStudyStns = {} inputFolder = '' ablationFolder = '' accumulationFolder = '' climateFolder = '' climateFolder_org = '' climateFolder1 = '' climateFolder2 = '' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case1_sattel-hochstuckli' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case2_Atzmaening' root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case3_hoch-ybrig\setup1' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case4_villars-diablerets_elevations_b1339' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case4_villars-diablerets_elevations_b1822' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case4_villars-diablerets_elevations_b2000' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case4_villars-diablerets_elevations_b2500' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case5_champex' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case6_davos_elevations_b1564' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case6_davos_elevations_b2141' #root = r'C:\Saeid\Prj100\SA_2\snowModelUZH\case6_davos_elevations_b2584' ## calling the function with multiple return values caseStudyStns, inputFolder, ablationFolder, accumulationFolder, climateFolder, climateFolder_org, \ climateFolder1, climateFolder2 = initialize_input_dict(root) def copytree(src, dst, symlinks=False, ignore=None): for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) ## 1st column as index: makaing date from 01 01 1981 to 2099 12 31 from datetime import timedelta, date def daterange(start_date, end_date): for n in range(int ((end_date - start_date ).days + 1)): yield start_date + timedelta(n) ### OR Let's make this function in a more OOP way: class Policy_Ski: def __init__(self, x1SnowThershold): self.x1SnowThershold = x1SnowThershold def policy_release2(self): return(self.x1SnowThershold) def policy_release3(self): ''' this function should make a matrix of evaluation fot the condition of 100 day ay minimum condition''' pass class Economic_Model_Ski: def __init__(self, xCostDay, xRevenueDay): self.costDayFixed = xCostDay self.revenueDayFixed = xRevenueDay def economic_costDay(self): return(self.costDayFixed) def economic_revenueDay(self): return(self.revenueDayFixed) class RCP_Model: def __init__(self, xRCP, xClimateModel): self.input1 = round(xRCP) #self.input1 = xRCP self.input2 = xClimateModel def rcpGenerator(self): if self.input1 == 1: RCP = str(2.6) rcpInt = 1 if self.input1 == 2: RCP = str(4.5) rcpInt = 2 if self.input1 == 3: RCP = str(8.5) rcpInt = 3 return(RCP, rcpInt) def climateModel(self): a, b = RCP_Model.rcpGenerator(self) if b == 1: climateModel = round(self.input2*11) elif b == 2: climateModel = 11 + max(1,round(self.input2*25)) else: climateModel = 36 + max(1, round(self.input2*31)) return (int(climateModel)) def tipping_points_freq(df, xGoodDays): """ This function, calculates the frequency of tipping points for each individual resort """ dfColumns= df.columns scenarios_length= len(dfColumns) simulations_Length = len(df[dfColumns[1]]) tipping_freq = np.zeros(scenarios_length) for i in range (1, scenarios_length, 1): m = 0 for j in range (1 , simulations_Length, 1): if float(df[dfColumns[i]].iloc[j]) < xGoodDays: m += 1 if m == 3: tipping_freq[i] += 1 m = 0 else: m = 0 continue #break return tipping_freq # XLR Framework def snow_Model (xRCP=None, xClimateModel=None, Xfactor1 = None, X2fM = None, X3iPot = None, X4rSnow = None, X5temp = None, X6tempArt = None, xCostDay = None, xRevenueDay = None, x1SnowThershold = None, xGoodDays = None): '''' This function controls the Ski resort model in an XLR framework''' ''' VERY IMPORTANT --- Controling the randomness --- VERY IMPORTANT''' xClimateRandomness = round(Xfactor1) if (xClimateRandomness == 1): os.chdir(climateFolder_org) src = os.getcwd() os.chdir(climateFolder) dst = os.getcwd() #copytree(src, dst) print('Original CH2018 is being used') elif (xClimateRandomness == 2) : os.chdir(climateFolder1) src = os.getcwd() os.chdir(climateFolder) dst = os.getcwd() #copytree(src, dst) print('Random Climate realization version 1 is being used') else: os.chdir(climateFolder2) src = os.getcwd() os.chdir(climateFolder) dst = os.getcwd() #copytree(src, dst) print('Random Climate realization version 2 is being used') os.chdir(climateFolder) fnames = os.listdir() #randomness_pcp_tmp(fnames, Xfactor1) print('Snow_Model: Matching the station names values with CSV files!') '''Matching the station names values in the dictionary of stations with CSV files in Climate folder of the case Study''' pcpCaseStudy = [] tmpCaseStudy = [] if (xClimateRandomness == 1): for i in range(len(caseStudyStns)): pcpCaseStudy.append(os.path.join(climateFolder, caseStudyStns[i]['fileName'] + 'p.csv')) tmpCaseStudy.append(os.path.join(climateFolder, caseStudyStns[i]['fileName'] + 't.csv')) elif (xClimateRandomness == 2) : for i in range(len(caseStudyStns)): pcpCaseStudy.append(os.path.join(climateFolder1, caseStudyStns[i]['fileName'] + 'p.csv')) tmpCaseStudy.append(os.path.join(climateFolder1, caseStudyStns[i]['fileName'] + 't.csv')) else: for i in range(len(caseStudyStns)): pcpCaseStudy.append(os.path.join(climateFolder2, caseStudyStns[i]['fileName'] + 'p.csv')) tmpCaseStudy.append(os.path.join(climateFolder2, caseStudyStns[i]['fileName'] + 't.csv')) print('Snow_Model: Building a database for each csv file (tmp and pcp)!') '''Step 6: building a database for each precipitation and temperature file in Climate folder and saving them in a list''' '''6.1 reading the csv files as databases''' dfpcp = [None for _ in range(len(pcpCaseStudy))] dftmp = [None for _ in range(len(tmpCaseStudy))] for i in range(len(pcpCaseStudy)): dfpcp[i] =
pd.read_csv(pcpCaseStudy[i])
pandas.read_csv
''' Created on 9 de nov de 2020 @author: klaus ''' import jsonlines from folders import DATA_DIR, SUBMISSIONS_DIR import os from os import path import pandas as pd import numpy as np import urllib import igraph as ig from input.read_input import read_item_data, get_emb def create_ratio(mode = 'train',CUTOFF=50, which='domain_id',alternate=False): assert mode in ['train','val'] assert which in ['domain_id','category_id','item_id','price','condition'] df = read_item_data() df['price'] =
pd.qcut(df['price'].values,100)
pandas.qcut
# %% imports from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn.decomposition import PCA from sklearn.cluster import KMeans import pickle import numpy as np import pandas as pd import pandarallel from pandarallel import pandarallel from sgt import SGT import matplotlib.pyplot as plt import seaborn as sns import torch import torch.nn as nn import torch.nn.functional as F # %% embeddings_joined = pd.read_csv("../../csv_hackathon/all_pairings.csv") # shuffle frame embeddings_joined = embeddings_joined.sample(frac=1) paired_embeddings = embeddings_joined.iloc[:round(embeddings_joined.shape[0]/2), :] non_paired_embeddings = embeddings_joined.iloc[round(embeddings_joined.shape[0]/2):, :] #%% heavy_half = non_paired_embeddings.iloc[:,:401] light_half_shuffled = non_paired_embeddings.iloc[:,401:].sample(frac=1) non_paired_embeddings =
pd.concat([heavy_half, light_half_shuffled], axis=1)
pandas.concat
#This finds address matches between files by looking for exact matches on street number and 'fuzzy' matches on street name #the goal is to use Open Addresses files to assign geocoordinates import pandas as pd from fuzzywuzzy import fuzz from fuzzywuzzy import process import time import sys import unidecode #to remove accents import re from AddressFuncs import DirectionCheck, NameIsNumber import sys input_dir='data/TESTING/inputs/' output_dir='data/TESTING/outputs/' database=sys.argv[1] addresses=sys.argv[2] output=sys.argv[3] t1=time.time() #This is a semi-arbitrary cut off for fuzzy string matching cut_off=70 #Read input files df=
pd.read_csv(input_dir+database)
pandas.read_csv
import os import pathlib from itertools import chain import pandas as pd __all__ = ['ImageDataset', 'ImageClassFolderDataset'] class ImageDataset(): def __init__(self, root, image_format=['png', 'jpg', 'jpeg'], label_func=None): """Construct an image dataset label index. Args: root: image dataset file root. image_format: list, default ['png', 'jpg', 'jpeg']. label_func: if label_func is None, self.data['label'] is not exist; function is apply to self.data['image']. Returns: class, self.data['image'] is image path, self.data['label'] is image label. """ self.root = root self.image_format = image_format p = pathlib.Path(self.root) self.data = pd.DataFrame(chain.from_iterable((p.rglob(f'*.{i}') for i in self.image_format)), columns=['image']) if label_func is not None: self.data['label'] = self.data.image.map(lambda x:label_func(x.name)) self.data['image'] = self.data.astype(str).image.map(lambda x:eval(repr(x).replace("\\", '/').replace("//", '/'))) class ImageClassFolderDataset(): def __init__(self, root, image_format=['png', 'jpg', 'jpeg'], label_encoder=False): """Construct an image dataset label index. Args: root: image dataset file root. image_format: list, default ['png', 'jpg', 'jpeg']. label_encoder: whether encode labels with value between 0 and n_classes-1. Returns: class, self.data['image'] is image path, self.data['label'] is image label. """ self.root = root self.image_format = image_format file = os.listdir(self.root) file = [i for i in file if os.path.isdir(self.root+'/'+i) and i[0]!='.'] data =
pd.DataFrame()
pandas.DataFrame
import fnmatch import functools import os import dateutil import pandas as pd import pytest from bs4 import BeautifulSoup from tika import config from covid_data_briefing import briefing_atk from covid_data_briefing import briefing_case_types from covid_data_briefing import briefing_deaths_provinces from covid_data_briefing import briefing_deaths_summary from covid_data_briefing import briefing_documents from covid_data_briefing import briefing_province_cases from covid_data_briefing import vac_briefing_totals from covid_data_situation import get_english_situation_files from covid_data_situation import get_thai_situation_files from covid_data_situation import situation_cases_new from covid_data_situation import situation_pui_en from covid_data_situation import situation_pui_th from covid_data_testing import get_test_files from covid_data_testing import get_tests_by_area_chart_pptx from covid_data_testing import get_tests_by_area_pdf from covid_data_vac import vac_manuf_given from covid_data_vac import vac_slides_files from covid_data_vac import vaccination_daily from covid_data_vac import vaccination_reports_files2 from covid_data_vac import vaccination_tables from utils_scraping import parse_file from utils_scraping import pptx2chartdata from utils_scraping import sanitize_filename from utils_thai import file2date # do any tika install now before we start the run and use multiple processes config.getParsers() def dl_files(target_dir, dl_gen, check=False): "find csv files and match them to dl files, either by filename or date" dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path = os.path.join(dir_path, target_dir) downloads = {} for url, date, get_file in dl_gen(check): fname = sanitize_filename(url.rsplit("/", 1)[-1]) fname, _ = fname.rsplit(".", 1) # remove ext if date is not None: sdate = str(date.date()) downloads[sdate] = (sdate, get_file) # put in file so test is identified if no date downloads[fname] = (str(date.date()) if date is not None else fname, get_file) tests = [] missing = False for root, dir, files in os.walk(dir_path): for test in fnmatch.filter(files, "*.json"): base, ext = test.rsplit(".", 1) # special format of name with .2021-08-01 to help make finding test files easier if "." in base: rest, dateish = base.rsplit(".", 1) if file2date(dateish): base = rest # throw away date since rest is file to check against try: testdf = pd.read_json(os.path.join(root, test), orient="table") except (ValueError, TypeError): testdf = None # try: # testdf = import_csv(check.rsplit(".", 1)[0], dir=root, index=["Date"]) # except pd.errors.EmptyDataError: # testdf = None date, get_file = downloads.get(base, (None, None)) if get_file is None: if check: raise Exception(f"Can't match test file {dir_path}/{test} to any downloadable file") missing = True tests.append((date, testdf, get_file)) if missing and not check: # files not cached yet so try again return dl_files(target_dir, dl_gen, check=True) else: return tests def pair(files): "return paired up combinations and also wrap in a cache so they don't get done generated twice" all_files = [(link, get_file) for link, _, get_file in files()] return zip([link for link, _ in all_files[:-1]], [f for _, f in all_files[:-1]], [f for _, f in all_files[1:]]) def write_scrape_data_back_to_test(df, dir, fname=None, date=None): "Use this when you are sure the scraped data is correct" if fname is not None: fname = os.path.splitext(os.path.basename(fname))[0] if date is None: latest = df.index.max() if type(latest) == tuple: latest = latest[0] # Assume date is always first date = str(latest.date()) else: date = str(date.date()) if fname: # .{date} is ignored but helps to have when fname doesn't have date in it df.to_json(f"tests/{dir}/{fname}.{date}.json", orient='table', indent=2) else: df.to_json(f"tests/{dir}/{date}.json", orient='table', indent=2) # 2021-07-05 0.0 # 2021-07-06 0.0 # 2021-07-07 0.0 # 2021-07-08 0.0 # 2021-07-09 0.0 # 2021-07-10 0.0 # 2021-07-11 0.0 @pytest.mark.parametrize("fname, testdf, get_file", dl_files("vaccination_daily", vaccination_reports_files2)) def test_vac_reports(fname, testdf, get_file): assert get_file is not None file = get_file() # Actually download assert file is not None df = pd.DataFrame(columns=["Date"]).set_index(["Date"]) for page in parse_file(file): df = vaccination_daily(df, None, file, page) # write_scrape_data_back_to_test(df, "vaccination_daily", fname) pd.testing.assert_frame_equal(testdf.dropna(axis=1), df.dropna(axis=1), check_dtype=False, check_like=True) # @pytest.mark.skip() # @pytest.mark.parametrize("link, content, get_file", list(vaccination_reports_files2())) # def test_vac_reports_assert(link, content, get_file): # assert get_file is not None # file = get_file() # Actually download # if file is None: # return # df = pd.DataFrame(columns=["Date"]).set_index(["Date"]) # for page in parse_file(file): # df = vaccination_daily(df, None, file, page) @functools.lru_cache def parse_vac_tables(*files): df = pd.DataFrame(columns=["Date"]).set_index(["Date"]) for get_file in files: assert get_file is not None file = get_file() # Actually download assert file is not None for page in parse_file(file): df = vaccination_tables(df, None, page, file) return df @pytest.mark.skip() @pytest.mark.parametrize("link, get_file1, get_file2", pair(vaccination_reports_files2)) def test_vac_tables_inc(link, get_file1, get_file2): if (df1 := parse_vac_tables(get_file1)).empty: return if (df2 := parse_vac_tables(get_file2)).empty: return # TODO: some files have no data in. So really need to get a range and compare to the last one with data? df = df1.combine_first(df2).dropna(axis=1) # don't compare empty cols if len(df.index) < 154: # for some reason two files gave data for the same day? # TODO: should be an error somewhere else? return # Ensure we didn't jump too much but only when we have min num of vac given cols = [c for c in df.columns if " Cum" in c] if not cols: return change = df[cols].clip(14000).groupby("Province").pct_change() dates = [str(d.date()) for d in df.reset_index("Province").index.unique()] assert (change.max() < 15).all(), f"jump in {get_file1()} {dates} in {change.max()}" @pytest.mark.parametrize("fname, testdf, get_file", dl_files("vaccination_tables", vaccination_reports_files2)) def test_vac_tables(fname, testdf, get_file): df = parse_vac_tables(get_file) df = df.dropna(axis=1) # don't compare empty cols # write_scrape_data_back_to_test(df, "vaccination_tables", fname) pd.testing.assert_frame_equal(testdf, df, check_dtype=False, check_like=True) @pytest.mark.parametrize("fname, testdf, get_file", dl_files("vac_manuf_given", vac_slides_files)) def test_vac_manuf_given(fname, testdf, get_file): assert get_file is not None file = get_file() # Actually download assert file is not None df =
pd.DataFrame(columns=["Date"])
pandas.DataFrame
import logging import os import time import numpy as np import pandas as pd from flask import Flask, Response, request import config import dataset import torch import torch.utils.data from model import BERTBaseUncased app = Flask(__name__) MODEL = None DEVICE = "cpu" os.environ["TOKENIZERS_PARALLELISM"] = "false" def generate_predictions(df): df.reset_index(drop=True, inplace=True) predict_dataset = dataset.BERTDataset(review=df.PROCESSED_TEXT.values) predict_data_loader = torch.utils.data.DataLoader( predict_dataset, batch_size=config.PREDICT_BATCH_SIZE, num_workers=config.NUM_WORKERS, ) test_preds = np.zeros(df.shape[0]) with torch.no_grad(): for bi, d in enumerate(predict_data_loader): ids = d["ids"] token_type_ids = d["token_type_ids"] mask = d["mask"] ids = ids.to(DEVICE, dtype=torch.long) token_type_ids = token_type_ids.to(DEVICE, dtype=torch.long) mask = mask.to(DEVICE, dtype=torch.long) preds = MODEL(ids=ids, mask=mask, token_type_ids=token_type_ids) test_preds[ bi * config.PREDICT_BATCH_SIZE : (bi + 1) * config.PREDICT_BATCH_SIZE ] = (preds[:, 0].detach().cpu().squeeze().numpy()) output = torch.sigmoid(torch.tensor(test_preds)).numpy().ravel() return output @app.route("/predict") def predict(): data = request.args.get("data") account = request.args.get("account") df =
pd.read_json(data)
pandas.read_json
import hashlib import re from typing import List, Tuple, Union from sklearn.feature_extraction.text import TfidfVectorizer import numpy as np import pandas as pd def md5_hash(text: str) -> str: """ Generate MD5 hash of a text. Args: text: String Returns: MD5 hash """ return hashlib.md5(text.encode("utf-8")).hexdigest() def sha256hash(text: str) -> str: """ Generate MD5 hash of a text. Args: text: String Returns: SHA256 hash """ return hashlib.sha256(text.encode("utf-8")).hexdigest() def window(tokens, size: int = 3): """ Generate samples for a window size. Example: ```python >>> window(['a', 'b', 'c', 'd'], size=2) [(['a', 'b'], 'c'), (['b', 'c'], 'd')] ``` Args: tokens: List of tokens size: Window size Returns: List of windowed samples """ return [ (tokens[i : i + size], tokens[i + size]) for i in range(0, len(tokens) - size, 1) ] def offset_by_one(x, sequence_length: int = 3): """ Generate a list of small sequences offset by 1. Usage: ```python >>> offset_by_one([1, 2, 3, 4, 5], sequence_length=3) [([1, 2, 3], [2, 3, 4])] ``` Args: x: Python list sequence_length: Chunk size Returns: """ sl = sequence_length return [ (x[i : i + sl], x[i + 1 : i + sl + 1]) for i in range(0, len(x) - sl - 1, sl) ] def num_words(text: str) -> int: """ Counts the number of words using whitespace as delimiter. Args: text: Sentence Returns: Number of words """ return len(text.split()) def unique_chars(texts: List[str]) -> List[str]: """ Get a list of unique characters from list of text. Args: texts: List of sentences Returns: A sorted list of unique characters """ return sorted(set("".join(texts))) def is_non_ascii(text: str) -> bool: """ Check if text has non-ascci characters. Useful heuristic to find text containing emojis and non-english characters. Args: text: Sentence Returns: True if the text contains non-ascii characters. """ try: text.encode("ascii") return False except UnicodeEncodeError: return True def span_positions(text: str, phrases: List[str]) -> List[Tuple[int, int]]: """ Find span position of phrases in a text. Args: text: Sentence phrases: List of phrases Returns: List of span positions for each phrase. The span position is a tuple of start and end index. """ capture_group = "|".join([re.escape(phrase) for phrase in phrases]) reg = re.compile(rf"\b({capture_group})\b", flags=re.IGNORECASE) return [match.span() for match in reg.finditer(text)] def extract_abbreviations(texts: List[str]) -> List[str]: """ Get a list of all-capitalized words. Example: WWW, HTTP, etc. Args: texts: List of sentences Returns: List of abbreviations """ combined_text = "\n".join(texts) symbols = re.findall(r"\b[A-Z][A-Z]+\b", combined_text) return list(set(symbols)) def export_fasttext_format( texts: List[str], labels: Union[List[str], List[List[str]]], filename ) -> None: """ Export training data to a fasttext compatible format. Format: __label__POSITIVE it was good Args: texts: List of sentences labels: List of single or multi-label classes filename: Exported filename Returns: None """ output = [] for text, text_label in zip(texts, labels): if type(text_label) is str: text_label = [text_label] labels = " ".join([f"__label__{label}" for label in text_label]) output.append(f"{labels} {text}\n") with open(filename, "w") as fp: fp.writelines(output) def extract_tfidf_keywords(texts: List[str], ngram: int = 2, n: int = 10) -> List[str]: """ Get top keywords based on mean tf-idf term score. Args: texts: List of sentences ngram: 1 for words, 2 for bigram and so on. n: Number of keywords to extract Returns: Keywords """ tfidf = TfidfVectorizer( ngram_range=(1, ngram), stop_words="english", strip_accents="unicode", sublinear_tf=True, ) vectors = tfidf.fit_transform(texts) term_tfidf = vectors.A.mean(axis=0) terms = np.array(tfidf.get_feature_names()) return terms[term_tfidf.argsort()[::-1]][:n].tolist() def extract_discriminative_keywords( df: pd.DataFrame, category_column: str, text_column: str, ngram: int = 2, n: int = 10, ) -> pd.DataFrame: """ Generate discriminative keywords for texts in each category. Args: df: Dataframe with text and category columns. text_column: Column name containing texts category_column: Column name for the text category ngram: 1 for words, 2 for bigram and so on. n: Number of keywords to return. Returns: Dataframe with categories in columns and top-n keywords in each columns. """ # Combine all texts into a single document for each category category_docs = df.groupby(by=category_column)[text_column].apply(" ".join) categories = category_docs.index.tolist() tfidf = TfidfVectorizer( ngram_range=(1, ngram), stop_words="english", strip_accents="unicode", sublinear_tf=True, ) document_vectors = tfidf.fit_transform(category_docs).A keywords = np.array(tfidf.get_feature_names()) top_terms = document_vectors.argsort(axis=1)[:, :n] return
pd.DataFrame(keywords[top_terms].T, columns=categories)
pandas.DataFrame
# pylint: disable=E1101 from datetime import datetime, timedelta from pandas.compat import range, lrange, zip, product import numpy as np from pandas import Series, TimeSeries, DataFrame, Panel, isnull, notnull, Timestamp from pandas.tseries.index import date_range from pandas.tseries.offsets import Minute, BDay from pandas.tseries.period import period_range, PeriodIndex, Period from pandas.tseries.resample import DatetimeIndex, TimeGrouper import pandas.tseries.offsets as offsets import pandas as pd import unittest import nose from pandas.util.testing import (assert_series_equal, assert_almost_equal, assert_frame_equal) import pandas.util.testing as tm bday = BDay() def _skip_if_no_pytz(): try: import pytz except ImportError: raise nose.SkipTest class TestResample(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): dti = DatetimeIndex(start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq='Min') self.series = Series(np.random.rand(len(dti)), dti) def test_custom_grouper(self): dti = DatetimeIndex(freq='Min', start=datetime(2005, 1, 1), end=datetime(2005, 1, 10)) s = Series(np.array([1] * len(dti)), index=dti, dtype='int64') b = TimeGrouper(Minute(5)) g = s.groupby(b) # check all cython functions work funcs = ['add', 'mean', 'prod', 'ohlc', 'min', 'max', 'var'] for f in funcs: g._cython_agg_general(f) b = TimeGrouper(Minute(5), closed='right', label='right') g = s.groupby(b) # check all cython functions work funcs = ['add', 'mean', 'prod', 'ohlc', 'min', 'max', 'var'] for f in funcs: g._cython_agg_general(f) self.assertEquals(g.ngroups, 2593) self.assert_(notnull(g.mean()).all()) # construct expected val arr = [1] + [5] * 2592 idx = dti[0:-1:5] idx = idx.append(dti[-1:]) expect =
Series(arr, index=idx)
pandas.Series
""" Say you Initially This script takes the Options_averages_calls.db & Options_averages_puts.db files created with contracts_avg_volume.py combines it with the """ import sqlite3 import os import pandas as pd import time from sqlalchemy import create_engine from pandas.io.sql import DatabaseError os.system('afplay /System/Library/Sounds/Sosumi.aiff') def get_time_now(): curr_time = time.localtime() curr_clock = time.strftime("%H:%M:%S", curr_time) curr_m = time.strftime('%m') curr_y_d = time.strftime('%d%Y') int_curr_clock = int(f'{curr_clock[:2]}{curr_clock[3:5]}') return int_curr_clock, curr_m, curr_y_d t, mon, day = get_time_now() def add_rows(clean_data, table_name, calls_puts, d): temp_d = d # d = int(d) - 10000 # for doing averages of yesterday d = int(d) if temp_d[0] == '0': engine = create_engine(f'sqlite:///Options_averages_{calls_puts}_0{d}.db', echo=False) else: engine = create_engine(f'sqlite:///Options_averages_{calls_puts}_{d}.db', echo=False) clean_data.to_sql(table_name, con=engine, if_exists='append', index_label='index') return 0 def update_averages(data_file, call_file, put_file): con = sqlite3.connect(f'AvgData/{data_file}') # next mining day file con_c = sqlite3.connect(f'{call_file}') # last average file con_p = sqlite3.connect(f'{put_file}') # last average file cursor = con.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='table'") for tab in cursor.fetchall(): Tab = str(tab[0]) temp_date = (mon+day)[:4] if Tab[0][0] == 'c': calls = pd.read_sql_query( f'SELECT symbol, totalVolume, quoteTimeInLong FROM \'{Tab}\' WHERE (totalVolume > 10) AND (symbol LIKE \"%!_07%\" ESCAPE \"!\" OR symbol LIKE \"%!_08%\" ESCAPE \"!\") ', con) symbol_count = 0 for i, r in calls.iterrows(): temp_sym = r['symbol'] temp_stock = temp_sym.split('_')[0] next_date = temp_sym.split('_')[1][:4] if next_date < (mon+day)[:4]: continue if next_date >= temp_date: temp_date = next_date try: temp_calls = pd.read_sql_query(f'SELECT * FROM \'{Tab + temp_date}\' ', con_c) if temp_sym in temp_calls.values: temp_row = temp_calls.loc[temp_calls['symbol'] == temp_sym].copy() temp_row.drop(['index'], axis='columns', inplace=True) temp_row.index = [symbol_count] temp_avg = temp_row['avgVolume'] * temp_row['daysComputed'] temp_days = temp_row['daysComputed'] + 1 temp_avg = (temp_avg + r['totalVolume']) // temp_days temp_row.at[symbol_count, 'avgVolume'] = temp_avg temp_row.at[symbol_count, 'daysComputed'] = temp_days symbol_count = symbol_count + 1 add_rows(temp_row, f'c{temp_stock}{next_date}', 'calls', f'{mon}{day}') else: new_row = {'symbol': [temp_sym], 'avgVolume': [r['totalVolume']], 'daysComputed': [1]} working_new = pd.DataFrame(data=new_row) working_new.index = [symbol_count] add_rows(working_new, f'c{temp_stock}{next_date}', 'calls', f'{mon}{day}') symbol_count = symbol_count + 1 except DatabaseError as e: if e.args[0].startswith('Execution failed on sql'): new_row = {'symbol': [temp_sym], 'avgVolume': [r['totalVolume']], 'daysComputed': [1]} working_new =
pd.DataFrame(data=new_row)
pandas.DataFrame
from itertools import chain import operator import numpy as np import pytest from pandas.core.dtypes.common import is_number from pandas import ( DataFrame, Index, Series, ) import pandas._testing as tm from pandas.core.groupby.base import maybe_normalize_deprecated_kernels from pandas.tests.apply.common import ( frame_transform_kernels, series_transform_kernels, ) @pytest.mark.parametrize("func", ["sum", "mean", "min", "max", "std"]) @pytest.mark.parametrize( "args,kwds", [ pytest.param([], {}, id="no_args_or_kwds"), pytest.param([1], {}, id="axis_from_args"), pytest.param([], {"axis": 1}, id="axis_from_kwds"), pytest.param([], {"numeric_only": True}, id="optional_kwds"), pytest.param([1, True], {"numeric_only": True}, id="args_and_kwds"), ], ) @pytest.mark.parametrize("how", ["agg", "apply"]) def test_apply_with_string_funcs(request, float_frame, func, args, kwds, how): if len(args) > 1 and how == "agg": request.node.add_marker( pytest.mark.xfail( raises=TypeError, reason="agg/apply signature mismatch - agg passes 2nd " "argument to func", ) ) result = getattr(float_frame, how)(func, *args, **kwds) expected = getattr(float_frame, func)(*args, **kwds)
tm.assert_series_equal(result, expected)
pandas._testing.assert_series_equal
import numpy as np import pandas as pd # メモリ削減関数 def reduce_mem_usage(df, verbose=False): start_mem_usg = df.memory_usage().sum() / 1024**2 numerics = ['int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64'] print("Memory usage of properties dataframe is :", start_mem_usg, " MB") NAlist = [] # Keeps track of columns that have missing values filled in. for col in df.columns: # if df[col].dtype != object: # Exclude strings col_type = df[col].dtypes if col_type in numerics: # Print current column type if verbose: print("******************************") print("Column: ",col) print("dtype before: ",df[col].dtype) # make variables for Int, max and min IsInt = False mx = df[col].max() mn = df[col].min() # print("min for this col: ",mn) # print("max for this col: ",mx) # Integer does not support NA, therefore, NA needs to be filled if not np.isfinite(df[col]).all(): NAlist.append(col) df[col] = df[col].astype(np.float32) # df[col].fillna(mn-1,inplace=True) else: # test if column can be converted to an integer asint = df[col].fillna(0).astype(np.int64) result = (df[col] - asint) result = result.sum() if result > -0.01 and result < 0.01: IsInt = True # Make Integer/unsigned Integer datatypes if IsInt: if mn >= 0: if mx < 255: df[col] = df[col].astype(np.uint8) elif mx < 65535: df[col] = df[col].astype(np.uint16) elif mx < 4294967295: df[col] = df[col].astype(np.uint32) else: df[col] = df[col].astype(np.uint64) else: if mn > np.iinfo(np.int8).min and mx < np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif mn > np.iinfo(np.int16).min and mx < np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif mn > np.iinfo(np.int32).min and mx < np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif mn > np.iinfo(np.int64).min and mx < np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) # Make float datatypes 32 bit else: df[col] = df[col].astype(np.float32) if verbose: # Print new column type print("dtype after: ",df[col].dtype) print("******************************") # Print final result print("___MEMORY USAGE AFTER COMPLETION:___") mem_usg = df.memory_usage().sum() / 1024**2 print("Memory usage is: ", mem_usg, " MB") print("This is ", 100*mem_usg/start_mem_usg, "% of the initial size") # return df, NAlist return df def reduce_mem_usage_old(df, verbose=True): numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] start_mem = df.memory_usage().sum() / 1024**2 for col in df.columns: col_type = df[col].dtypes if col_type in numerics: c_min = df[col].min() c_max = df[col].max() if str(col_type)[:3] == 'int': if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) else: if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max: df[col] = df[col].astype(np.float16) elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max: df[col] = df[col].astype(np.float32) else: df[col] = df[col].astype(np.float64) end_mem = df.memory_usage().sum() / 1024**2 if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)' .format(end_mem, 100 * (start_mem - end_mem) / start_mem)) return df def downcast(df): cols = df.dtypes.index.tolist() types = df.dtypes.values.tolist() for i, t in enumerate(types): if 'int' in str(t): if df[cols[i]].min() > np.iinfo(np.int8).min and df[cols[i]].max() < np.iinfo(np.int8).max: df[cols[i]] = df[cols[i]].astype(np.int8) elif df[cols[i]].min() > np.iinfo(np.int16).min and df[cols[i]].max() < np.iinfo(np.int16).max: df[cols[i]] = df[cols[i]].astype(np.int16) elif df[cols[i]].min() > np.iinfo(np.int32).min and df[cols[i]].max() < np.iinfo(np.int32).max: df[cols[i]] = df[cols[i]].astype(np.int32) else: df[cols[i]] = df[cols[i]].astype(np.int64) elif 'float' in str(t): if df[cols[i]].min() > np.finfo(np.float16).min and df[cols[i]].max() < np.finfo(np.float16).max: df[cols[i]] = df[cols[i]].astype(np.float16) elif df[cols[i]].min() > np.finfo(np.float32).min and df[cols[i]].max() < np.finfo(np.float32).max: df[cols[i]] = df[cols[i]].astype(np.float32) else: df[cols[i]] = df[cols[i]].astype(np.float64) elif t == np.object: if cols[i] == 'date': df[cols[i]] =
pd.to_datetime(df[cols[i]], format='%Y-%m-%d')
pandas.to_datetime
import pathlib import re import pandas as pd def lnc_txt2csv(): p_temp = pathlib.Path('ldcc-20140209/text') article_list = [] # フォルダ内のテキストファイルを全てサーチ for p in p_temp.glob('**/*.txt'): # フォルダ名からニュースサイトの名前を取得 media = str(p.parent.stem) # 拡張子を除くファイル名を取得 file_name = str(p.stem) if file_name != 'LICENSE.txt': # テキストファイルを読み込む with open(p, 'r') as f: # テキストファイルの中身を一行ずつ読み込み、リスト形式で格納 article = f.readlines() # 不要な改行等を置換処理 article = [re.sub(r'[\s\u3000]', '', i) for i in article] # ニュースサイト名・記事URL・日付・記事タイトル・本文の並びでリスト化 article_list.append([media, article[0], article[1], article[2], ''.join(article[3:])]) else: continue article_df = pd.DataFrame(article_list, columns=[ 'Name', 'URL', 'Date', 'Title', 'Body']) path_lnp_csv = p_temp.parent.joinpath('csv/lnp.csv') path_lnp_csv.parent.mkdir(parents=True, exist_ok=True) article_df.to_csv(path_lnp_csv) def extract_words_in_lnc(self, category: str): ''' livedoor_news_corpusから単語を抽出します。 ''' article_df =
pd.read_csv('ldcc-20140209/csv/lnp.csv')
pandas.read_csv
import pandas as pd import math from csv import reader """https://www.easycalculation.com/statistics/standard-deviation.php""" pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) pd.set_option('display.max_colwidth', None) pd.options.display.float_format = '{:.8f}'.format class data(): """Generic Data class created in order to deal with the different kinds of Data Objects required for the project.""" def __init__(self, filepath, declared_type_df): self.filepath = str(filepath) self.df_toddbb = pd.DataFrame() self.df = pd.read_csv(filepath) self.columns = list(self.df.columns) self.n_columns = len(self.df.columns) self.type_df = str(self.find_type_of_df(self.n_columns)) self.data_type_valid = self.df_is_numeric(self.df) if self.type_df != 'test': self.df = self.df.sort_values(by=self.df.columns[0], ascending=True) def df_is_numeric(self,df): temp_data = df.apply(lambda s:
pd.to_numeric(s, errors="coerce")
pandas.to_numeric
# -*- coding: utf-8 -*- """ Created on Mon Apr 9 11:15:48 2018 @author: bfyang.cephei """ import numpy as np import pandas as pd #import pandas_datareader.data as web #import tushare as ts #import datetime #============================================================================== def poss_date(date): if len(date) == 10: return date[:4]+'-'+date[5:7]+'-'+date[8:] elif len(date) == 8: return date[:4]+'-0'+date[5]+'-0'+date[-1] elif date[-2] == r'/': return date[:4]+'-'+date[5:7]+'-0'+date[-1] else: return date[:4]+'-0'+date[5]+'-'+date[-2:] data = pd.read_csv(r'C:\Users\bfyang.cephei\Desktop\CTA\data\daybar_20180204\futures_20180204.csv') data['tradedate'] = data['tradedate'].apply(lambda x : poss_date(x)) data_train = data[(data['tradedate']>='2017-01-01') & (data['tradedate']<='2017-01-31')] #============================================================================== data_train.head() ## sklearn from sklearn import linear_model y_train = (data_train['close']-data_train['pre_close'])/data_train['pre_close'] y_train = np.array(y_train.fillna(0)) x_train = data_train[['swing','oi','open']] x_train = np.array(x_train.fillna(0)) data_test = data[(data['tradedate']>='2017-02-01') & (data['tradedate']<='2017-02-31')] y_test = (data_test['close']-data_test['pre_close'])/data_test['pre_close'] y_test = np.array(y_test.fillna(0)) x_test = data_test[['swing','oi','open']] x_test = np.array(x_test.fillna(0)) # Create linear regression object linear = linear_model.LinearRegression() # Train the model using the training sets and check score linear.fit(x_train,y_train) linear.score(x_train, y_train) #Equation coefficient and Intercept print('Coefficient: n', linear.coef_) # 贝塔系数 print('Intercept: n', linear.intercept_) # #Predict Output predicted= linear.predict(x_test) # correlation res1 = np.corrcoef(predicted,y_test) # numpy 数组格式求相关系数 res2 = pd.Series(predicted).corr(pd.Series(y_test)) # dataframe 数据格式求相关系数 import os os.chdir('D:/yh_min-mfactors') from poss_data_format import * from address_data import * import pandas as pd import statsmodels.api as sm import numpy as np # 某一时间截面,所有个股的收益对所有个股的各个因子进行多元回归, # 得到某个因子在某个时间个股的残差值,数据量191*227*300,得到有效因子 # 然后对每个截面求得预测收益和实际收益的相关系数,即IC(t)值,最后得到一个时间序列的IC值 # 对IC值进行T检验 # 第一步 读取行业数据 code_HS300 = pd.read_excel(add_gene_file + 'data_mkt.xlsx',sheetname='HS300') stockList = list(code_HS300['code'][:]) industry = pd.read_pickle\ (add_gene_file + 'industry.pkl').drop_duplicates() industry = industry[industry['code'].isin(stockList)] industry.index = industry['code'] industry.drop(['code'],axis = 1,inplace = True) industry = industry.T industry.reset_index(inplace = True) industry.rename(columns={'index':'date'},inplace = True) # 第二步 读取风格因子数据 # 因子数据截止到2017-12-06日' style_filenames = os.listdir(add_Nstyle_factors) style_list = list(map(lambda x : x[:-4],style_filenames)) for sfilename in style_filenames: names = locals() names[sfilename[:-4]] = pd.read_csv(add_Nstyle_factors+sfilename) # 第三步 因子值回归,得到行业和风格中性的因子残差值 def resid(x, y): return sm.OLS(x, y).fit().resid def beta_value(x, y): return sm.OLS(x, y).fit().params def possess_alpha(alpha_data, saf): alpha_data['code'] = alpha_data['code'].apply(lambda x:add_exchange(poss_symbol(x))) mid_columns = ['code'] + [x for x in list(alpha_data.columns)[1:] \ if x >='2017-01-01'and x<='2017-12-06'] alpha_data = alpha_data.loc[:,mid_columns] alpha_data.index = alpha_data['code'] alpha_data.drop(['code'],axis = 1,inplace = True) alpha_data = alpha_data.T alpha_data.reset_index(inplace = True) alpha_data.rename(columns={'index':'date'},inplace = True) return alpha_data standard_alpha = os.listdir(add_alpha_day_stand) for saf in standard_alpha: alpha_d =
pd.read_pickle(add_alpha_day_stand + saf)
pandas.read_pickle
from typing import Sequence import pandas as pd import numpy as np import logging import sys import click import joblib from pathlib import Path from collections import OrderedDict from sklearn.metrics import roc_auc_score, accuracy_score, average_precision_score, f1_score, \ confusion_matrix, classification_report from bac.util.config import parse_config from bac.util.io import load_data_partitions, load_feature_labels, load_model from bac.util.data_cleaning import split_data, fill_missing_data from bac.models.model_schemas import ModelSchemas from bac.viz.viz_model_performance import plot_ROC_comparison from bac.features.feature_importances import compute_feature_importances logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stdout, level=logging.INFO) # TODO: Would have to configure a logger elsewhere for all files to use # handler = logging.FileHandler(filename='/mnt/data/logs/evaluate.log', mode='w') # logger.addHandler(handler) def get_model_features_target(model_schema: ModelSchemas, X_test: pd.DataFrame, y_test: pd.Series) -> (pd.DataFrame, pd.Series): """Given a ModelSchema, define X and y for evaluation. e.g., subset the features or perform another modification. Args: model_schema (ModelSchemas): A schema obj defining a model, features, target X_test (pd.DataFrame): The complete feature set for evaluation y_test (pd.Series): The original target for evaluation Returns: A new X and y, with a subset of features or other modification """ model_name = model_schema["name"] logging.info(f"Loading model schema: {model_name}") subset_columns = model_schema['features'] target = model_schema["target"] X = X_test[subset_columns] y = y_test return X, y class ModelEvaluator(): def __init__(self, y_true: pd.Series, y_prob: pd.Series): """Evaluate a classification model's performance, given the vectors of true observatiosn & predicted probabilities Args: y_true (pd.Series): Obs y-values y_prob (pd.Series): Predicted probabilities """ self.y_true = y_true self.y_prob = y_prob # Assumes a discrimination threshold of .5 # TODO: May want to implement ability to use other thresholds self.y_pred = [round(prob) for prob in y_prob] # Compute model performance metrics for an sklearn classifier self.metrics = OrderedDict() self.cm = None self.get_classifier_metrics() self.get_confusion_matrix_metrics() self.log_metrics() def log_metrics(self): for score_type, value in self.metrics.items(): logging.info(f'Evaluator -- {score_type}: {value}.') logging.info('\n') def get_classifier_metrics(self): """Evaluate a classification model's performance with standard metrics. Assigns a dictionary obj for self.metrics: """ assert self.y_true.size>0 assert self.y_prob.size == self.y_true.size self.metrics['roc_auc'] = roc_auc_score(self.y_true, self.y_prob, max_fpr=None) self.metrics['accuracy'] = accuracy_score(self.y_true, self.y_pred) self.metrics['f1_score'] = f1_score(self.y_true, self.y_pred, average='weighted') def get_confusion_matrix(self): """ Compute the confusion matrix for a classifier model.""" self.cm = confusion_matrix(self.y_true, self.y_pred) logging.info(f"\nConfusion Matrix:\n{self.cm}\n") def get_confusion_matrix_metrics(self) -> Sequence[float]: """ Compute additional statistics from the confusion matrix.""" if self.cm is None: self.get_confusion_matrix() tn, fp, fn, tp = self.cm.ravel() self.metrics["sensitivity"] = tp/(fn+tp)# same as recall self.metrics["specificity"] = 1 - (fp/(tn+fp)) self.metrics["precision"] = tp/(tp+fp) def log_classification_report(self, target_names: Sequence[str]): if len(target_names) != len(self.y_true.unique()): raise ValueError(f"N-target names doesn't match the number of unique targets.") report = classification_report(self.y_true, self.y_pred, target_names=target_names) logging.info(report) def build_table_1(model_metrics: OrderedDict, table_folder: str="/mnt/data/tables") -> pd.DataFrame: """Builds and Saves Table 1: Summary of Eval Metrics for all Models, as defined by ModelSchemas class Args: model_metrics (OrderedDict): key is model_name, value is metrics table_folder (str): local filepath outside docker to write csv Returns: pd.DataFrame: Organized as a DataFrame to write to csv """ # Build Table 1 model_metrics_df =
pd.DataFrame.from_dict(model_metrics, orient='index')
pandas.DataFrame.from_dict
# -*- coding: utf-8 -*- """ Small analysis of Estonian kennelshows using Bernese mountain dogs data from kennelliit.ee and CatBoost algorithm """ import matplotlib.pyplot as plt import pandas as pd import numpy as np from catboost import CatBoostRegressor, CatBoostClassifier, Pool, cv from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn import metrics import seaborn as sns # load and join all data to a single frame df_2019 =
pd.read_csv('dogshows_bernese_est_2019.csv')
pandas.read_csv
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 7 21:37:25 2018 @author: jeanfernandes """ import pandas as pd base = pd.read_csv('./bigData/credit-data.csv') base.describe() base.loc[base['idade'] < 0] #apagar a coluna base.drop('idade', 1, inplace = True) #apagar somento os reg com problema base.drop(base[base.idade < 0].index, inplace = True) #preenche os valores manualmente base.mean() base['idade'].mean() base['idade'][base.idade > 0].mean() base.loc[base.idade < 0, 'idade'] = 40.92 pd.isnull(base['idade']) base.loc[
pd.isnull(base['idade'])
pandas.isnull
import streamlit as st import pandas as pd import numpy as np import os from update_data import update_data_instant, update_data_anual import geopy.distance from geopy.geocoders import Nominatim from geopy.extra.rate_limiter import RateLimiter from streamlit_folium import folium_static import folium import branca from time import time import streamlit_analytics.streamlit_analytics as streamlit_analytics import pickle import altair as alt from bokeh.models.widgets import Button from bokeh.models import CustomJS from streamlit_bokeh_events import streamlit_bokeh_events with streamlit_analytics.track(): update_data_instant() update_data_anual() st.title("Comparateur de station") st.write("Où sont les stations essence les moins chères autour de vous ? Voici une carte mise à jour quotidiennement. Choisissez le type de carburant recherché, l'adresse ainsi la distance de recherche dans les filtres.") BASE_CWD = os.getcwd() PATH_DATA = BASE_CWD + "/data" def get_close_station(lat, lon, row, distance): coord1 = (lat,lon) coord2 = (row["latitude"], row["longitude"]) if geopy.distance.geodesic(coord1, coord2).km < distance: return True else: return False @st.experimental_memo def load_data(): df_instant = pd.read_csv(os.path.join(PATH_DATA, "instant.csv"), index_col="id") return df_instant df_instant = load_data() carburant = st.sidebar.radio( "Quel carburant voulez vous?", ('SP95-E10', 'Gazole', 'SP98','GPLc', 'E85')) if carburant == "SP95-E10": suffixe = "E10" else: suffixe = carburant df_instant[f"maj_{suffixe}"] = pd.to_datetime(df_instant[f"maj_{suffixe}"]) with open(os.path.join(PATH_DATA, suffixe), 'rb') as fp: data_year = pickle.load(fp) mode = st.sidebar.select_slider("Comment vous localiser?", options=["Adresse", "Localisation"], value="Localisation") rue = st.sidebar.text_input("Adresse", "Antony") geolocator = Nominatim(user_agent="GTA Lookup") geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1) location = geolocator.geocode(f"{rue}, France") if location is None: location = geolocator.geocode(f"Paris, France") rue = 'Paris' st.sidebar.write("Erreur: Adresse non trouvée") R = st.sidebar.number_input('Distance de recherche (Km)', value=5) loc_button = Button(label="Me localiser", button_type="primary") loc_button.js_on_event( "button_click", CustomJS( code=""" navigator.geolocation.getCurrentPosition( (loc) => { document.dispatchEvent(new CustomEvent("GET_LOCATION", {detail: {lat: loc.coords.latitude, lon: loc.coords.longitude}})) } ) """ ), ) result = streamlit_bokeh_events( loc_button, events="GET_LOCATION", key="get_location", refresh_on_update=False, override_height=75, debounce_time=0,) if result and "GET_LOCATION" in result and mode == "Localisation": loc = result.get("GET_LOCATION") lat = loc.get("lat") lon = loc.get("lon") else: lat = location.latitude lon = location.longitude station_to_plot = df_instant.apply(lambda row: get_close_station(lat, lon, row, R), axis=1) m = folium.Map(location=[lat, lon], zoom_start=13) folium.Marker([lat, lon], tooltip=rue).add_to(m) min_prix = np.inf max_prix = -np.inf for index, row in df_instant[station_to_plot].iterrows(): prix = row[f"prix_{suffixe}"] if prix < min_prix: min_prix = prix if prix > max_prix: max_prix = prix colorscale = branca.colormap.StepColormap(colors=["green", "orange", "red", "darkred"], vmin=min_prix, vmax=max_prix) colorscale.add_to(m) color_dict = {"#008000ff": "green", "#ffa500ff": "orange", "#ff0000ff": "red", "#8b0000ff": "darkred"} for index, row in df_instant[station_to_plot].iterrows(): if not pd.isna(row[f'prix_{suffixe}']): lat_row = row["latitude"] lon_row = row["longitude"] adresse = row["adresse"] ville = row["ville"] T,P = data_year[str(index)] T = pd.DataFrame(T, columns=["Date"]) P = pd.DataFrame(P, columns=[f"Prix"]) chart_data = pd.concat([T,P], axis=1) c = alt.Chart(chart_data).mark_line().encode( x='Date', y=alt.Y("Prix", scale=alt.Scale(zero=False)) ).properties( title="Historique du prix", ) folium.Marker( location=[lat_row, lon_row], tooltip= f"<b>{row[f'prix_{suffixe}']}€</b><br><br>{adresse}<br><br>{ville}", icon=folium.Icon(color=color_dict[colorscale(row[f"prix_{suffixe}"])]), popup=folium.Popup(max_width=450).add_child(folium.VegaLite(c)) ).add_to(m) folium_static(m) colms = st.columns((2, 1, 1, 1, 1)) fields = ["Adresse", 'Ville', f'Prix {carburant}', 'Dernière mise à jour'] for col, field_name in zip(colms, fields): # header col.write(field_name) for x, iterrow in enumerate(df_instant[station_to_plot].sort_values(f"prix_{suffixe}", ascending=True).iterrows()): index, row = iterrow if not pd.isna(row[f'prix_{suffixe}']): col1, col2, col3, col4, col5 = st.columns((2, 1, 1, 1, 1)) col1.write(row["adresse"]) col2.write(row["ville"]) col3.write(row[f"prix_{suffixe}"]) col4.write(row[f"maj_{suffixe}"]) button_type = "Voir l'historique" button_phold = col5.empty() # create a placeholder do_action = button_phold.button(button_type, key=x) if do_action: st.write(f"Historique de prix de la station") T,P = data_year[str(index)] T = pd.DataFrame(T, columns=["Date"]) P =
pd.DataFrame(P, columns=[f"Prix"])
pandas.DataFrame
# Import Libraries # PyTorch from torchvision import models import torch import torch.nn as nn import warnings warnings.filterwarnings('ignore', category=FutureWarning) # Data science tools import pandas as pd # Useful for examining network from torchsummary import summary # Visualization loading from tqdm import tqdm # Import custom functions from src.utils.functions.checking_functions import check_on_gpu # def load_model(model_name, pretrained): if model_name == 'resnet18': model = models.resnet18(pretrained=pretrained) return model elif model_name == 'resnet34': model = models.resnet34(pretrained=pretrained) return model elif model_name == 'resnet50': model = models.resnet50(pretrained=pretrained) return model elif model_name == 'vgg16': model = models.vgg16(pretrained=pretrained) return model elif model_name == 'alexnet': model = models.alexnet(pretrained=pretrained) return model # def freeze_until(model, layer_name): requires_grad = False for name, params in model.named_parameters(): if layer_name in name: requires_grad = True params.requires_grad = requires_grad # def add_custom_classifier(model_name, model, n_output): if model_name == 'resnet18': n_inputs = model.fc.in_features model.fc = nn.Sequential( nn.Linear(n_inputs, n_output)) return model elif model_name == 'resnet34': n_inputs = model.fc.in_features model.fc = nn.Sequential( nn.Linear(n_inputs, n_output)) return model elif model_name == 'resnet50': n_inputs = model.fc.in_features model.fc = nn.Sequential( nn.Linear(n_inputs, n_output)) return model elif model_name == 'vgg16': n_inputs = model.classifier[6].in_features model.classifier[6] = nn.Sequential( nn.Linear(n_inputs, n_output)) return model elif model_name == 'alexnet': n_inputs = model.classifier[6].in_features model.classifier[6] = nn.Sequential( nn.Linear(n_inputs, n_output)) return model # def train(model, criterion, optimizer, scheduler, data_loaders, save_file_name, n_epochs=20, print_every=1): print(f'\nStarting Training.\n') best_acc = 0.0 history = [] story = pd.DataFrame() test_acc_history = [] # Main Loop for epoch in tqdm(range(n_epochs)): # Keep track of training loss epoch train_loss = 0.0 test_loss = 0.0 test_acc = 0 train_acc = 0 # Set to training model.train() # Training Loop for ii, (feature, target) in enumerate(data_loaders['train']): # Check if train on GPU if check_on_gpu(): feature, target = feature.cuda(), target.cuda() # Clear gradients optimizer.zero_grad() # Predicted outputs are log probabilities output = model(feature) # Loss and backpropagation of gradients loss = criterion(output, target) loss.backward() # Update the parameters optimizer.step() # Track train loss by multiplying average loss by number of example in batch train_loss += loss.item() * feature.size(0) # Calculate accuracy by finding max log probability _, pred = torch.max(output, dim=1) correct_tensor = pred.eq(target.data.view_as(pred)) # Need to convert correct tensor from int to float to average accuracy = torch.mean(correct_tensor.type(torch.FloatTensor)) # Multiply average accuracy times the number of examples in batch train_acc += accuracy.item() * feature.size(0) with torch.no_grad(): # Set to evaluation model.eval() for feature, target in data_loaders['test']: output = model(feature) loss = criterion(output, target) test_loss += loss.item() * feature.size(0) _, pred = torch.max(output, dim=1) correct_tensor = pred.eq(target.data.view_as(pred)) accuracy = torch.mean(correct_tensor.type(torch.FloatTensor)) test_acc += accuracy.item() * feature.size(0) train_loss = train_loss / len(data_loaders['train'].dataset) test_loss = test_loss / len(data_loaders['test'].dataset) train_acc = train_acc / len(data_loaders['train'].dataset) test_acc = test_acc / len(data_loaders['test'].dataset) test_acc_history.append(test_acc) history.append([train_loss, test_loss, train_acc, test_acc]) # Check the best accuracy if test_acc > best_acc: best_acc = test_acc # Save the model if test accuracy more 50 % torch.save(model.state_dict(), save_file_name) print('\n Saved') scheduler.step() # Print training and test results if (epoch + 2) % print_every == 0: print( f'\nEpoch:{epoch} \tTraining Loss:{train_loss:.4f}\t Testing Loss:{test_loss:.4f} \t Train Accuracy: {100 * train_acc:.2f}%') print(f'\t\tTest Accuracy:{100 * test_acc:.2f}%') print('Best accuracy: ', best_acc * 100) # Trigger early stopping if len(test_acc_history) > 10: if best_acc not in test_acc_history[-10:]: print( f'\n Early Stopping! Total epochs: {epoch}, with Trainig loss: {train_loss:.2f} and Testing loss: {test_loss:.2f}%') print( f'\n Train accuracy: {100 * train_acc:.2f} and Test accuracy: {100 * test_acc:.2f} and best accuracy of test: {100 * best_acc:.2f}%') # Load the best state dict print("Load model") model.load_state_dict(torch.load(save_file_name)) # Attach the optimizer model.optimizer = optimizer # Add epochs for model model.epochs = epoch # Format history story =
pd.DataFrame(history, columns=['train_loss', 'test_loss', 'train_acc', 'test_acc'])
pandas.DataFrame
#coding=utf-8 import pandas as pd import numpy as np import sys import os from sklearn import preprocessing import datetime import scipy as sc from sklearn.preprocessing import MinMaxScaler,StandardScaler from sklearn.externals import joblib #import joblib class FEbase(object): """description of class""" def __init__(self, **kwargs): pass def create(self,*DataSetName): #print (self.__class__.__name__) (filepath, tempfilename) = os.path.split(DataSetName[0]) (filename, extension) = os.path.splitext(tempfilename) #bufferstring='savetest2017.csv' bufferstringoutput=filepath+'/'+filename+'_'+self.__class__.__name__+extension if(os.path.exists(bufferstringoutput)==False): #df_all=pd.read_csv(bufferstring,index_col=0,header=0,nrows=100000) df_all=self.core(DataSetName) df_all.to_csv(bufferstringoutput) return bufferstringoutput def core(self,df_all,Data_adj_name=''): return df_all def real_FE(): return 0 class FEg30eom0110network(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): intflag=True df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_limit_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='inner', on=['ts_code','trade_date']) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['limit_percent']=df_all['down_limit']/df_all['up_limit'] #是否st或其他 df_all['st_or_otherwrong']=0 df_all.loc[(df_all['limit_percent']<0.85) & (0.58<df_all['limit_percent']),'st_or_otherwrong']=1 df_all.drop(['up_limit','down_limit','limit_percent'],axis=1,inplace=True) ##排除科创版 #print(df_all) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] #===================================================================================================================================# df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) if(intflag): df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) if(intflag): df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) if(intflag): df_all['ps_ttm']=df_all['ps_ttm']*10//1 #===================================================================================================================================# df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min',True) df_all,_=FEsingle.CloseWithHighLow(df_all,8,'min',True) df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max',True) df_all,_=FEsingle.CloseWithHighLow(df_all,8,'max',True) df_all,_=FEsingle.HighLowRange(df_all,8,True) df_all,_=FEsingle.HighLowRange(df_all,25,True) df_all.drop(['change','vol'],axis=1,inplace=True) #===================================================================================================================================# #df_all['mvadj']=1 #df_all.loc[df_all['total_mv_rank']<11,'mvadj']=0.9 #df_all.loc[df_all['total_mv_rank']<7,'mvadj']=0.85 #df_all.loc[df_all['total_mv_rank']<4,'mvadj']=0.6 #df_all.loc[df_all['total_mv_rank']<2,'mvadj']=0.45 #df_all.loc[df_all['total_mv_rank']<1,'mvadj']=0.35 #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 #df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 ###真实价格范围(区分实际股价高低) #df_all['price_real_rank']=df_all.groupby('trade_date')['pre_close'].rank(pct=True) #df_all['price_real_rank']=df_all['price_real_rank']*10//1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) if(intflag): df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) if(intflag): df_all['pct_chg_abs_rank']=df_all['pct_chg_abs_rank']*10//2 df_all=FEsingle.PctChgAbsSumRank(df_all,6,True) df_all=FEsingle.PctChgSumRank(df_all,3,True) df_all=FEsingle.PctChgSumRank(df_all,6,True) df_all=FEsingle.PctChgSumRank(df_all,12,True) df_all=FEsingle.AmountChgRank(df_all,12,True) #df_all=FEsingle.AmountChgRank(df_all,30) #计算三种比例rank dolist=['open','high','low'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) if(intflag): df_all[curc]=df_all[curc]*9.9//2 df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],1) df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],2) df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],3) df_all.drop(['pre_close','adj_factor','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) df_all=FEsingle.PredictDaysTrend(df_all,5) #df_all['tomorrow_chg_rank'] = np.random.randint(0, 10, df_all.shape[0]) #df_all.drop(['mvadj'],axis=1,inplace=True) df_all.drop(['pct_chg'],axis=1,inplace=True) #删除股价过低的票 df_all=df_all[df_all['close']>3] #df_all=df_all[df_all['8_pct_rank_min']>0.1] #df_all=df_all[df_all['25_pct_rank_max']>0.1] #df_all=df_all[df_all['total_mv_rank']>18] #df_all=df_all[df_all['total_mv_rank']>2] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['circ_mv_pct']>3] #df_all=df_all[df_all['ps_ttm']>3] #df_all=df_all[df_all['pb_rank']>3] #暂时不用的列 df_all=df_all[df_all['high_stop']==0] df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop','amount','close','real_price'],axis=1,inplace=True) df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all class FEg30eom0110onlinew6d(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_money_all=pd.read_csv(DataSetName[3],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) print(df_money_all) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_limit_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='inner', on=['ts_code','trade_date']) df_all['sm_amount_pos']=df_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['lg_amount_pos']=df_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['net_mf_amount_pos']=df_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['sm_amount_pos']=df_all.groupby('ts_code')['sm_amount_pos'].shift(1) df_all['lg_amount_pos']=df_all.groupby('ts_code')['lg_amount_pos'].shift(1) df_all['net_mf_amount_pos']=df_all.groupby('ts_code')['net_mf_amount_pos'].shift(1) df_all['sm_amount']=df_all.groupby('ts_code')['sm_amount'].shift(1) df_all['lg_amount']=df_all.groupby('ts_code')['lg_amount'].shift(1) df_all['net_mf_amount']=df_all.groupby('ts_code')['net_mf_amount'].shift(1) df_all=pd.merge(df_all, df_long_all, how='inner', on=['ts_code','trade_date']) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['limit_percent']=df_all['down_limit']/df_all['up_limit'] #是否st或其他 df_all['st_or_otherwrong']=0 df_all.loc[(df_all['limit_percent']<0.85) & (0.58<df_all['limit_percent']),'st_or_otherwrong']=1 df_all.drop(['up_limit','down_limit','limit_percent'],axis=1,inplace=True) ##排除科创版 #print(df_all) #df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 #===================================================================================================================================# df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'max') df_all,_=FEsingle.HighLowRange(df_all,8) df_all,_=FEsingle.HighLowRange(df_all,25) df_all.drop(['change','vol'],axis=1,inplace=True) #===================================================================================================================================# #df_all['mvadj']=1 #df_all.loc[df_all['total_mv_rank']<11,'mvadj']=0.9 #df_all.loc[df_all['total_mv_rank']<7,'mvadj']=0.85 #df_all.loc[df_all['total_mv_rank']<4,'mvadj']=0.6 #df_all.loc[df_all['total_mv_rank']<2,'mvadj']=0.45 #df_all.loc[df_all['total_mv_rank']<1,'mvadj']=0.35 #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 #df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 ###真实价格范围(区分实际股价高低) #df_all['price_real_rank']=df_all.groupby('trade_date')['pre_close'].rank(pct=True) #df_all['price_real_rank']=df_all['price_real_rank']*10//1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) #df_all=FEsingle.PctChgAbsSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.AmountChgRank(df_all,12) #df_all=FEsingle.AmountChgRank(df_all,30) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*9.9//2 df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12','real_price_pos'],1) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],3) df_all.drop(['pre_close','adj_factor','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) df_all=FEsingle.PredictDaysTrend(df_all,5) #df_all['tomorrow_chg_rank'] = np.random.randint(0, 10, df_all.shape[0]) #df_all.drop(['mvadj'],axis=1,inplace=True) df_all.drop(['pct_chg'],axis=1,inplace=True) #删除股价过低的票 df_all=df_all[df_all['close']>3] #df_all=df_all[df_all['8_pct_rank_min']>0.1] #df_all=df_all[df_all['25_pct_rank_max']>0.1] #df_all=df_all[df_all['total_mv_rank']>18] #df_all=df_all[df_all['total_mv_rank']>2] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['circ_mv_pct']>3] #df_all=df_all[df_all['ps_ttm']>3] #df_all=df_all[df_all['pb_rank']>3] #暂时不用的列 df_all=df_all[df_all['high_stop']==0] df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop','amount','close','real_price'],axis=1,inplace=True) df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all class FE_a23(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_money_all=pd.read_csv(DataSetName[3],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'] #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'] #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'] #df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) #df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) #df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_money_all=FEsingle.InputChgSum(df_money_all,5,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'net_mf_amount') print(df_money_all) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_limit_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='inner', on=['ts_code','trade_date']) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['limit_percent']=df_all['down_limit']/df_all['up_limit'] #是否st或其他 df_all['st_or_otherwrong']=0 df_all.loc[(df_all['limit_percent']<0.85) & (0.58<df_all['limit_percent']),'st_or_otherwrong']=1 df_all.drop(['up_limit','down_limit','limit_percent'],axis=1,inplace=True) df_all['dayofweek']=pd.to_datetime(df_all['trade_date'],format='%Y%m%d') df_all['dayofweek']=df_all['dayofweek'].dt.dayofweek ##排除科创版 #print(df_all) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 #===================================================================================================================================# df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'max') df_all,_=FEsingle.HighLowRange(df_all,5) df_all,_=FEsingle.HighLowRange(df_all,12) df_all,_=FEsingle.HighLowRange(df_all,25) df_all.drop(['change','vol'],axis=1,inplace=True) #===================================================================================================================================# #df_all['mvadj']=1 #df_all.loc[df_all['total_mv_rank']<11,'mvadj']=0.9 #df_all.loc[df_all['total_mv_rank']<7,'mvadj']=0.85 #df_all.loc[df_all['total_mv_rank']<4,'mvadj']=0.6 #df_all.loc[df_all['total_mv_rank']<2,'mvadj']=0.45 #df_all.loc[df_all['total_mv_rank']<1,'mvadj']=0.35 #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 #df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 ###真实价格范围(区分实际股价高低) #df_all['price_real_rank']=df_all.groupby('trade_date')['pre_close'].rank(pct=True) #df_all['price_real_rank']=df_all['price_real_rank']*10//1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgAbsSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSumRank(df_all,24) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.PctChgSum(df_all,24) #df_all=FEsingle.AmountChgRank(df_all,12) #df_all=FEsingle.AmountChgRank(df_all,30) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*9.9//2 df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','real_price_pos'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],3) df_all.drop(['pre_close','adj_factor','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) df_all=FEsingle.PredictDaysTrend(df_all,5) #df_all['tomorrow_chg_rank'] = np.random.randint(0, 10, df_all.shape[0]) #df_all.drop(['mvadj'],axis=1,inplace=True) df_all.drop(['pct_chg'],axis=1,inplace=True) #删除股价过低的票 df_all=df_all[df_all['close']>2] #df_all=df_all[df_all['8_pct_rank_min']>0.1] #df_all=df_all[df_all['25_pct_rank_max']>0.1] #df_all=df_all[df_all['total_mv_rank']>18] #df_all=df_all[df_all['total_mv_rank']>2] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['circ_mv_pct']>3] #df_all=df_all[df_all['ps_ttm']>3] #df_all=df_all[df_all['pb_rank']>3] #暂时不用的列 df_all=df_all[df_all['high_stop']==0] df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop','amount','close','real_price'],axis=1,inplace=True) df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all def real_FE(self): #新模型预定版本 df_data=pd.read_csv('real_now.csv',index_col=0,header=0) df_adj_all=pd.read_csv('real_adj_now.csv',index_col=0,header=0) df_money_all=pd.read_csv('real_moneyflow_now.csv',index_col=0,header=0) df_long_all=pd.read_csv('real_long_now.csv',index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'].shift(1) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'].shift(1) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'].shift(1) df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_all=pd.merge(df_data, df_adj_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='left', on=['ts_code','trade_date']) print(df_all) #df_all.drop(['turnover_rate','volume_ratio','pe','pb'],axis=1,inplace=True) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) #这里打一个问号 #df_all=df_all[df_all['ts_code'].str.startswith('688')==False] #df_all=pd.read_csv(bufferstring,index_col=0,header=0,nrows=100000) #df_all.drop(['change','vol'],axis=1,inplace=True) df_all['ts_code'] = df_all['ts_code'].astype('str') #将原本的int数据类型转换为文本 df_all['ts_code'] = df_all['ts_code'].str.zfill(6) #用的时候必须加上.str前缀 print(df_all) ##排除科创版 #print(df_all) df_all[["ts_code"]]=df_all[["ts_code"]].astype(str) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['adj_factor']=df_all['adj_factor'].fillna(0) df_all['real_price']=df_all['close']*df_all['adj_factor'] df_all['real_price']=df_all.groupby('ts_code')['real_price'].shift(1) df_all['real_price']=df_all['real_price']*(1+df_all['pct_chg']/100) #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'max') df_all,_=FEsingle.HighLowRange(df_all,8) df_all,_=FEsingle.HighLowRange(df_all,25) #===================================================================================================================================# #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.AmountChgRank(df_all,12) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*10//2 #df_all=FEsingle.PctChgSumRank_Common(df_all,5,'high') df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12','real_price_pos'],1) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],3) #删除市值过低的票 df_all=df_all[df_all['close']>3] #df_all=df_all[df_all['chg_rank']>0.7] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['total_mv_rank']<12] df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price','amount','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #暂时不用的列 df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) month_sec=df_all['trade_date'].max() df_all=df_all[df_all['trade_date']==month_sec] print(df_all) df_all=df_all.reset_index(drop=True) df_all.to_csv('today_train.csv') dwdw=1 class FE_a29(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_money_all=pd.read_csv(DataSetName[3],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'] #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'] #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'] #df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) #df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) #df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_money_all=FEsingle.InputChgSum(df_money_all,5,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'net_mf_amount') #df_money_all['sm_amount_25_diff']=df_money_all['sm_amount_25']-df_money_all['sm_amount_12'] #df_money_all['sm_amount_12_diff']=df_money_all['sm_amount_12']-df_money_all['sm_amount_5'] #df_money_all['lg_amount_25_diff']=df_money_all['lg_amount_25']-df_money_all['lg_amount_12'] #df_money_all['lg_amount_12_diff']=df_money_all['lg_amount_12']-df_money_all['lg_amount_5'] #df_money_all['net_mf_amount_25_diff']=df_money_all['net_mf_amount_25']-df_money_all['net_mf_amount_12'] #df_money_all['net_mf_amount_12_diff']=df_money_all['net_mf_amount_12']-df_money_all['net_mf_amount_5'] print(df_money_all) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_limit_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='inner', on=['ts_code','trade_date']) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['limit_percent']=df_all['down_limit']/df_all['up_limit'] #是否st或其他 df_all['st_or_otherwrong']=0 df_all.loc[(df_all['limit_percent']<0.85) & (0.58<df_all['limit_percent']),'st_or_otherwrong']=1 df_all.drop(['up_limit','down_limit','limit_percent'],axis=1,inplace=True) df_all['dayofweek']=pd.to_datetime(df_all['trade_date'],format='%Y%m%d') df_all['dayofweek']=df_all['dayofweek'].dt.dayofweek ##排除科创版 #print(df_all) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 #===================================================================================================================================# df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'max') df_all,_=FEsingle.HighLowRange(df_all,5) df_all,_=FEsingle.HighLowRange(df_all,12) df_all,_=FEsingle.HighLowRange(df_all,25) df_all['25_pct_rank_min_diff']=df_all['25_pct_rank_min']-df_all['12_pct_rank_min'] df_all['12_pct_rank_min_diff']=df_all['12_pct_rank_min']-df_all['5_pct_rank_min'] df_all['25_pct_rank_max_diff']=df_all['25_pct_rank_max']-df_all['12_pct_rank_max'] df_all['12_pct_rank_max_diff']=df_all['12_pct_rank_max']-df_all['5_pct_rank_max'] df_all['25_pct_Rangerank_diff']=df_all['25_pct_Rangerank']-df_all['12_pct_Rangerank'] df_all['12_pct_Rangerank_diff']=df_all['12_pct_Rangerank']-df_all['5_pct_Rangerank'] df_all.drop(['change','vol'],axis=1,inplace=True) #===================================================================================================================================# #df_all['mvadj']=1 #df_all.loc[df_all['total_mv_rank']<11,'mvadj']=0.9 #df_all.loc[df_all['total_mv_rank']<7,'mvadj']=0.85 #df_all.loc[df_all['total_mv_rank']<4,'mvadj']=0.6 #df_all.loc[df_all['total_mv_rank']<2,'mvadj']=0.45 #df_all.loc[df_all['total_mv_rank']<1,'mvadj']=0.35 #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 #df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 ###真实价格范围(区分实际股价高低) #df_all['price_real_rank']=df_all.groupby('trade_date')['pre_close'].rank(pct=True) #df_all['price_real_rank']=df_all['price_real_rank']*10//1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgAbsSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSumRank(df_all,24) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.PctChgSum(df_all,24) df_all['chg_rank_24_diff']=df_all['chg_rank_24']-df_all['chg_rank_12'] df_all['chg_rank_12_diff']=df_all['chg_rank_12']-df_all['chg_rank_6'] df_all['chg_rank_6_diff']=df_all['chg_rank_6']-df_all['chg_rank_3'] df_all['pct_chg_24_diff']=df_all['pct_chg_24']-df_all['pct_chg_12'] df_all['pct_chg_12_diff']=df_all['pct_chg_12']-df_all['pct_chg_6'] df_all['pct_chg_6_diff']=df_all['pct_chg_6']-df_all['pct_chg_3'] #df_all=FEsingle.AmountChgRank(df_all,12) #df_all=FEsingle.AmountChgRank(df_all,30) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*9.9//2 df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','real_price_pos'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],3) df_all.drop(['pre_close','adj_factor','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) df_all=FEsingle.PredictDaysTrend(df_all,5) #df_all['tomorrow_chg_rank'] = np.random.randint(0, 10, df_all.shape[0]) #df_all.drop(['mvadj'],axis=1,inplace=True) df_all.drop(['pct_chg'],axis=1,inplace=True) #删除股价过低的票 df_all=df_all[df_all['close']>2] #df_all=df_all[df_all['8_pct_rank_min']>0.1] #df_all=df_all[df_all['25_pct_rank_max']>0.1] #df_all=df_all[df_all['total_mv_rank']>15] #df_all=df_all[df_all['total_mv_rank']>2] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['circ_mv_pct']>3] #df_all=df_all[df_all['ps_ttm']>3] #df_all=df_all[df_all['pb_rank']>3] #暂时不用的列 df_all=df_all[df_all['high_stop']==0] df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop','amount','close','real_price'],axis=1,inplace=True) df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) #df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all def real_FE(self): #新模型预定版本 df_data=pd.read_csv('real_now.csv',index_col=0,header=0) df_adj_all=pd.read_csv('real_adj_now.csv',index_col=0,header=0) df_money_all=pd.read_csv('real_moneyflow_now.csv',index_col=0,header=0) df_long_all=pd.read_csv('real_long_now.csv',index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'].shift(1) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'].shift(1) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'].shift(1) df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_all=pd.merge(df_data, df_adj_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='left', on=['ts_code','trade_date']) print(df_all) #df_all.drop(['turnover_rate','volume_ratio','pe','pb'],axis=1,inplace=True) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) #这里打一个问号 #df_all=df_all[df_all['ts_code'].str.startswith('688')==False] #df_all=pd.read_csv(bufferstring,index_col=0,header=0,nrows=100000) #df_all.drop(['change','vol'],axis=1,inplace=True) df_all['ts_code'] = df_all['ts_code'].astype('str') #将原本的int数据类型转换为文本 df_all['ts_code'] = df_all['ts_code'].str.zfill(6) #用的时候必须加上.str前缀 print(df_all) ##排除科创版 #print(df_all) df_all[["ts_code"]]=df_all[["ts_code"]].astype(str) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['adj_factor']=df_all['adj_factor'].fillna(0) df_all['real_price']=df_all['close']*df_all['adj_factor'] df_all['real_price']=df_all.groupby('ts_code')['real_price'].shift(1) df_all['real_price']=df_all['real_price']*(1+df_all['pct_chg']/100) #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'max') df_all,_=FEsingle.HighLowRange(df_all,8) df_all,_=FEsingle.HighLowRange(df_all,25) #===================================================================================================================================# #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.AmountChgRank(df_all,12) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*10//2 #df_all=FEsingle.PctChgSumRank_Common(df_all,5,'high') df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12','real_price_pos'],1) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],3) #删除市值过低的票 df_all=df_all[df_all['close']>3] #df_all=df_all[df_all['chg_rank']>0.7] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['total_mv_rank']<12] df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price','amount','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #暂时不用的列 df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) month_sec=df_all['trade_date'].max() df_all=df_all[df_all['trade_date']==month_sec] print(df_all) df_all=df_all.reset_index(drop=True) df_all.to_csv('today_train.csv') dwdw=1 class FE_a29_Volatility(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_money_all=pd.read_csv(DataSetName[3],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'] #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'] #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'] #df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) #df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) #df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_money_all=FEsingle.InputChgSum(df_money_all,5,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'net_mf_amount') #df_money_all['sm_amount_25_diff']=df_money_all['sm_amount_25']-df_money_all['sm_amount_12'] #df_money_all['sm_amount_12_diff']=df_money_all['sm_amount_12']-df_money_all['sm_amount_5'] #df_money_all['lg_amount_25_diff']=df_money_all['lg_amount_25']-df_money_all['lg_amount_12'] #df_money_all['lg_amount_12_diff']=df_money_all['lg_amount_12']-df_money_all['lg_amount_5'] #df_money_all['net_mf_amount_25_diff']=df_money_all['net_mf_amount_25']-df_money_all['net_mf_amount_12'] #df_money_all['net_mf_amount_12_diff']=df_money_all['net_mf_amount_12']-df_money_all['net_mf_amount_5'] print(df_money_all) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_limit_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='inner', on=['ts_code','trade_date']) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['limit_percent']=df_all['down_limit']/df_all['up_limit'] #是否st或其他 df_all['st_or_otherwrong']=0 df_all.loc[(df_all['limit_percent']<0.85) & (0.58<df_all['limit_percent']),'st_or_otherwrong']=1 df_all.drop(['up_limit','down_limit','limit_percent'],axis=1,inplace=True) df_all['dayofweek']=pd.to_datetime(df_all['trade_date'],format='%Y%m%d') df_all['dayofweek']=df_all['dayofweek'].dt.dayofweek ##排除科创版 #print(df_all) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 #===================================================================================================================================# df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'max') df_all,_=FEsingle.HighLowRange(df_all,5) df_all,_=FEsingle.HighLowRange(df_all,12) df_all,_=FEsingle.HighLowRange(df_all,25) df_all['25_pct_rank_min_diff']=df_all['25_pct_rank_min']-df_all['12_pct_rank_min'] df_all['12_pct_rank_min_diff']=df_all['12_pct_rank_min']-df_all['5_pct_rank_min'] df_all['25_pct_rank_max_diff']=df_all['25_pct_rank_max']-df_all['12_pct_rank_max'] df_all['12_pct_rank_max_diff']=df_all['12_pct_rank_max']-df_all['5_pct_rank_max'] df_all['25_pct_Rangerank_diff']=df_all['25_pct_Rangerank']-df_all['12_pct_Rangerank'] df_all['12_pct_Rangerank_diff']=df_all['12_pct_Rangerank']-df_all['5_pct_Rangerank'] df_all.drop(['change','vol'],axis=1,inplace=True) #===================================================================================================================================# #df_all['mvadj']=1 #df_all.loc[df_all['total_mv_rank']<11,'mvadj']=0.9 #df_all.loc[df_all['total_mv_rank']<7,'mvadj']=0.85 #df_all.loc[df_all['total_mv_rank']<4,'mvadj']=0.6 #df_all.loc[df_all['total_mv_rank']<2,'mvadj']=0.45 #df_all.loc[df_all['total_mv_rank']<1,'mvadj']=0.35 #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 #df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 ###真实价格范围(区分实际股价高低) #df_all['price_real_rank']=df_all.groupby('trade_date')['pre_close'].rank(pct=True) #df_all['price_real_rank']=df_all['price_real_rank']*10//1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgAbsSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSumRank(df_all,24) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.PctChgSum(df_all,24) df_all['chg_rank_24_diff']=df_all['chg_rank_24']-df_all['chg_rank_12'] df_all['chg_rank_12_diff']=df_all['chg_rank_12']-df_all['chg_rank_6'] df_all['chg_rank_6_diff']=df_all['chg_rank_6']-df_all['chg_rank_3'] df_all['pct_chg_24_diff']=df_all['pct_chg_24']-df_all['pct_chg_12'] df_all['pct_chg_12_diff']=df_all['pct_chg_12']-df_all['pct_chg_6'] df_all['pct_chg_6_diff']=df_all['pct_chg_6']-df_all['pct_chg_3'] #df_all=FEsingle.AmountChgRank(df_all,12) #df_all=FEsingle.AmountChgRank(df_all,30) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*9.9//2 df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','real_price_pos'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],3) df_all.drop(['pre_close','adj_factor','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) df_all=FEsingle.PredictDaysTrend(df_all,5) #df_all['tomorrow_chg_rank'] = np.random.randint(0, 10, df_all.shape[0]) #df_all.drop(['mvadj'],axis=1,inplace=True) df_all.drop(['pct_chg'],axis=1,inplace=True) #删除股价过低的票 df_all=df_all[df_all['close']>2] #df_all=df_all[df_all['8_pct_rank_min']>0.1] #df_all=df_all[df_all['25_pct_rank_max']>0.1] #df_all=df_all[df_all['total_mv_rank']>15] #df_all=df_all[df_all['total_mv_rank']>2] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['circ_mv_pct']>3] #df_all=df_all[df_all['ps_ttm']>3] #df_all=df_all[df_all['pb_rank']>3] #暂时不用的列 df_all=df_all[df_all['high_stop']==0] df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop','amount','close','real_price'],axis=1,inplace=True) df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) #df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all def real_FE(self): #新模型预定版本 df_data=pd.read_csv('real_now.csv',index_col=0,header=0) df_adj_all=pd.read_csv('real_adj_now.csv',index_col=0,header=0) df_money_all=pd.read_csv('real_moneyflow_now.csv',index_col=0,header=0) df_long_all=pd.read_csv('real_long_now.csv',index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'].shift(1) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'].shift(1) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'].shift(1) df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_all=pd.merge(df_data, df_adj_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='left', on=['ts_code','trade_date']) print(df_all) #df_all.drop(['turnover_rate','volume_ratio','pe','pb'],axis=1,inplace=True) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) #这里打一个问号 #df_all=df_all[df_all['ts_code'].str.startswith('688')==False] #df_all=pd.read_csv(bufferstring,index_col=0,header=0,nrows=100000) #df_all.drop(['change','vol'],axis=1,inplace=True) df_all['ts_code'] = df_all['ts_code'].astype('str') #将原本的int数据类型转换为文本 df_all['ts_code'] = df_all['ts_code'].str.zfill(6) #用的时候必须加上.str前缀 print(df_all) ##排除科创版 #print(df_all) df_all[["ts_code"]]=df_all[["ts_code"]].astype(str) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['adj_factor']=df_all['adj_factor'].fillna(0) df_all['real_price']=df_all['close']*df_all['adj_factor'] df_all['real_price']=df_all.groupby('ts_code')['real_price'].shift(1) df_all['real_price']=df_all['real_price']*(1+df_all['pct_chg']/100) #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'max') df_all,_=FEsingle.HighLowRange(df_all,8) df_all,_=FEsingle.HighLowRange(df_all,25) #===================================================================================================================================# #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.AmountChgRank(df_all,12) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*10//2 #df_all=FEsingle.PctChgSumRank_Common(df_all,5,'high') df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12','real_price_pos'],1) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],3) #删除市值过低的票 df_all=df_all[df_all['close']>3] #df_all=df_all[df_all['chg_rank']>0.7] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['total_mv_rank']<12] df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price','amount','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #暂时不用的列 df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) month_sec=df_all['trade_date'].max() df_all=df_all[df_all['trade_date']==month_sec] print(df_all) df_all=df_all.reset_index(drop=True) df_all.to_csv('today_train.csv') dwdw=1 class FE_a31(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_money_all=pd.read_csv(DataSetName[3],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'] #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'] #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'] #df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) #df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) #df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_money_all=FEsingle.InputChgSum(df_money_all,5,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'net_mf_amount') #df_money_all['sm_amount_25_diff']=df_money_all['sm_amount_25']-df_money_all['sm_amount_12'] #df_money_all['sm_amount_12_diff']=df_money_all['sm_amount_12']-df_money_all['sm_amount_5'] #df_money_all['lg_amount_25_diff']=df_money_all['lg_amount_25']-df_money_all['lg_amount_12'] #df_money_all['lg_amount_12_diff']=df_money_all['lg_amount_12']-df_money_all['lg_amount_5'] #df_money_all['net_mf_amount_25_diff']=df_money_all['net_mf_amount_25']-df_money_all['net_mf_amount_12'] #df_money_all['net_mf_amount_12_diff']=df_money_all['net_mf_amount_12']-df_money_all['net_mf_amount_5'] print(df_money_all) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_limit_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='inner', on=['ts_code','trade_date']) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['limit_percent']=df_all['down_limit']/df_all['up_limit'] #是否st或其他 df_all['st_or_otherwrong']=0 df_all.loc[(df_all['limit_percent']<0.85) & (0.58<df_all['limit_percent']),'st_or_otherwrong']=1 df_all.drop(['up_limit','down_limit','limit_percent'],axis=1,inplace=True) df_all['dayofweek']=pd.to_datetime(df_all['trade_date'],format='%Y%m%d') df_all['dayofweek']=df_all['dayofweek'].dt.dayofweek ##排除科创版 #print(df_all) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 #===================================================================================================================================# df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'max') df_all,_=FEsingle.HighLowRange(df_all,5) df_all,_=FEsingle.HighLowRange(df_all,12) df_all,_=FEsingle.HighLowRange(df_all,25) df_all['25_pct_rank_min_diff']=df_all['25_pct_rank_min']-df_all['12_pct_rank_min'] df_all['12_pct_rank_min_diff']=df_all['12_pct_rank_min']-df_all['5_pct_rank_min'] df_all['25_pct_rank_max_diff']=df_all['25_pct_rank_max']-df_all['12_pct_rank_max'] df_all['12_pct_rank_max_diff']=df_all['12_pct_rank_max']-df_all['5_pct_rank_max'] df_all['25_pct_Rangerank_diff']=df_all['25_pct_Rangerank']-df_all['12_pct_Rangerank'] df_all['12_pct_Rangerank_diff']=df_all['12_pct_Rangerank']-df_all['5_pct_Rangerank'] df_all.drop(['change','vol'],axis=1,inplace=True) #===================================================================================================================================# #df_all['mvadj']=1 #df_all.loc[df_all['total_mv_rank']<11,'mvadj']=0.9 #df_all.loc[df_all['total_mv_rank']<7,'mvadj']=0.85 #df_all.loc[df_all['total_mv_rank']<4,'mvadj']=0.6 #df_all.loc[df_all['total_mv_rank']<2,'mvadj']=0.45 #df_all.loc[df_all['total_mv_rank']<1,'mvadj']=0.35 #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 #df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 ###真实价格范围(区分实际股价高低) #df_all['price_real_rank']=df_all.groupby('trade_date')['pre_close'].rank(pct=True) #df_all['price_real_rank']=df_all['price_real_rank']*10//1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgAbsSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSumRank(df_all,24) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.PctChgSum(df_all,24) df_all['chg_rank_24_diff']=df_all['chg_rank_24']-df_all['chg_rank_12'] df_all['chg_rank_12_diff']=df_all['chg_rank_12']-df_all['chg_rank_6'] df_all['chg_rank_6_diff']=df_all['chg_rank_6']-df_all['chg_rank_3'] df_all['pct_chg_24_diff']=df_all['pct_chg_24']-df_all['pct_chg_12'] df_all['pct_chg_12_diff']=df_all['pct_chg_12']-df_all['pct_chg_6'] df_all['pct_chg_6_diff']=df_all['pct_chg_6']-df_all['pct_chg_3'] #df_all=FEsingle.AmountChgRank(df_all,12) #df_all=FEsingle.AmountChgRank(df_all,30) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*9.9//2 df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','real_price_pos'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],3) df_all.drop(['pre_close','adj_factor','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) df_all=FEsingle.PredictDaysTrend(df_all,5) #df_all['tomorrow_chg_rank'] = np.random.randint(0, 10, df_all.shape[0]) #df_all.drop(['mvadj'],axis=1,inplace=True) df_all.drop(['pct_chg'],axis=1,inplace=True) #删除股价过低的票 df_all=df_all[df_all['close']>2] #df_all=df_all[df_all['8_pct_rank_min']>0.1] #df_all=df_all[df_all['25_pct_rank_max']>0.1] df_all=df_all[df_all['total_mv_rank']<6] #df_all=df_all[df_all['total_mv_rank']>2] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['circ_mv_pct']>3] #df_all=df_all[df_all['ps_ttm']>3] #df_all=df_all[df_all['pb_rank']>3] #暂时不用的列 df_all=df_all[df_all['high_stop']==0] df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop','amount','close','real_price'],axis=1,inplace=True) df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) #df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all def real_FE(self): #新模型预定版本 df_data=pd.read_csv('real_now.csv',index_col=0,header=0) df_adj_all=pd.read_csv('real_adj_now.csv',index_col=0,header=0) df_money_all=pd.read_csv('real_moneyflow_now.csv',index_col=0,header=0) df_long_all=pd.read_csv('real_long_now.csv',index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'].shift(1) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'].shift(1) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'].shift(1) df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_all=pd.merge(df_data, df_adj_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='left', on=['ts_code','trade_date']) print(df_all) #df_all.drop(['turnover_rate','volume_ratio','pe','pb'],axis=1,inplace=True) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) #这里打一个问号 #df_all=df_all[df_all['ts_code'].str.startswith('688')==False] #df_all=pd.read_csv(bufferstring,index_col=0,header=0,nrows=100000) #df_all.drop(['change','vol'],axis=1,inplace=True) df_all['ts_code'] = df_all['ts_code'].astype('str') #将原本的int数据类型转换为文本 df_all['ts_code'] = df_all['ts_code'].str.zfill(6) #用的时候必须加上.str前缀 print(df_all) ##排除科创版 #print(df_all) df_all[["ts_code"]]=df_all[["ts_code"]].astype(str) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['adj_factor']=df_all['adj_factor'].fillna(0) df_all['real_price']=df_all['close']*df_all['adj_factor'] df_all['real_price']=df_all.groupby('ts_code')['real_price'].shift(1) df_all['real_price']=df_all['real_price']*(1+df_all['pct_chg']/100) #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'max') df_all,_=FEsingle.HighLowRange(df_all,8) df_all,_=FEsingle.HighLowRange(df_all,25) #===================================================================================================================================# #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.AmountChgRank(df_all,12) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*10//2 #df_all=FEsingle.PctChgSumRank_Common(df_all,5,'high') df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12','real_price_pos'],1) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],3) #删除市值过低的票 df_all=df_all[df_all['close']>3] #df_all=df_all[df_all['chg_rank']>0.7] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['total_mv_rank']<12] df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price','amount','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #暂时不用的列 df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) month_sec=df_all['trade_date'].max() df_all=df_all[df_all['trade_date']==month_sec] print(df_all) df_all=df_all.reset_index(drop=True) df_all.to_csv('today_train.csv') dwdw=1 class FE_a31_full(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_money_all=pd.read_csv(DataSetName[3],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'] #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'] #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'] #df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) #df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) #df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_money_all=FEsingle.InputChgSum(df_money_all,5,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'net_mf_amount') #df_money_all['sm_amount_25_diff']=df_money_all['sm_amount_25']-df_money_all['sm_amount_12'] #df_money_all['sm_amount_12_diff']=df_money_all['sm_amount_12']-df_money_all['sm_amount_5'] #df_money_all['lg_amount_25_diff']=df_money_all['lg_amount_25']-df_money_all['lg_amount_12'] #df_money_all['lg_amount_12_diff']=df_money_all['lg_amount_12']-df_money_all['lg_amount_5'] #df_money_all['net_mf_amount_25_diff']=df_money_all['net_mf_amount_25']-df_money_all['net_mf_amount_12'] #df_money_all['net_mf_amount_12_diff']=df_money_all['net_mf_amount_12']-df_money_all['net_mf_amount_5'] print(df_money_all) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_limit_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='inner', on=['ts_code','trade_date']) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['limit_percent']=df_all['down_limit']/df_all['up_limit'] #是否st或其他 #df_all['st_or_otherwrong']=0 #df_all.loc[(df_all['limit_percent']<0.85) & (0.58<df_all['limit_percent']),'st_or_otherwrong']=1 df_all.drop(['up_limit','down_limit','limit_percent'],axis=1,inplace=True) df_all['dayofweek']=pd.to_datetime(df_all['trade_date'],format='%Y%m%d') df_all['dayofweek']=df_all['dayofweek'].dt.dayofweek ##排除科创版 #print(df_all) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 #===================================================================================================================================# df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'max') df_all,_=FEsingle.HighLowRange(df_all,5) df_all,_=FEsingle.HighLowRange(df_all,12) df_all,_=FEsingle.HighLowRange(df_all,25) df_all['25_pct_rank_min_diff']=df_all['25_pct_rank_min']-df_all['12_pct_rank_min'] df_all['12_pct_rank_min_diff']=df_all['12_pct_rank_min']-df_all['5_pct_rank_min'] df_all['25_pct_rank_max_diff']=df_all['25_pct_rank_max']-df_all['12_pct_rank_max'] df_all['12_pct_rank_max_diff']=df_all['12_pct_rank_max']-df_all['5_pct_rank_max'] df_all['25_pct_Rangerank_diff']=df_all['25_pct_Rangerank']-df_all['12_pct_Rangerank'] df_all['12_pct_Rangerank_diff']=df_all['12_pct_Rangerank']-df_all['5_pct_Rangerank'] df_all.drop(['change','vol'],axis=1,inplace=True) #===================================================================================================================================# #df_all['mvadj']=1 #df_all.loc[df_all['total_mv_rank']<11,'mvadj']=0.9 #df_all.loc[df_all['total_mv_rank']<7,'mvadj']=0.85 #df_all.loc[df_all['total_mv_rank']<4,'mvadj']=0.6 #df_all.loc[df_all['total_mv_rank']<2,'mvadj']=0.45 #df_all.loc[df_all['total_mv_rank']<1,'mvadj']=0.35 #是否停 #df_all['high_stop']=0 #df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 #df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 ###真实价格范围(区分实际股价高低) #df_all['price_real_rank']=df_all.groupby('trade_date')['pre_close'].rank(pct=True) #df_all['price_real_rank']=df_all['price_real_rank']*10//1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgAbsSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSumRank(df_all,24) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.PctChgSum(df_all,24) df_all['chg_rank_24_diff']=df_all['chg_rank_24']-df_all['chg_rank_12'] df_all['chg_rank_12_diff']=df_all['chg_rank_12']-df_all['chg_rank_6'] df_all['chg_rank_6_diff']=df_all['chg_rank_6']-df_all['chg_rank_3'] df_all['pct_chg_24_diff']=df_all['pct_chg_24']-df_all['pct_chg_12'] df_all['pct_chg_12_diff']=df_all['pct_chg_12']-df_all['pct_chg_6'] df_all['pct_chg_6_diff']=df_all['pct_chg_6']-df_all['pct_chg_3'] #df_all=FEsingle.AmountChgRank(df_all,12) #df_all=FEsingle.AmountChgRank(df_all,30) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*9.9//2 df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','real_price_pos'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],3) df_all.drop(['pre_close','adj_factor','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) df_all=FEsingle.PredictDaysTrend(df_all,5) #df_all['tomorrow_chg_rank'] = np.random.randint(0, 10, df_all.shape[0]) #df_all.drop(['mvadj'],axis=1,inplace=True) df_all.drop(['pct_chg'],axis=1,inplace=True) #删除股价过低的票 df_all=df_all[df_all['close']>2] #df_all=df_all[df_all['8_pct_rank_min']>0.1] #df_all=df_all[df_all['25_pct_rank_max']>0.1] df_all=df_all[df_all['total_mv_rank']<6] #df_all=df_all[df_all['total_mv_rank']>2] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['circ_mv_pct']>3] #df_all=df_all[df_all['ps_ttm']>3] #df_all=df_all[df_all['pb_rank']>3] #暂时不用的列 #df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['amount','close','real_price'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all def real_FE(self): #新模型预定版本 df_data=pd.read_csv('real_now.csv',index_col=0,header=0) df_adj_all=pd.read_csv('real_adj_now.csv',index_col=0,header=0) df_money_all=pd.read_csv('real_moneyflow_now.csv',index_col=0,header=0) df_long_all=pd.read_csv('real_long_now.csv',index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'].shift(1) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'].shift(1) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'].shift(1) df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_all=pd.merge(df_data, df_adj_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='left', on=['ts_code','trade_date']) print(df_all) #df_all.drop(['turnover_rate','volume_ratio','pe','pb'],axis=1,inplace=True) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) #这里打一个问号 #df_all=df_all[df_all['ts_code'].str.startswith('688')==False] #df_all=pd.read_csv(bufferstring,index_col=0,header=0,nrows=100000) #df_all.drop(['change','vol'],axis=1,inplace=True) df_all['ts_code'] = df_all['ts_code'].astype('str') #将原本的int数据类型转换为文本 df_all['ts_code'] = df_all['ts_code'].str.zfill(6) #用的时候必须加上.str前缀 print(df_all) ##排除科创版 #print(df_all) df_all[["ts_code"]]=df_all[["ts_code"]].astype(str) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['adj_factor']=df_all['adj_factor'].fillna(0) df_all['real_price']=df_all['close']*df_all['adj_factor'] df_all['real_price']=df_all.groupby('ts_code')['real_price'].shift(1) df_all['real_price']=df_all['real_price']*(1+df_all['pct_chg']/100) #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'max') df_all,_=FEsingle.HighLowRange(df_all,8) df_all,_=FEsingle.HighLowRange(df_all,25) #===================================================================================================================================# #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.AmountChgRank(df_all,12) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*10//2 #df_all=FEsingle.PctChgSumRank_Common(df_all,5,'high') df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12','real_price_pos'],1) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],3) #删除市值过低的票 df_all=df_all[df_all['close']>3] #df_all=df_all[df_all['chg_rank']>0.7] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['total_mv_rank']<12] df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price','amount','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #暂时不用的列 df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) month_sec=df_all['trade_date'].max() df_all=df_all[df_all['trade_date']==month_sec] print(df_all) df_all=df_all.reset_index(drop=True) df_all.to_csv('today_train.csv') dwdw=1 class FE_a29_full(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_money_all=pd.read_csv(DataSetName[3],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'] #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'] #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'] #df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) #df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) #df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_money_all=FEsingle.InputChgSum(df_money_all,5,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'net_mf_amount') #df_money_all['sm_amount_25_diff']=df_money_all['sm_amount_25']-df_money_all['sm_amount_12'] #df_money_all['sm_amount_12_diff']=df_money_all['sm_amount_12']-df_money_all['sm_amount_5'] #df_money_all['lg_amount_25_diff']=df_money_all['lg_amount_25']-df_money_all['lg_amount_12'] #df_money_all['lg_amount_12_diff']=df_money_all['lg_amount_12']-df_money_all['lg_amount_5'] #df_money_all['net_mf_amount_25_diff']=df_money_all['net_mf_amount_25']-df_money_all['net_mf_amount_12'] #df_money_all['net_mf_amount_12_diff']=df_money_all['net_mf_amount_12']-df_money_all['net_mf_amount_5'] print(df_money_all) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_limit_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='inner', on=['ts_code','trade_date']) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['limit_percent']=df_all['down_limit']/df_all['up_limit'] #是否st或其他 #df_all['st_or_otherwrong']=0 #df_all.loc[(df_all['limit_percent']<0.85) & (0.58<df_all['limit_percent']),'st_or_otherwrong']=1 df_all.drop(['up_limit','down_limit','limit_percent'],axis=1,inplace=True) df_all['dayofweek']=pd.to_datetime(df_all['trade_date'],format='%Y%m%d') df_all['dayofweek']=df_all['dayofweek'].dt.dayofweek ##排除科创版 #print(df_all) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 #===================================================================================================================================# df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'max') df_all,_=FEsingle.HighLowRange(df_all,5) df_all,_=FEsingle.HighLowRange(df_all,12) df_all,_=FEsingle.HighLowRange(df_all,25) df_all['25_pct_rank_min_diff']=df_all['25_pct_rank_min']-df_all['12_pct_rank_min'] df_all['12_pct_rank_min_diff']=df_all['12_pct_rank_min']-df_all['5_pct_rank_min'] df_all['25_pct_rank_max_diff']=df_all['25_pct_rank_max']-df_all['12_pct_rank_max'] df_all['12_pct_rank_max_diff']=df_all['12_pct_rank_max']-df_all['5_pct_rank_max'] df_all['25_pct_Rangerank_diff']=df_all['25_pct_Rangerank']-df_all['12_pct_Rangerank'] df_all['12_pct_Rangerank_diff']=df_all['12_pct_Rangerank']-df_all['5_pct_Rangerank'] df_all.drop(['change','vol'],axis=1,inplace=True) #===================================================================================================================================# #df_all['mvadj']=1 #df_all.loc[df_all['total_mv_rank']<11,'mvadj']=0.9 #df_all.loc[df_all['total_mv_rank']<7,'mvadj']=0.85 #df_all.loc[df_all['total_mv_rank']<4,'mvadj']=0.6 #df_all.loc[df_all['total_mv_rank']<2,'mvadj']=0.45 #df_all.loc[df_all['total_mv_rank']<1,'mvadj']=0.35 #是否停 #df_all['high_stop']=0 #df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 #df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 ###真实价格范围(区分实际股价高低) #df_all['price_real_rank']=df_all.groupby('trade_date')['pre_close'].rank(pct=True) #df_all['price_real_rank']=df_all['price_real_rank']*10//1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgAbsSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSumRank(df_all,24) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.PctChgSum(df_all,24) df_all['chg_rank_24_diff']=df_all['chg_rank_24']-df_all['chg_rank_12'] df_all['chg_rank_12_diff']=df_all['chg_rank_12']-df_all['chg_rank_6'] df_all['chg_rank_6_diff']=df_all['chg_rank_6']-df_all['chg_rank_3'] df_all['pct_chg_24_diff']=df_all['pct_chg_24']-df_all['pct_chg_12'] df_all['pct_chg_12_diff']=df_all['pct_chg_12']-df_all['pct_chg_6'] df_all['pct_chg_6_diff']=df_all['pct_chg_6']-df_all['pct_chg_3'] #df_all=FEsingle.AmountChgRank(df_all,12) #df_all=FEsingle.AmountChgRank(df_all,30) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*9.9//2 df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','real_price_pos'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],3) df_all.drop(['pre_close','adj_factor','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) df_all=FEsingle.PredictDaysTrend(df_all,5) #df_all['tomorrow_chg_rank'] = np.random.randint(0, 10, df_all.shape[0]) #df_all.drop(['mvadj'],axis=1,inplace=True) df_all.drop(['pct_chg'],axis=1,inplace=True) #删除股价过低的票 df_all=df_all[df_all['close']>2] #df_all=df_all[df_all['8_pct_rank_min']>0.1] #df_all=df_all[df_all['25_pct_rank_max']>0.1] #df_all=df_all[df_all['total_mv_rank']<6] #df_all=df_all[df_all['total_mv_rank']>2] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['circ_mv_pct']>3] #df_all=df_all[df_all['ps_ttm']>3] #df_all=df_all[df_all['pb_rank']>3] #暂时不用的列 #df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['amount','close','real_price'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all def real_FE(self): #新模型预定版本 df_data=pd.read_csv('real_now.csv',index_col=0,header=0) df_adj_all=pd.read_csv('real_adj_now.csv',index_col=0,header=0) df_money_all=pd.read_csv('real_moneyflow_now.csv',index_col=0,header=0) df_long_all=pd.read_csv('real_long_now.csv',index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'].shift(1) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'].shift(1) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'].shift(1) df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_all=pd.merge(df_data, df_adj_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='left', on=['ts_code','trade_date']) print(df_all) #df_all.drop(['turnover_rate','volume_ratio','pe','pb'],axis=1,inplace=True) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) #这里打一个问号 #df_all=df_all[df_all['ts_code'].str.startswith('688')==False] #df_all=pd.read_csv(bufferstring,index_col=0,header=0,nrows=100000) #df_all.drop(['change','vol'],axis=1,inplace=True) df_all['ts_code'] = df_all['ts_code'].astype('str') #将原本的int数据类型转换为文本 df_all['ts_code'] = df_all['ts_code'].str.zfill(6) #用的时候必须加上.str前缀 print(df_all) ##排除科创版 #print(df_all) df_all[["ts_code"]]=df_all[["ts_code"]].astype(str) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['adj_factor']=df_all['adj_factor'].fillna(0) df_all['real_price']=df_all['close']*df_all['adj_factor'] df_all['real_price']=df_all.groupby('ts_code')['real_price'].shift(1) df_all['real_price']=df_all['real_price']*(1+df_all['pct_chg']/100) #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'max') df_all,_=FEsingle.HighLowRange(df_all,8) df_all,_=FEsingle.HighLowRange(df_all,25) #===================================================================================================================================# #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.AmountChgRank(df_all,12) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*10//2 #df_all=FEsingle.PctChgSumRank_Common(df_all,5,'high') df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12','real_price_pos'],1) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],3) #删除市值过低的票 df_all=df_all[df_all['close']>3] #df_all=df_all[df_all['chg_rank']>0.7] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['total_mv_rank']<12] df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price','amount','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #暂时不用的列 df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) month_sec=df_all['trade_date'].max() df_all=df_all[df_all['trade_date']==month_sec] print(df_all) df_all=df_all.reset_index(drop=True) df_all.to_csv('today_train.csv') dwdw=1 class FE_qliba2(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] df_all=FEsingle.PredictDaysTrend(df_all,5) print(df_all) df_all=df_all.loc[:,['ts_code','trade_date','tomorrow_chg','tomorrow_chg_rank']] print(df_all.dtypes) print(df_all) #===================================================================================================================================# #获取qlib特征 ###df_qlib_1=pd.read_csv('zzztest.csv',header=0) ###df_qlib_2=pd.read_csv('zzztest2.csv',header=0) ##df_qlib_1=pd.read_csv('2013.csv',header=0) ###df_qlib_1=df_qlib_1.iloc[:,0:70] ##df_qlib_all_l=df_qlib_1.iloc[:,0:2] ##df_qlib_all_r=df_qlib_1.iloc[:,70:] ##df_qlib_1 = pd.concat([df_qlib_all_l,df_qlib_all_r],axis=1) ##print(df_qlib_1.head(10)) ##df_qlib_2=pd.read_csv('2015.csv',header=0) ##df_qlib_all_l=df_qlib_2.iloc[:,0:2] ##df_qlib_all_r=df_qlib_2.iloc[:,70:] ##df_qlib_2 = pd.concat([df_qlib_all_l,df_qlib_all_r],axis=1) ##df_qlib_3=pd.read_csv('2017.csv',header=0) ##df_qlib_all_l=df_qlib_3.iloc[:,0:2] ##df_qlib_all_r=df_qlib_3.iloc[:,70:] ##df_qlib_3 = pd.concat([df_qlib_all_l,df_qlib_all_r],axis=1) ##df_qlib_4=pd.read_csv('2019.csv',header=0) ##df_qlib_all_l=df_qlib_4.iloc[:,0:2] ##df_qlib_all_r=df_qlib_4.iloc[:,70:] ##df_qlib_4 = pd.concat([df_qlib_all_l,df_qlib_all_r],axis=1) ##df_qlib_all=pd.concat([df_qlib_2,df_qlib_1]) ##df_qlib_all=pd.concat([df_qlib_3,df_qlib_all]) ##df_qlib_all=pd.concat([df_qlib_4,df_qlib_all]) ##df_qlib_all.drop_duplicates() ##print(df_qlib_all.head(10)) ##df_qlib_all.drop(['LABEL0'],axis=1,inplace=True) ##df_qlib_all.to_csv("13to21_first70plus.csv") df_qlib_all=pd.read_csv('13to21_first70plus.csv',header=0) #df_qlib_all.drop(['LABEL0'],axis=1,inplace=True) print(df_qlib_all) df_qlib_all.rename(columns={'datetime':'trade_date','instrument':'ts_code','score':'mix'}, inplace = True) print(df_qlib_all.dtypes) print(df_qlib_all) df_qlib_all['trade_date'] = pd.to_datetime(df_qlib_all['trade_date'], format='%Y-%m-%d') df_qlib_all['trade_date']=df_qlib_all['trade_date'].apply(lambda x: x.strftime('%Y%m%d')) df_qlib_all['trade_date'] = df_qlib_all['trade_date'].astype(int) df_qlib_all['ts_codeL'] = df_qlib_all['ts_code'].str[:2] df_qlib_all['ts_codeR'] = df_qlib_all['ts_code'].str[2:] df_qlib_all['ts_codeR'] = df_qlib_all['ts_codeR'].apply(lambda s: s+'.') df_qlib_all['ts_code']=df_qlib_all['ts_codeR'].str.cat(df_qlib_all['ts_codeL']) df_qlib_all.drop(['ts_codeL','ts_codeR'],axis=1,inplace=True) print(df_qlib_all.dtypes) print(df_qlib_all) df_qlib_all=df_qlib_all.fillna(value=0) df_all=pd.merge(df_all, df_qlib_all, how='left', on=['ts_code','trade_date']) print(df_all) df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all def real_FE(self): #新模型预定版本 df_data=pd.read_csv('real_now.csv',index_col=0,header=0) df_adj_all=pd.read_csv('real_adj_now.csv',index_col=0,header=0) df_money_all=pd.read_csv('real_moneyflow_now.csv',index_col=0,header=0) df_long_all=pd.read_csv('real_long_now.csv',index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'].shift(1) df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'].shift(1) df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'].shift(1) df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_all=pd.merge(df_data, df_adj_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='left', on=['ts_code','trade_date']) print(df_all) #df_all.drop(['turnover_rate','volume_ratio','pe','pb'],axis=1,inplace=True) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) #这里打一个问号 #df_all=df_all[df_all['ts_code'].str.startswith('688')==False] #df_all=pd.read_csv(bufferstring,index_col=0,header=0,nrows=100000) #df_all.drop(['change','vol'],axis=1,inplace=True) df_all['ts_code'] = df_all['ts_code'].astype('str') #将原本的int数据类型转换为文本 df_all['ts_code'] = df_all['ts_code'].str.zfill(6) #用的时候必须加上.str前缀 print(df_all) ##排除科创版 #print(df_all) df_all[["ts_code"]]=df_all[["ts_code"]].astype(str) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['adj_factor']=df_all['adj_factor'].fillna(0) df_all['real_price']=df_all['close']*df_all['adj_factor'] df_all['real_price']=df_all.groupby('ts_code')['real_price'].shift(1) df_all['real_price']=df_all['real_price']*(1+df_all['pct_chg']/100) #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,8,'max') df_all,_=FEsingle.HighLowRange(df_all,8) df_all,_=FEsingle.HighLowRange(df_all,25) #===================================================================================================================================# #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.AmountChgRank(df_all,12) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*10//2 #df_all=FEsingle.PctChgSumRank_Common(df_all,5,'high') df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12','real_price_pos'],1) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],3) #删除市值过低的票 df_all=df_all[df_all['close']>3] #df_all=df_all[df_all['chg_rank']>0.7] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['total_mv_rank']<12] df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price','amount','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #暂时不用的列 df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) month_sec=df_all['trade_date'].max() df_all=df_all[df_all['trade_date']==month_sec] print(df_all) df_all=df_all.reset_index(drop=True) df_all.to_csv('today_train.csv') dwdw=1 class FEonlinew_a31(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_money_all=pd.read_csv(DataSetName[3],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'] #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'] #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'] df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_money_all=FEsingle.InputChgSum(df_money_all,5,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,12,'net_mf_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,25,'net_mf_amount') print(df_money_all) df_all=pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_limit_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='inner', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_long_all, how='inner', on=['ts_code','trade_date']) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['limit_percent']=df_all['down_limit']/df_all['up_limit'] #是否st或其他 df_all['st_or_otherwrong']=0 df_all.loc[(df_all['limit_percent']<0.85) & (0.58<df_all['limit_percent']),'st_or_otherwrong']=1 df_all.drop(['up_limit','down_limit','limit_percent'],axis=1,inplace=True) ##排除科创版 #print(df_all) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['real_price']=df_all['close']*df_all['adj_factor'] #df_all['real_open']=df_all['adj_factor']*df_all['open'] #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 #===================================================================================================================================# df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'max') df_all,_=FEsingle.HighLowRange(df_all,5) df_all,_=FEsingle.HighLowRange(df_all,12) df_all,_=FEsingle.HighLowRange(df_all,25) df_all.drop(['change','vol'],axis=1,inplace=True) #===================================================================================================================================# #df_all['mvadj']=1 #df_all.loc[df_all['total_mv_rank']<11,'mvadj']=0.9 #df_all.loc[df_all['total_mv_rank']<7,'mvadj']=0.85 #df_all.loc[df_all['total_mv_rank']<4,'mvadj']=0.6 #df_all.loc[df_all['total_mv_rank']<2,'mvadj']=0.45 #df_all.loc[df_all['total_mv_rank']<1,'mvadj']=0.35 #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 #df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 ###真实价格范围(区分实际股价高低) #df_all['price_real_rank']=df_all.groupby('trade_date')['pre_close'].rank(pct=True) #df_all['price_real_rank']=df_all['price_real_rank']*10//1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgAbsSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSumRank(df_all,24) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.PctChgSum(df_all,24) #df_all=FEsingle.AmountChgRank(df_all,12) #df_all=FEsingle.AmountChgRank(df_all,30) #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*9.9//2 df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','real_price_pos'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','pst_amount_rank_12'],3) df_all.drop(['pre_close','adj_factor','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) df_all=FEsingle.PredictDaysTrend(df_all,5) #df_all['tomorrow_chg_rank'] = np.random.randint(0, 10, df_all.shape[0]) #df_all.drop(['mvadj'],axis=1,inplace=True) df_all.drop(['pct_chg'],axis=1,inplace=True) #删除股价过低的票 df_all=df_all[df_all['close']>2] #df_all=df_all[df_all['8_pct_rank_min']>0.1] #df_all=df_all[df_all['25_pct_rank_max']>0.1] #df_all=df_all[df_all['total_mv_rank']>18] #df_all=df_all[df_all['total_mv_rank']>2] df_all=df_all[df_all['amount']>15000] #df_all=df_all[df_all['circ_mv_pct']>3] #df_all=df_all[df_all['ps_ttm']>3] #df_all=df_all[df_all['pb_rank']>3] #暂时不用的列 df_all=df_all[df_all['high_stop']==0] df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop','amount','close','real_price'],axis=1,inplace=True) df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) print(df_all) df_all=df_all.reset_index(drop=True) return df_all def real_FE(self): #新模型预定版本 df_data=pd.read_csv('real_now.csv',index_col=0,header=0) df_adj_all=pd.read_csv('real_adj_now.csv',index_col=0,header=0) df_money_all=pd.read_csv('real_moneyflow_now.csv',index_col=0,header=0) df_long_all=pd.read_csv('real_long_now.csv',index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) df_all=pd.merge(df_data, df_adj_all, how='left', on=['ts_code','trade_date']) df_all=pd.merge(df_all, df_money_all, how='left', on=['ts_code','trade_date']) df_all['sm_amount']=df_all.groupby('ts_code')['sm_amount'].shift(1) df_all['lg_amount']=df_all.groupby('ts_code')['lg_amount'].shift(1) df_all['net_mf_amount']=df_all.groupby('ts_code')['net_mf_amount'].shift(1) df_all=FEsingle.InputChgSum(df_all,5,'sm_amount') df_all=FEsingle.InputChgSum(df_all,5,'lg_amount') df_all=FEsingle.InputChgSum(df_all,5,'net_mf_amount') df_all=FEsingle.InputChgSum(df_all,12,'sm_amount') df_all=FEsingle.InputChgSum(df_all,12,'lg_amount') df_all=FEsingle.InputChgSum(df_all,12,'net_mf_amount') df_all=FEsingle.InputChgSum(df_all,25,'sm_amount') df_all=FEsingle.InputChgSum(df_all,25,'lg_amount') df_all=FEsingle.InputChgSum(df_all,25,'net_mf_amount') df_all=pd.merge(df_all, df_long_all, how='left', on=['ts_code','trade_date']) print(df_all) #df_all.drop(['turnover_rate','volume_ratio','pe','pb'],axis=1,inplace=True) df_all.drop(['turnover_rate','volume_ratio','pe','dv_ttm'],axis=1,inplace=True) df_all['dayofweek']=pd.to_datetime(df_all['trade_date'],format='%Y%m%d') df_all['dayofweek']=df_all['dayofweek'].dt.dayofweek #这里打一个问号 #df_all=df_all[df_all['ts_code'].str.startswith('688')==False] #df_all=pd.read_csv(bufferstring,index_col=0,header=0,nrows=100000) #df_all.drop(['change','vol'],axis=1,inplace=True) df_all['ts_code'] = df_all['ts_code'].astype('str') #将原本的int数据类型转换为文本 df_all['ts_code'] = df_all['ts_code'].str.zfill(6) #用的时候必须加上.str前缀 print(df_all) ##排除科创版 #print(df_all) df_all[["ts_code"]]=df_all[["ts_code"]].astype(str) df_all=df_all[df_all['ts_code'].str.startswith('688')==False] df_all['class1']=0 df_all.loc[df_all['ts_code'].str.startswith('30')==True,'class1']=1 df_all.loc[df_all['ts_code'].str.startswith('60')==True,'class1']=2 df_all.loc[df_all['ts_code'].str.startswith('00')==True,'class1']=3 #===================================================================================================================================# #复权后价格 df_all['adj_factor']=df_all['adj_factor'].fillna(0) df_all['real_price']=df_all['close']*df_all['adj_factor'] df_all['real_price']=df_all.groupby('ts_code')['real_price'].shift(1) df_all['real_price']=df_all['real_price']*(1+df_all['pct_chg']/100) #===================================================================================================================================# df_all['real_price_pos']=df_all.groupby('ts_code')['real_price'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) df_all['total_mv_rank']=df_all.groupby('trade_date')['total_mv'].rank(pct=True) df_all['total_mv_rank']=df_all.groupby('ts_code')['total_mv_rank'].shift(1) df_all['total_mv_rank']=df_all['total_mv_rank']*19.9//1 df_all['pb_rank']=df_all.groupby('trade_date')['pb'].rank(pct=True) df_all['pb_rank']=df_all.groupby('ts_code')['pb_rank'].shift(1) #df_all['pb_rank']=df_all['pb_rank']*10//1 df_all['circ_mv_pct']=(df_all['total_mv']-df_all['circ_mv'])/df_all['total_mv'] df_all['circ_mv_pct']=df_all.groupby('trade_date')['circ_mv_pct'].rank(pct=True) df_all['circ_mv_pct']=df_all.groupby('ts_code')['circ_mv_pct'].shift(1) #df_all['circ_mv_pct']=df_all['circ_mv_pct']*10//1 df_all['ps_ttm']=df_all.groupby('trade_date')['ps_ttm'].rank(pct=True) df_all['ps_ttm']=df_all.groupby('ts_code')['ps_ttm'].shift(1) #df_all['ps_ttm']=df_all['ps_ttm']*10//1 df_all,_=FEsingle.CloseWithHighLow(df_all,25,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,25,'max') df_all,_=FEsingle.CloseWithHighLow(df_all,12,'min') df_all,_=FEsingle.CloseWithHighLow(df_all,5,'max') df_all,_=FEsingle.HighLowRange(df_all,5) df_all,_=FEsingle.HighLowRange(df_all,12) df_all,_=FEsingle.HighLowRange(df_all,25) #===================================================================================================================================# df_all['25_pct_rank_min_diff']=df_all['25_pct_rank_min']-df_all['12_pct_rank_min'] df_all['12_pct_rank_min_diff']=df_all['12_pct_rank_min']-df_all['5_pct_rank_min'] df_all['25_pct_rank_max_diff']=df_all['25_pct_rank_max']-df_all['12_pct_rank_max'] df_all['12_pct_rank_max_diff']=df_all['12_pct_rank_max']-df_all['5_pct_rank_max'] df_all['25_pct_Rangerank_diff']=df_all['25_pct_Rangerank']-df_all['12_pct_Rangerank'] df_all['12_pct_Rangerank_diff']=df_all['12_pct_Rangerank']-df_all['5_pct_Rangerank'] #是否停 df_all['high_stop']=0 df_all.loc[df_all['pct_chg']>9.4,'high_stop']=1 df_all.loc[(df_all['pct_chg']<5.2) & (4.8<df_all['pct_chg']),'high_stop']=1 #1日 df_all['chg_rank']=df_all.groupby('trade_date')['pct_chg'].rank(pct=True) #df_all['chg_rank']=df_all['chg_rank']*10//2 df_all['pct_chg_abs']=df_all['pct_chg'].abs() df_all['pct_chg_abs_rank']=df_all.groupby('trade_date')['pct_chg_abs'].rank(pct=True) df_all=FEsingle.PctChgAbsSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,3) df_all=FEsingle.PctChgSumRank(df_all,6) df_all=FEsingle.PctChgSumRank(df_all,12) df_all=FEsingle.PctChgSumRank(df_all,24) df_all=FEsingle.PctChgSum(df_all,3) df_all=FEsingle.PctChgSum(df_all,6) df_all=FEsingle.PctChgSum(df_all,12) df_all=FEsingle.PctChgSum(df_all,24) df_all['chg_rank_24_diff']=df_all['chg_rank_24']-df_all['chg_rank_12'] df_all['chg_rank_12_diff']=df_all['chg_rank_12']-df_all['chg_rank_6'] df_all['chg_rank_6_diff']=df_all['chg_rank_6']-df_all['chg_rank_3'] df_all['pct_chg_24_diff']=df_all['pct_chg_24']-df_all['pct_chg_12'] df_all['pct_chg_12_diff']=df_all['pct_chg_12']-df_all['pct_chg_6'] df_all['pct_chg_6_diff']=df_all['pct_chg_6']-df_all['pct_chg_3'] #计算三种比例rank dolist=['open','high','low'] df_all['pct_chg_r']=df_all['pct_chg'] for curc in dolist: buffer=((df_all[curc]-df_all['pre_close'])*100)/df_all['pre_close'] df_all[curc]=buffer df_all[curc]=df_all.groupby('trade_date')[curc].rank(pct=True) #df_all[curc]=df_all[curc]*10//2 #df_all=FEsingle.PctChgSumRank_Common(df_all,5,'high') df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pct_chg_r','real_price_pos'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],1) df_all=FEsingle.OldFeaturesRank(df_all,['sm_amount','lg_amount','net_mf_amount'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],2) #df_all=FEsingle.OldFeaturesRank(df_all,['open','high','low','pst_amount_rank_12'],3) #删除市值过低的票 df_all=df_all[df_all['close']>2] #df_all=df_all[df_all['chg_rank']>0.7] df_all=df_all[df_all['amount']>15000] df_all=df_all[df_all['total_mv_rank']<6] df_all.drop(['close','pre_close','pct_chg','adj_factor','real_price','amount','total_mv','pb','circ_mv','pct_chg_abs'],axis=1,inplace=True) #暂时不用的列 df_all=df_all[df_all['high_stop']==0] #df_all=df_all[df_all['st_or_otherwrong']==1] #'tomorrow_chg' df_all.drop(['high_stop'],axis=1,inplace=True) #df_all.drop(['st_or_otherwrong'],axis=1,inplace=True) df_all.dropna(axis=0,how='any',inplace=True) month_sec=df_all['trade_date'].max() df_all=df_all[df_all['trade_date']==month_sec] print(df_all) df_all=df_all.reset_index(drop=True) df_all.to_csv('today_train.csv') dwdw=1 class FEfast_a23(FEbase): #这个版本变为3天预测 def __init__(self): pass def core(self,DataSetName): df_data=pd.read_csv(DataSetName[0],index_col=0,header=0) df_adj_all=pd.read_csv(DataSetName[1],index_col=0,header=0) df_limit_all=pd.read_csv(DataSetName[2],index_col=0,header=0) df_money_all=pd.read_csv(DataSetName[3],index_col=0,header=0) df_long_all=pd.read_csv(DataSetName[4],index_col=0,header=0) df_money_all.drop(['buy_sm_vol','sell_sm_vol','buy_md_vol','sell_md_vol','buy_lg_vol','sell_lg_vol','buy_md_vol','sell_md_vol'],axis=1,inplace=True) df_money_all.drop(['buy_elg_vol','buy_elg_amount','sell_elg_vol','sell_elg_amount','net_mf_vol'],axis=1,inplace=True) df_money_all.drop(['buy_md_amount','sell_md_amount'],axis=1,inplace=True) df_money_all['sm_amount']=df_money_all['buy_sm_amount']-df_money_all['sell_sm_amount'] df_money_all['lg_amount']=df_money_all['buy_lg_amount']-df_money_all['sell_lg_amount'] df_money_all.drop(['buy_sm_amount','sell_sm_amount'],axis=1,inplace=True) df_money_all.drop(['buy_lg_amount','sell_lg_amount'],axis=1,inplace=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount'].rolling(20).apply(lambda x: rollingRankSciPyB(x)).reset_index(0,drop=True) #df_money_all['sm_amount_pos']=df_money_all.groupby('ts_code')['sm_amount_pos'].shift(1) #df_money_all['lg_amount_pos']=df_money_all.groupby('ts_code')['lg_amount_pos'] #df_money_all['net_mf_amount_pos']=df_money_all.groupby('ts_code')['net_mf_amount_pos'] df_money_all['sm_amount']=df_money_all.groupby('ts_code')['sm_amount'].shift(1) df_money_all['lg_amount']=df_money_all.groupby('ts_code')['lg_amount'].shift(1) df_money_all['net_mf_amount']=df_money_all.groupby('ts_code')['net_mf_amount'].shift(1) df_money_all=FEsingle.InputChgSum(df_money_all,5,'sm_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'lg_amount') df_money_all=FEsingle.InputChgSum(df_money_all,5,'net_mf_amount') #print(df_money_all) df_all=
pd.merge(df_data, df_adj_all, how='inner', on=['ts_code','trade_date'])
pandas.merge
# -*- coding: utf-8 -*- """ Created on Sun Jan 10 17:50:04 2021 @author: <NAME> """ import pandas as pd import numpy as np df = pd.read_csv(r'CoinDatasets\ripple_price.csv') print(df) #Dataframe indexlenmesi : #1)Sütunsal indexleyebilirim ve sütun indexini verip çağırabilirim #2)dataframe iloc-loc ile indexlenirse satırın tamamı elde edilir #2.1)df.iloc yaparsam tek bir satırı elde edersem series olur,bir grup satırı elde etmek istersem dataframe olur.[Satırlar için iloc kullan,satırın numarasıyla işlem yapar] #df.iloc[5:7] :Data frame alır #df.iloc[5] :series olarak alır #df.iloc[[1,2]]=1 ve 2.satırları alırım #-------------------------- import pandas as pd import numpy as np df = pd.read_csv(r'CoinDatasets\ripple_price.csv') result = df.iloc[10:20] print(result) #2.2)df.loc yaparsam tek bir satırı elde edersem series olur,bir grup satırı elde etmek istersem dataframe olur.[index isimleriyle ele geçiriyorum] #df.loc['A'] = label ismini verdim ve eriştim #3)Dataframe nesnesi ile indexleme: Sütunları ele geçiririm bu yöntemle :Sütun ismini ele geçirip işlem yapar #tek sütun ele geçirilirse series çok sütun ele geçirilirse dataframe olur #-------------------------- import pandas as pd import numpy as np df = pd.read_csv(r'CoinDatasets\ripple_price.csv') result = df[['Date', 'Open', 'Close']] print(result) #bir satırda herhangi bir kriter uygulamak isterm: import pandas as pd import numpy as np df = pd.read_csv(r'CoinDatasets\ripple_price.csv') result = df.iloc[(df['Open'] > 2).values] #open columnda 2 den büyük olanları getirdim print(result) #iloc kullanmadan dataframe indexlemesiyle koşul belirtme import pandas as pd import numpy as np df = pd.read_csv(r'CoinDatasets\ripple_price.csv') result = df[df['Open'] > 2] print(result) #Dataframe den satır ve sütun silme :satırda axis=0 ,sütun silersem axis=1 yazacağım df.drop() fonksiyonu içerisine import pandas as pd import numpy as np df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], columns=['X', 'Y', 'Z']) result = df.drop('X', axis=1) print(result) #birden fazla sütun silmek istersem liste halinde vereceğim :result = df.drop(['X', 'Y'], axis=1) #satır silmek istersem aşağıdaki gibi yapabilirim import pandas as pd import numpy as np df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], columns=['X', 'Y', 'Z']) print(df) print() result = df.drop(2) #2.satırı sildim esas nesnemde bir değişiklik yok result nesnemde değişiklik oldu print(result) #Dataframe insert yapmak istersem import pandas as pd import numpy as np df = pd.DataFrame({'X': [1, 2, 3], 'Y': [4, 5, 6], 'Z': [7, 8, 9]}, index=['A', 'B', 'C']) print(df) print() df['K'] = [10, 20, 30] #K sütununu insert ettim df['K']=100 dersem tüm elemanlar 100 oluyor print(df) #2.yol insert etme yöntemi import pandas as pd import numpy as np df = pd.DataFrame({'X': [1, 2, 3], 'Y': [4, 5, 6], 'Z': [7, 8, 9]}) print(df) print() df.insert(2, 'K', [10, 20, 30]) #df.insert(3, 'K', [10, 20, 30]) = 3 yaparsam K 3.sütuna geliyor print(df) #eğer series veriyorsam indexlerim uyuşmalı import pandas as pd import numpy as np df =
pd.DataFrame({'X': [1, 2, 3], 'Y': [4, 5, 6], 'Z': [7, 8, 9]}, index=['A', 'B', 'C'])
pandas.DataFrame
# -*- coding: utf-8 -*- # pylint: disable-msg=E1101,W0612 from datetime import datetime, timedelta import pytest import re from numpy import nan as NA import numpy as np from numpy.random import randint from pandas.compat import range, u import pandas.compat as compat from pandas import Index, Series, DataFrame, isna, MultiIndex, notna from pandas.util.testing import assert_series_equal import pandas.util.testing as tm import pandas.core.strings as strings class TestStringMethods(object): def test_api(self): # GH 6106, GH 9322 assert Series.str is strings.StringMethods assert isinstance(Series(['']).str, strings.StringMethods) # GH 9184 invalid = Series([1]) with tm.assert_raises_regex(AttributeError, "only use .str accessor"): invalid.str assert not hasattr(invalid, 'str') def test_iter(self): # GH3638 strs = 'google', 'wikimedia', 'wikipedia', 'wikitravel' ds = Series(strs) for s in ds.str: # iter must yield a Series assert isinstance(s, Series) # indices of each yielded Series should be equal to the index of # the original Series tm.assert_index_equal(s.index, ds.index) for el in s: # each element of the series is either a basestring/str or nan assert isinstance(el, compat.string_types) or isna(el) # desired behavior is to iterate until everything would be nan on the # next iter so make sure the last element of the iterator was 'l' in # this case since 'wikitravel' is the longest string assert s.dropna().values.item() == 'l' def test_iter_empty(self): ds = Series([], dtype=object) i, s = 100, 1 for i, s in enumerate(ds.str): pass # nothing to iterate over so nothing defined values should remain # unchanged assert i == 100 assert s == 1 def test_iter_single_element(self): ds = Series(['a']) for i, s in enumerate(ds.str): pass assert not i assert_series_equal(ds, s) def test_iter_object_try_string(self): ds = Series([slice(None, randint(10), randint(10, 20)) for _ in range( 4)]) i, s = 100, 'h' for i, s in enumerate(ds.str): pass assert i == 100 assert s == 'h' def test_cat(self): one = np.array(['a', 'a', 'b', 'b', 'c', NA], dtype=np.object_) two = np.array(['a', NA, 'b', 'd', 'foo', NA], dtype=np.object_) # single array result = strings.str_cat(one) exp = 'aabbc' assert result == exp result = strings.str_cat(one, na_rep='NA') exp = 'aabbcNA' assert result == exp result = strings.str_cat(one, na_rep='-') exp = 'aabbc-' assert result == exp result = strings.str_cat(one, sep='_', na_rep='NA') exp = 'a_a_b_b_c_NA' assert result == exp result = strings.str_cat(two, sep='-') exp = 'a-b-d-foo' assert result == exp # Multiple arrays result = strings.str_cat(one, [two], na_rep='NA') exp = np.array(['aa', 'aNA', 'bb', 'bd', 'cfoo', 'NANA'], dtype=np.object_) tm.assert_numpy_array_equal(result, exp) result = strings.str_cat(one, two) exp = np.array(['aa', NA, 'bb', 'bd', 'cfoo', NA], dtype=np.object_) tm.assert_almost_equal(result, exp) def test_count(self): values = np.array(['foo', 'foofoo', NA, 'foooofooofommmfoo'], dtype=np.object_) result = strings.str_count(values, 'f[o]+') exp = np.array([1, 2, NA, 4]) tm.assert_numpy_array_equal(result, exp) result = Series(values).str.count('f[o]+') exp = Series([1, 2, NA, 4]) assert isinstance(result, Series) tm.assert_series_equal(result, exp) # mixed mixed = ['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.] rs = strings.str_count(mixed, 'a') xp = np.array([1, NA, 0, NA, NA, 0, NA, NA, NA]) tm.assert_numpy_array_equal(rs, xp) rs = Series(mixed).str.count('a') xp = Series([1, NA, 0, NA, NA, 0, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode values = [u('foo'), u('foofoo'), NA, u('foooofooofommmfoo')] result = strings.str_count(values, 'f[o]+') exp = np.array([1, 2, NA, 4]) tm.assert_numpy_array_equal(result, exp) result = Series(values).str.count('f[o]+') exp = Series([1, 2, NA, 4]) assert isinstance(result, Series) tm.assert_series_equal(result, exp) def test_contains(self): values = np.array(['foo', NA, 'fooommm__foo', 'mmm_', 'foommm[_]+bar'], dtype=np.object_) pat = 'mmm[_]+' result = strings.str_contains(values, pat) expected = np.array([False, NA, True, True, False], dtype=np.object_) tm.assert_numpy_array_equal(result, expected) result = strings.str_contains(values, pat, regex=False) expected = np.array([False, NA, False, False, True], dtype=np.object_) tm.assert_numpy_array_equal(result, expected) values = ['foo', 'xyz', 'fooommm__foo', 'mmm_'] result = strings.str_contains(values, pat) expected = np.array([False, False, True, True]) assert result.dtype == np.bool_ tm.assert_numpy_array_equal(result, expected) # case insensitive using regex values = ['Foo', 'xYz', 'fOOomMm__fOo', 'MMM_'] result = strings.str_contains(values, 'FOO|mmm', case=False) expected = np.array([True, False, True, True]) tm.assert_numpy_array_equal(result, expected) # case insensitive without regex result = strings.str_contains(values, 'foo', regex=False, case=False) expected = np.array([True, False, True, False]) tm.assert_numpy_array_equal(result, expected) # mixed mixed = ['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.] rs = strings.str_contains(mixed, 'o') xp = np.array([False, NA, False, NA, NA, True, NA, NA, NA], dtype=np.object_) tm.assert_numpy_array_equal(rs, xp) rs = Series(mixed).str.contains('o') xp = Series([False, NA, False, NA, NA, True, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode values = np.array([u'foo', NA, u'fooommm__foo', u'mmm_'], dtype=np.object_) pat = 'mmm[_]+' result = strings.str_contains(values, pat) expected = np.array([False, np.nan, True, True], dtype=np.object_) tm.assert_numpy_array_equal(result, expected) result = strings.str_contains(values, pat, na=False) expected = np.array([False, False, True, True]) tm.assert_numpy_array_equal(result, expected) values = np.array(['foo', 'xyz', 'fooommm__foo', 'mmm_'], dtype=np.object_) result = strings.str_contains(values, pat) expected = np.array([False, False, True, True]) assert result.dtype == np.bool_ tm.assert_numpy_array_equal(result, expected) # na values = Series(['om', 'foo', np.nan]) res = values.str.contains('foo', na="foo") assert res.loc[2] == "foo" def test_startswith(self): values = Series(['om', NA, 'foo_nom', 'nom', 'bar_foo', NA, 'foo']) result = values.str.startswith('foo') exp = Series([False, NA, True, False, False, NA, True]) tm.assert_series_equal(result, exp) # mixed mixed = np.array(['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.], dtype=np.object_) rs = strings.str_startswith(mixed, 'f') xp = np.array([False, NA, False, NA, NA, True, NA, NA, NA], dtype=np.object_) tm.assert_numpy_array_equal(rs, xp) rs = Series(mixed).str.startswith('f') assert isinstance(rs, Series) xp = Series([False, NA, False, NA, NA, True, NA, NA, NA]) tm.assert_series_equal(rs, xp) # unicode values = Series([u('om'), NA, u('foo_nom'), u('nom'), u('bar_foo'), NA, u('foo')]) result = values.str.startswith('foo') exp = Series([False, NA, True, False, False, NA, True]) tm.assert_series_equal(result, exp) result = values.str.startswith('foo', na=True) tm.assert_series_equal(result, exp.fillna(True).astype(bool)) def test_endswith(self): values = Series(['om', NA, 'foo_nom', 'nom', 'bar_foo', NA, 'foo']) result = values.str.endswith('foo') exp = Series([False, NA, False, False, True, NA, True]) tm.assert_series_equal(result, exp) # mixed mixed = ['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.] rs = strings.str_endswith(mixed, 'f') xp = np.array([False, NA, False, NA, NA, False, NA, NA, NA], dtype=np.object_) tm.assert_numpy_array_equal(rs, xp) rs = Series(mixed).str.endswith('f') xp = Series([False, NA, False, NA, NA, False, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode values = Series([u('om'), NA, u('foo_nom'), u('nom'), u('bar_foo'), NA, u('foo')]) result = values.str.endswith('foo') exp = Series([False, NA, False, False, True, NA, True]) tm.assert_series_equal(result, exp) result = values.str.endswith('foo', na=False) tm.assert_series_equal(result, exp.fillna(False).astype(bool)) def test_title(self): values = Series(["FOO", "BAR", NA, "Blah", "blurg"]) result = values.str.title() exp = Series(["Foo", "Bar", NA, "Blah", "Blurg"]) tm.assert_series_equal(result, exp) # mixed mixed = Series(["FOO", NA, "bar", True, datetime.today(), "blah", None, 1, 2.]) mixed = mixed.str.title() exp = Series(["Foo", NA, "Bar", NA, NA, "Blah", NA, NA, NA]) tm.assert_almost_equal(mixed, exp) # unicode values = Series([u("FOO"), NA, u("bar"), u("Blurg")]) results = values.str.title() exp = Series([u("Foo"), NA, u("Bar"), u("Blurg")]) tm.assert_series_equal(results, exp) def test_lower_upper(self): values = Series(['om', NA, 'nom', 'nom']) result = values.str.upper() exp = Series(['OM', NA, 'NOM', 'NOM']) tm.assert_series_equal(result, exp) result = result.str.lower() tm.assert_series_equal(result, values) # mixed mixed = Series(['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.]) mixed = mixed.str.upper() rs = Series(mixed).str.lower() xp = Series(['a', NA, 'b', NA, NA, 'foo', NA, NA, NA]) assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode values = Series([u('om'), NA, u('nom'), u('nom')]) result = values.str.upper() exp = Series([u('OM'), NA, u('NOM'), u('NOM')]) tm.assert_series_equal(result, exp) result = result.str.lower() tm.assert_series_equal(result, values) def test_capitalize(self): values = Series(["FOO", "BAR", NA, "Blah", "blurg"]) result = values.str.capitalize() exp = Series(["Foo", "Bar", NA, "Blah", "Blurg"]) tm.assert_series_equal(result, exp) # mixed mixed = Series(["FOO", NA, "bar", True, datetime.today(), "blah", None, 1, 2.]) mixed = mixed.str.capitalize() exp = Series(["Foo", NA, "Bar", NA, NA, "Blah", NA, NA, NA]) tm.assert_almost_equal(mixed, exp) # unicode values = Series([u("FOO"), NA, u("bar"), u("Blurg")]) results = values.str.capitalize() exp = Series([u("Foo"), NA, u("Bar"), u("Blurg")]) tm.assert_series_equal(results, exp) def test_swapcase(self): values = Series(["FOO", "BAR", NA, "Blah", "blurg"]) result = values.str.swapcase() exp = Series(["foo", "bar", NA, "bLAH", "BLURG"]) tm.assert_series_equal(result, exp) # mixed mixed = Series(["FOO", NA, "bar", True, datetime.today(), "Blah", None, 1, 2.]) mixed = mixed.str.swapcase() exp = Series(["foo", NA, "BAR", NA, NA, "bLAH", NA, NA, NA]) tm.assert_almost_equal(mixed, exp) # unicode values = Series([u("FOO"), NA, u("bar"), u("Blurg")]) results = values.str.swapcase() exp = Series([u("foo"), NA, u("BAR"), u("bLURG")]) tm.assert_series_equal(results, exp) def test_casemethods(self): values = ['aaa', 'bbb', 'CCC', 'Dddd', 'eEEE'] s = Series(values) assert s.str.lower().tolist() == [v.lower() for v in values] assert s.str.upper().tolist() == [v.upper() for v in values] assert s.str.title().tolist() == [v.title() for v in values] assert s.str.capitalize().tolist() == [v.capitalize() for v in values] assert s.str.swapcase().tolist() == [v.swapcase() for v in values] def test_replace(self): values = Series(['fooBAD__barBAD', NA]) result = values.str.replace('BAD[_]*', '') exp = Series(['foobar', NA]) tm.assert_series_equal(result, exp) result = values.str.replace('BAD[_]*', '', n=1) exp = Series(['foobarBAD', NA]) tm.assert_series_equal(result, exp) # mixed mixed = Series(['aBAD', NA, 'bBAD', True, datetime.today(), 'fooBAD', None, 1, 2.]) rs = Series(mixed).str.replace('BAD[_]*', '') xp = Series(['a', NA, 'b', NA, NA, 'foo', NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode values = Series([u('fooBAD__barBAD'), NA]) result = values.str.replace('BAD[_]*', '') exp = Series([u('foobar'), NA]) tm.assert_series_equal(result, exp) result = values.str.replace('BAD[_]*', '', n=1) exp = Series([u('foobarBAD'), NA]) tm.assert_series_equal(result, exp) # flags + unicode values = Series([b"abcd,\xc3\xa0".decode("utf-8")]) exp = Series([b"abcd, \xc3\xa0".decode("utf-8")]) result = values.str.replace(r"(?<=\w),(?=\w)", ", ", flags=re.UNICODE) tm.assert_series_equal(result, exp) # GH 13438 for klass in (Series, Index): for repl in (None, 3, {'a': 'b'}): for data in (['a', 'b', None], ['a', 'b', 'c', 'ad']): values = klass(data) pytest.raises(TypeError, values.str.replace, 'a', repl) def test_replace_callable(self): # GH 15055 values = Series(['fooBAD__barBAD', NA]) # test with callable repl = lambda m: m.group(0).swapcase() result = values.str.replace('[a-z][A-Z]{2}', repl, n=2) exp = Series(['foObaD__baRbaD', NA]) tm.assert_series_equal(result, exp) # test with wrong number of arguments, raising an error if compat.PY2: p_err = r'takes (no|(exactly|at (least|most)) ?\d+) arguments?' else: p_err = (r'((takes)|(missing)) (?(2)from \d+ to )?\d+ ' r'(?(3)required )positional arguments?') repl = lambda: None with tm.assert_raises_regex(TypeError, p_err): values.str.replace('a', repl) repl = lambda m, x: None with tm.assert_raises_regex(TypeError, p_err): values.str.replace('a', repl) repl = lambda m, x, y=None: None with tm.assert_raises_regex(TypeError, p_err): values.str.replace('a', repl) # test regex named groups values = Series(['Foo Bar Baz', NA]) pat = r"(?P<first>\w+) (?P<middle>\w+) (?P<last>\w+)" repl = lambda m: m.group('middle').swapcase() result = values.str.replace(pat, repl) exp = Series(['bAR', NA]) tm.assert_series_equal(result, exp) def test_replace_compiled_regex(self): # GH 15446 values = Series(['fooBAD__barBAD', NA]) # test with compiled regex pat = re.compile(r'BAD[_]*') result = values.str.replace(pat, '') exp = Series(['foobar', NA]) tm.assert_series_equal(result, exp) # mixed mixed = Series(['aBAD', NA, 'bBAD', True, datetime.today(), 'fooBAD', None, 1, 2.]) rs = Series(mixed).str.replace(pat, '') xp = Series(['a', NA, 'b', NA, NA, 'foo', NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode values = Series([u('fooBAD__barBAD'), NA]) result = values.str.replace(pat, '') exp = Series([u('foobar'), NA]) tm.assert_series_equal(result, exp) result = values.str.replace(pat, '', n=1) exp = Series([u('foobarBAD'), NA]) tm.assert_series_equal(result, exp) # flags + unicode values = Series([b"abcd,\xc3\xa0".decode("utf-8")]) exp = Series([b"abcd, \xc3\xa0".decode("utf-8")]) pat = re.compile(r"(?<=\w),(?=\w)", flags=re.UNICODE) result = values.str.replace(pat, ", ") tm.assert_series_equal(result, exp) # case and flags provided to str.replace will have no effect # and will produce warnings values = Series(['fooBAD__barBAD__bad', NA]) pat = re.compile(r'BAD[_]*') with tm.assert_raises_regex(ValueError, "case and flags cannot be"): result = values.str.replace(pat, '', flags=re.IGNORECASE) with tm.assert_raises_regex(ValueError, "case and flags cannot be"): result = values.str.replace(pat, '', case=False) with tm.assert_raises_regex(ValueError, "case and flags cannot be"): result = values.str.replace(pat, '', case=True) # test with callable values = Series(['fooBAD__barBAD', NA]) repl = lambda m: m.group(0).swapcase() pat = re.compile('[a-z][A-Z]{2}') result = values.str.replace(pat, repl, n=2) exp = Series(['foObaD__baRbaD', NA]) tm.assert_series_equal(result, exp) def test_repeat(self): values = Series(['a', 'b', NA, 'c', NA, 'd']) result = values.str.repeat(3) exp = Series(['aaa', 'bbb', NA, 'ccc', NA, 'ddd']) tm.assert_series_equal(result, exp) result = values.str.repeat([1, 2, 3, 4, 5, 6]) exp = Series(['a', 'bb', NA, 'cccc', NA, 'dddddd']) tm.assert_series_equal(result, exp) # mixed mixed = Series(['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.]) rs = Series(mixed).str.repeat(3) xp = Series(['aaa', NA, 'bbb', NA, NA, 'foofoofoo', NA, NA, NA]) assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode values = Series([u('a'), u('b'), NA, u('c'), NA, u('d')]) result = values.str.repeat(3) exp = Series([u('aaa'), u('bbb'), NA, u('ccc'), NA, u('ddd')]) tm.assert_series_equal(result, exp) result = values.str.repeat([1, 2, 3, 4, 5, 6]) exp = Series([u('a'), u('bb'), NA, u('cccc'), NA, u('dddddd')]) tm.assert_series_equal(result, exp) def test_match(self): # New match behavior introduced in 0.13 values = Series(['fooBAD__barBAD', NA, 'foo']) result = values.str.match('.*(BAD[_]+).*(BAD)') exp = Series([True, NA, False]) tm.assert_series_equal(result, exp) values = Series(['fooBAD__barBAD', NA, 'foo']) result = values.str.match('.*BAD[_]+.*BAD') exp = Series([True, NA, False]) tm.assert_series_equal(result, exp) # test passing as_indexer still works but is ignored values = Series(['fooBAD__barBAD', NA, 'foo']) exp = Series([True, NA, False]) with tm.assert_produces_warning(FutureWarning): result = values.str.match('.*BAD[_]+.*BAD', as_indexer=True) tm.assert_series_equal(result, exp) with tm.assert_produces_warning(FutureWarning): result = values.str.match('.*BAD[_]+.*BAD', as_indexer=False) tm.assert_series_equal(result, exp) with tm.assert_produces_warning(FutureWarning): result = values.str.match('.*(BAD[_]+).*(BAD)', as_indexer=True) tm.assert_series_equal(result, exp) pytest.raises(ValueError, values.str.match, '.*(BAD[_]+).*(BAD)', as_indexer=False) # mixed mixed = Series(['aBAD_BAD', NA, 'BAD_b_BAD', True, datetime.today(), 'foo', None, 1, 2.]) rs = Series(mixed).str.match('.*(BAD[_]+).*(BAD)') xp = Series([True, NA, True, NA, NA, False, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode values = Series([u('fooBAD__barBAD'), NA, u('foo')]) result = values.str.match('.*(BAD[_]+).*(BAD)') exp = Series([True, NA, False]) tm.assert_series_equal(result, exp) # na GH #6609 res = Series(['a', 0, np.nan]).str.match('a', na=False) exp = Series([True, False, False]) assert_series_equal(exp, res) res = Series(['a', 0, np.nan]).str.match('a') exp = Series([True, np.nan, np.nan]) assert_series_equal(exp, res) def test_extract_expand_None(self): values = Series(['fooBAD__barBAD', NA, 'foo']) with tm.assert_produces_warning(FutureWarning): values.str.extract('.*(BAD[_]+).*(BAD)', expand=None) def test_extract_expand_unspecified(self): values = Series(['fooBAD__barBAD', NA, 'foo']) with tm.assert_produces_warning(FutureWarning): values.str.extract('.*(BAD[_]+).*(BAD)') def test_extract_expand_False(self): # Contains tests like those in test_match and some others. values = Series(['fooBAD__barBAD', NA, 'foo']) er = [NA, NA] # empty row result = values.str.extract('.*(BAD[_]+).*(BAD)', expand=False) exp = DataFrame([['BAD__', 'BAD'], er, er]) tm.assert_frame_equal(result, exp) # mixed mixed = Series(['aBAD_BAD', NA, 'BAD_b_BAD', True, datetime.today(), 'foo', None, 1, 2.]) rs = Series(mixed).str.extract('.*(BAD[_]+).*(BAD)', expand=False) exp = DataFrame([['BAD_', 'BAD'], er, ['BAD_', 'BAD'], er, er, er, er, er, er]) tm.assert_frame_equal(rs, exp) # unicode values = Series([u('fooBAD__barBAD'), NA, u('foo')]) result = values.str.extract('.*(BAD[_]+).*(BAD)', expand=False) exp = DataFrame([[u('BAD__'), u('BAD')], er, er]) tm.assert_frame_equal(result, exp) # GH9980 # Index only works with one regex group since # multi-group would expand to a frame idx = Index(['A1', 'A2', 'A3', 'A4', 'B5']) with tm.assert_raises_regex(ValueError, "supported"): idx.str.extract('([AB])([123])', expand=False) # these should work for both Series and Index for klass in [Series, Index]: # no groups s_or_idx = klass(['A1', 'B2', 'C3']) f = lambda: s_or_idx.str.extract('[ABC][123]', expand=False) pytest.raises(ValueError, f) # only non-capturing groups f = lambda: s_or_idx.str.extract('(?:[AB]).*', expand=False) pytest.raises(ValueError, f) # single group renames series/index properly s_or_idx = klass(['A1', 'A2']) result = s_or_idx.str.extract(r'(?P<uno>A)\d', expand=False) assert result.name == 'uno' exp = klass(['A', 'A'], name='uno') if klass == Series: tm.assert_series_equal(result, exp) else: tm.assert_index_equal(result, exp) s = Series(['A1', 'B2', 'C3']) # one group, no matches result = s.str.extract('(_)', expand=False) exp = Series([NA, NA, NA], dtype=object) tm.assert_series_equal(result, exp) # two groups, no matches result = s.str.extract('(_)(_)', expand=False) exp = DataFrame([[NA, NA], [NA, NA], [NA, NA]], dtype=object) tm.assert_frame_equal(result, exp) # one group, some matches result = s.str.extract('([AB])[123]', expand=False) exp = Series(['A', 'B', NA]) tm.assert_series_equal(result, exp) # two groups, some matches result = s.str.extract('([AB])([123])', expand=False) exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]]) tm.assert_frame_equal(result, exp) # one named group result = s.str.extract('(?P<letter>[AB])', expand=False) exp = Series(['A', 'B', NA], name='letter') tm.assert_series_equal(result, exp) # two named groups result = s.str.extract('(?P<letter>[AB])(?P<number>[123])', expand=False) exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]], columns=['letter', 'number']) tm.assert_frame_equal(result, exp) # mix named and unnamed groups result = s.str.extract('([AB])(?P<number>[123])', expand=False) exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]], columns=[0, 'number']) tm.assert_frame_equal(result, exp) # one normal group, one non-capturing group result = s.str.extract('([AB])(?:[123])', expand=False) exp = Series(['A', 'B', NA]) tm.assert_series_equal(result, exp) # two normal groups, one non-capturing group result = Series(['A11', 'B22', 'C33']).str.extract( '([AB])([123])(?:[123])', expand=False) exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]]) tm.assert_frame_equal(result, exp) # one optional group followed by one normal group result = Series(['A1', 'B2', '3']).str.extract( '(?P<letter>[AB])?(?P<number>[123])', expand=False) exp = DataFrame([['A', '1'], ['B', '2'], [NA, '3']], columns=['letter', 'number']) tm.assert_frame_equal(result, exp) # one normal group followed by one optional group result = Series(['A1', 'B2', 'C']).str.extract( '(?P<letter>[ABC])(?P<number>[123])?', expand=False) exp = DataFrame([['A', '1'], ['B', '2'], ['C', NA]], columns=['letter', 'number']) tm.assert_frame_equal(result, exp) # GH6348 # not passing index to the extractor def check_index(index): data = ['A1', 'B2', 'C'] index = index[:len(data)] s = Series(data, index=index) result = s.str.extract(r'(\d)', expand=False) exp = Series(['1', '2', NA], index=index) tm.assert_series_equal(result, exp) result = Series(data, index=index).str.extract( r'(?P<letter>\D)(?P<number>\d)?', expand=False) e_list = [ ['A', '1'], ['B', '2'], ['C', NA] ] exp = DataFrame(e_list, columns=['letter', 'number'], index=index) tm.assert_frame_equal(result, exp) i_funs = [ tm.makeStringIndex, tm.makeUnicodeIndex, tm.makeIntIndex, tm.makeDateIndex, tm.makePeriodIndex, tm.makeRangeIndex ] for index in i_funs: check_index(index()) # single_series_name_is_preserved. s = Series(['a3', 'b3', 'c2'], name='bob') r = s.str.extract(r'(?P<sue>[a-z])', expand=False) e = Series(['a', 'b', 'c'], name='sue') tm.assert_series_equal(r, e) assert r.name == e.name def test_extract_expand_True(self): # Contains tests like those in test_match and some others. values = Series(['fooBAD__barBAD', NA, 'foo']) er = [NA, NA] # empty row result = values.str.extract('.*(BAD[_]+).*(BAD)', expand=True) exp = DataFrame([['BAD__', 'BAD'], er, er]) tm.assert_frame_equal(result, exp) # mixed mixed = Series(['aBAD_BAD', NA, 'BAD_b_BAD', True, datetime.today(), 'foo', None, 1, 2.]) rs = Series(mixed).str.extract('.*(BAD[_]+).*(BAD)', expand=True) exp = DataFrame([['BAD_', 'BAD'], er, ['BAD_', 'BAD'], er, er, er, er, er, er]) tm.assert_frame_equal(rs, exp) # unicode values = Series([u('fooBAD__barBAD'), NA, u('foo')]) result = values.str.extract('.*(BAD[_]+).*(BAD)', expand=True) exp = DataFrame([[u('BAD__'), u('BAD')], er, er]) tm.assert_frame_equal(result, exp) # these should work for both Series and Index for klass in [Series, Index]: # no groups s_or_idx = klass(['A1', 'B2', 'C3']) f = lambda: s_or_idx.str.extract('[ABC][123]', expand=True) pytest.raises(ValueError, f) # only non-capturing groups f = lambda: s_or_idx.str.extract('(?:[AB]).*', expand=True) pytest.raises(ValueError, f) # single group renames series/index properly s_or_idx = klass(['A1', 'A2']) result_df = s_or_idx.str.extract(r'(?P<uno>A)\d', expand=True) assert isinstance(result_df, DataFrame) result_series = result_df['uno'] assert_series_equal(result_series, Series(['A', 'A'], name='uno')) def test_extract_series(self): # extract should give the same result whether or not the # series has a name. for series_name in None, "series_name": s = Series(['A1', 'B2', 'C3'], name=series_name) # one group, no matches result = s.str.extract('(_)', expand=True) exp = DataFrame([NA, NA, NA], dtype=object) tm.assert_frame_equal(result, exp) # two groups, no matches result = s.str.extract('(_)(_)', expand=True) exp = DataFrame([[NA, NA], [NA, NA], [NA, NA]], dtype=object) tm.assert_frame_equal(result, exp) # one group, some matches result = s.str.extract('([AB])[123]', expand=True) exp = DataFrame(['A', 'B', NA]) tm.assert_frame_equal(result, exp) # two groups, some matches result = s.str.extract('([AB])([123])', expand=True) exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]]) tm.assert_frame_equal(result, exp) # one named group result = s.str.extract('(?P<letter>[AB])', expand=True) exp = DataFrame({"letter": ['A', 'B', NA]}) tm.assert_frame_equal(result, exp) # two named groups result = s.str.extract( '(?P<letter>[AB])(?P<number>[123])', expand=True) e_list = [ ['A', '1'], ['B', '2'], [NA, NA] ] exp = DataFrame(e_list, columns=['letter', 'number']) tm.assert_frame_equal(result, exp) # mix named and unnamed groups result = s.str.extract('([AB])(?P<number>[123])', expand=True) exp = DataFrame(e_list, columns=[0, 'number']) tm.assert_frame_equal(result, exp) # one normal group, one non-capturing group result = s.str.extract('([AB])(?:[123])', expand=True) exp = DataFrame(['A', 'B', NA]) tm.assert_frame_equal(result, exp) def test_extract_optional_groups(self): # two normal groups, one non-capturing group result = Series(['A11', 'B22', 'C33']).str.extract( '([AB])([123])(?:[123])', expand=True) exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]]) tm.assert_frame_equal(result, exp) # one optional group followed by one normal group result = Series(['A1', 'B2', '3']).str.extract( '(?P<letter>[AB])?(?P<number>[123])', expand=True) e_list = [ ['A', '1'], ['B', '2'], [NA, '3'] ] exp = DataFrame(e_list, columns=['letter', 'number']) tm.assert_frame_equal(result, exp) # one normal group followed by one optional group result = Series(['A1', 'B2', 'C']).str.extract( '(?P<letter>[ABC])(?P<number>[123])?', expand=True) e_list = [ ['A', '1'], ['B', '2'], ['C', NA] ] exp = DataFrame(e_list, columns=['letter', 'number']) tm.assert_frame_equal(result, exp) # GH6348 # not passing index to the extractor def check_index(index): data = ['A1', 'B2', 'C'] index = index[:len(data)] result = Series(data, index=index).str.extract( r'(\d)', expand=True) exp = DataFrame(['1', '2', NA], index=index) tm.assert_frame_equal(result, exp) result = Series(data, index=index).str.extract( r'(?P<letter>\D)(?P<number>\d)?', expand=True) e_list = [ ['A', '1'], ['B', '2'], ['C', NA] ] exp = DataFrame(e_list, columns=['letter', 'number'], index=index) tm.assert_frame_equal(result, exp) i_funs = [ tm.makeStringIndex, tm.makeUnicodeIndex, tm.makeIntIndex, tm.makeDateIndex, tm.makePeriodIndex, tm.makeRangeIndex ] for index in i_funs: check_index(index()) def test_extract_single_group_returns_frame(self): # GH11386 extract should always return DataFrame, even when # there is only one group. Prior to v0.18.0, extract returned # Series when there was only one group in the regex. s = Series(['a3', 'b3', 'c2'], name='series_name') r = s.str.extract(r'(?P<letter>[a-z])', expand=True) e = DataFrame({"letter": ['a', 'b', 'c']}) tm.assert_frame_equal(r, e) def test_extractall(self): subject_list = [ '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL> some text <EMAIL>', '<EMAIL> some text c@d.<EMAIL> and <EMAIL>', np.nan, "", ] expected_tuples = [ ("dave", "google", "com"), ("tdhock5", "gmail", "com"), ("maudelaperriere", "gmail", "com"), ("rob", "gmail", "com"), ("steve", "gmail", "com"), ("a", "b", "com"), ("c", "d", "com"), ("e", "f", "com"), ] named_pattern = r""" (?P<user>[a-z0-9]+) @ (?P<domain>[a-z]+) \. (?P<tld>[a-z]{2,4}) """ expected_columns = ["user", "domain", "tld"] S = Series(subject_list) # extractall should return a DataFrame with one row for each # match, indexed by the subject from which the match came. expected_index = MultiIndex.from_tuples([ (0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 0), (4, 1), (4, 2), ], names=(None, "match")) expected_df = DataFrame( expected_tuples, expected_index, expected_columns) computed_df = S.str.extractall(named_pattern, re.VERBOSE) tm.assert_frame_equal(computed_df, expected_df) # The index of the input Series should be used to construct # the index of the output DataFrame: series_index = MultiIndex.from_tuples([ ("single", "Dave"), ("single", "Toby"), ("single", "Maude"), ("multiple", "robAndSteve"), ("multiple", "abcdef"), ("none", "missing"), ("none", "empty"), ]) Si = Series(subject_list, series_index) expected_index = MultiIndex.from_tuples([ ("single", "Dave", 0), ("single", "Toby", 0), ("single", "Maude", 0), ("multiple", "robAndSteve", 0), ("multiple", "robAndSteve", 1), ("multiple", "abcdef", 0), ("multiple", "abcdef", 1), ("multiple", "abcdef", 2), ], names=(None, None, "match")) expected_df = DataFrame( expected_tuples, expected_index, expected_columns) computed_df = Si.str.extractall(named_pattern, re.VERBOSE) tm.assert_frame_equal(computed_df, expected_df) # MultiIndexed subject with names. Sn = Series(subject_list, series_index) Sn.index.names = ("matches", "description") expected_index.names = ("matches", "description", "match") expected_df = DataFrame( expected_tuples, expected_index, expected_columns) computed_df = Sn.str.extractall(named_pattern, re.VERBOSE) tm.assert_frame_equal(computed_df, expected_df) # optional groups. subject_list = ['', 'A1', '32'] named_pattern = '(?P<letter>[AB])?(?P<number>[123])' computed_df = Series(subject_list).str.extractall(named_pattern) expected_index = MultiIndex.from_tuples([ (1, 0), (2, 0), (2, 1), ], names=(None, "match")) expected_df = DataFrame([ ('A', '1'), (NA, '3'), (NA, '2'), ], expected_index, columns=['letter', 'number']) tm.assert_frame_equal(computed_df, expected_df) # only one of two groups has a name. pattern = '([AB])?(?P<number>[123])' computed_df = Series(subject_list).str.extractall(pattern) expected_df = DataFrame([ ('A', '1'), (NA, '3'), (NA, '2'), ], expected_index, columns=[0, 'number']) tm.assert_frame_equal(computed_df, expected_df) def test_extractall_single_group(self): # extractall(one named group) returns DataFrame with one named # column. s = Series(['a3', 'b3', 'd4c2'], name='series_name') r = s.str.extractall(r'(?P<letter>[a-z])') i = MultiIndex.from_tuples([ (0, 0), (1, 0), (2, 0), (2, 1), ], names=(None, "match")) e = DataFrame({"letter": ['a', 'b', 'd', 'c']}, i) tm.assert_frame_equal(r, e) # extractall(one un-named group) returns DataFrame with one # un-named column. r = s.str.extractall(r'([a-z])') e = DataFrame(['a', 'b', 'd', 'c'], i) tm.assert_frame_equal(r, e) def test_extractall_single_group_with_quantifier(self): # extractall(one un-named group with quantifier) returns # DataFrame with one un-named column (GH13382). s = Series(['ab3', 'abc3', 'd4cd2'], name='series_name') r = s.str.extractall(r'([a-z]+)') i = MultiIndex.from_tuples([ (0, 0), (1, 0), (2, 0), (2, 1), ], names=(None, "match")) e = DataFrame(['ab', 'abc', 'd', 'cd'], i) tm.assert_frame_equal(r, e) def test_extractall_no_matches(self): s = Series(['a3', 'b3', 'd4c2'], name='series_name') # one un-named group. r = s.str.extractall('(z)') e = DataFrame(columns=[0]) tm.assert_frame_equal(r, e) # two un-named groups. r = s.str.extractall('(z)(z)') e = DataFrame(columns=[0, 1]) tm.assert_frame_equal(r, e) # one named group. r = s.str.extractall('(?P<first>z)') e = DataFrame(columns=["first"]) tm.assert_frame_equal(r, e) # two named groups. r = s.str.extractall('(?P<first>z)(?P<second>z)') e = DataFrame(columns=["first", "second"]) tm.assert_frame_equal(r, e) # one named, one un-named. r = s.str.extractall('(z)(?P<second>z)') e = DataFrame(columns=[0, "second"]) tm.assert_frame_equal(r, e) def test_extractall_stringindex(self): s = Series(["a1a2", "b1", "c1"], name='xxx') res = s.str.extractall(r"[ab](?P<digit>\d)") exp_idx = MultiIndex.from_tuples([(0, 0), (0, 1), (1, 0)], names=[None, 'match']) exp = DataFrame({'digit': ["1", "2", "1"]}, index=exp_idx) tm.assert_frame_equal(res, exp) # index should return the same result as the default index without name # thus index.name doesn't affect to the result for idx in [Index(["a1a2", "b1", "c1"]), Index(["a1a2", "b1", "c1"], name='xxx')]: res = idx.str.extractall(r"[ab](?P<digit>\d)") tm.assert_frame_equal(res, exp) s = Series(["a1a2", "b1", "c1"], name='s_name', index=Index(["XX", "yy", "zz"], name='idx_name')) res = s.str.extractall(r"[ab](?P<digit>\d)") exp_idx = MultiIndex.from_tuples([("XX", 0), ("XX", 1), ("yy", 0)], names=["idx_name", 'match']) exp = DataFrame({'digit': ["1", "2", "1"]}, index=exp_idx) tm.assert_frame_equal(res, exp) def test_extractall_errors(self): # Does not make sense to use extractall with a regex that has # no capture groups. (it returns DataFrame with one column for # each capture group) s = Series(['a3', 'b3', 'd4c2'], name='series_name') with tm.assert_raises_regex(ValueError, "no capture groups"): s.str.extractall(r'[a-z]') def test_extract_index_one_two_groups(self): s = Series(['a3', 'b3', 'd4c2'], index=["A3", "B3", "D4"], name='series_name') r = s.index.str.extract(r'([A-Z])', expand=True) e = DataFrame(['A', "B", "D"]) tm.assert_frame_equal(r, e) # Prior to v0.18.0, index.str.extract(regex with one group) # returned Index. With more than one group, extract raised an # error (GH9980). Now extract always returns DataFrame. r = s.index.str.extract( r'(?P<letter>[A-Z])(?P<digit>[0-9])', expand=True) e_list = [ ("A", "3"), ("B", "3"), ("D", "4"), ] e = DataFrame(e_list, columns=["letter", "digit"]) tm.assert_frame_equal(r, e) def test_extractall_same_as_extract(self): s = Series(['a3', 'b3', 'c2'], name='series_name') pattern_two_noname = r'([a-z])([0-9])' extract_two_noname = s.str.extract(pattern_two_noname, expand=True) has_multi_index = s.str.extractall(pattern_two_noname) no_multi_index = has_multi_index.xs(0, level="match") tm.assert_frame_equal(extract_two_noname, no_multi_index) pattern_two_named = r'(?P<letter>[a-z])(?P<digit>[0-9])' extract_two_named = s.str.extract(pattern_two_named, expand=True) has_multi_index = s.str.extractall(pattern_two_named) no_multi_index = has_multi_index.xs(0, level="match") tm.assert_frame_equal(extract_two_named, no_multi_index) pattern_one_named = r'(?P<group_name>[a-z])' extract_one_named = s.str.extract(pattern_one_named, expand=True) has_multi_index = s.str.extractall(pattern_one_named) no_multi_index = has_multi_index.xs(0, level="match") tm.assert_frame_equal(extract_one_named, no_multi_index) pattern_one_noname = r'([a-z])' extract_one_noname = s.str.extract(pattern_one_noname, expand=True) has_multi_index = s.str.extractall(pattern_one_noname) no_multi_index = has_multi_index.xs(0, level="match") tm.assert_frame_equal(extract_one_noname, no_multi_index) def test_extractall_same_as_extract_subject_index(self): # same as above tests, but s has an MultiIndex. i = MultiIndex.from_tuples([ ("A", "first"), ("B", "second"), ("C", "third"), ], names=("capital", "ordinal")) s = Series(['a3', 'b3', 'c2'], i, name='series_name') pattern_two_noname = r'([a-z])([0-9])' extract_two_noname = s.str.extract(pattern_two_noname, expand=True) has_match_index = s.str.extractall(pattern_two_noname) no_match_index = has_match_index.xs(0, level="match") tm.assert_frame_equal(extract_two_noname, no_match_index) pattern_two_named = r'(?P<letter>[a-z])(?P<digit>[0-9])' extract_two_named = s.str.extract(pattern_two_named, expand=True) has_match_index = s.str.extractall(pattern_two_named) no_match_index = has_match_index.xs(0, level="match") tm.assert_frame_equal(extract_two_named, no_match_index) pattern_one_named = r'(?P<group_name>[a-z])' extract_one_named = s.str.extract(pattern_one_named, expand=True) has_match_index = s.str.extractall(pattern_one_named) no_match_index = has_match_index.xs(0, level="match") tm.assert_frame_equal(extract_one_named, no_match_index) pattern_one_noname = r'([a-z])' extract_one_noname = s.str.extract(pattern_one_noname, expand=True) has_match_index = s.str.extractall(pattern_one_noname) no_match_index = has_match_index.xs(0, level="match") tm.assert_frame_equal(extract_one_noname, no_match_index) def test_empty_str_methods(self): empty_str = empty = Series(dtype=object) empty_int = Series(dtype=int) empty_bool = Series(dtype=bool) empty_bytes = Series(dtype=object) # GH7241 # (extract) on empty series tm.assert_series_equal(empty_str, empty.str.cat(empty)) assert '' == empty.str.cat() tm.assert_series_equal(empty_str, empty.str.title()) tm.assert_series_equal(empty_int, empty.str.count('a')) tm.assert_series_equal(empty_bool, empty.str.contains('a')) tm.assert_series_equal(empty_bool, empty.str.startswith('a')) tm.assert_series_equal(empty_bool, empty.str.endswith('a')) tm.assert_series_equal(empty_str, empty.str.lower()) tm.assert_series_equal(empty_str, empty.str.upper()) tm.assert_series_equal(empty_str, empty.str.replace('a', 'b')) tm.assert_series_equal(empty_str, empty.str.repeat(3)) tm.assert_series_equal(empty_bool, empty.str.match('^a')) tm.assert_frame_equal( DataFrame(columns=[0], dtype=str), empty.str.extract('()', expand=True)) tm.assert_frame_equal( DataFrame(columns=[0, 1], dtype=str), empty.str.extract('()()', expand=True)) tm.assert_series_equal( empty_str, empty.str.extract('()', expand=False)) tm.assert_frame_equal( DataFrame(columns=[0, 1], dtype=str), empty.str.extract('()()', expand=False)) tm.assert_frame_equal(DataFrame(dtype=str), empty.str.get_dummies()) tm.assert_series_equal(empty_str, empty_str.str.join('')) tm.assert_series_equal(empty_int, empty.str.len()) tm.assert_series_equal(empty_str, empty_str.str.findall('a')) tm.assert_series_equal(empty_int, empty.str.find('a')) tm.assert_series_equal(empty_int, empty.str.rfind('a')) tm.assert_series_equal(empty_str, empty.str.pad(42)) tm.assert_series_equal(empty_str, empty.str.center(42)) tm.assert_series_equal(empty_str, empty.str.split('a')) tm.assert_series_equal(empty_str, empty.str.rsplit('a')) tm.assert_series_equal(empty_str, empty.str.partition('a', expand=False)) tm.assert_series_equal(empty_str, empty.str.rpartition('a', expand=False)) tm.assert_series_equal(empty_str, empty.str.slice(stop=1)) tm.assert_series_equal(empty_str, empty.str.slice(step=1)) tm.assert_series_equal(empty_str, empty.str.strip()) tm.assert_series_equal(empty_str, empty.str.lstrip()) tm.assert_series_equal(empty_str, empty.str.rstrip()) tm.assert_series_equal(empty_str, empty.str.wrap(42)) tm.assert_series_equal(empty_str, empty.str.get(0)) tm.assert_series_equal(empty_str, empty_bytes.str.decode('ascii')) tm.assert_series_equal(empty_bytes, empty.str.encode('ascii')) tm.assert_series_equal(empty_str, empty.str.isalnum()) tm.assert_series_equal(empty_str, empty.str.isalpha()) tm.assert_series_equal(empty_str, empty.str.isdigit()) tm.assert_series_equal(empty_str, empty.str.isspace()) tm.assert_series_equal(empty_str, empty.str.islower()) tm.assert_series_equal(empty_str, empty.str.isupper()) tm.assert_series_equal(empty_str, empty.str.istitle()) tm.assert_series_equal(empty_str, empty.str.isnumeric()) tm.assert_series_equal(empty_str, empty.str.isdecimal()) tm.assert_series_equal(empty_str, empty.str.capitalize()) tm.assert_series_equal(empty_str, empty.str.swapcase()) tm.assert_series_equal(empty_str, empty.str.normalize('NFC')) if compat.PY3: table = str.maketrans('a', 'b') else: import string table = string.maketrans('a', 'b') tm.assert_series_equal(empty_str, empty.str.translate(table)) def test_empty_str_methods_to_frame(self): empty = Series(dtype=str) empty_df = DataFrame([]) tm.assert_frame_equal(empty_df, empty.str.partition('a')) tm.assert_frame_equal(empty_df, empty.str.rpartition('a')) def test_ismethods(self): values = ['A', 'b', 'Xy', '4', '3A', '', 'TT', '55', '-', ' '] str_s = Series(values) alnum_e = [True, True, True, True, True, False, True, True, False, False] alpha_e = [True, True, True, False, False, False, True, False, False, False] digit_e = [False, False, False, True, False, False, False, True, False, False] # TODO: unused num_e = [False, False, False, True, False, False, # noqa False, True, False, False] space_e = [False, False, False, False, False, False, False, False, False, True] lower_e = [False, True, False, False, False, False, False, False, False, False] upper_e = [True, False, False, False, True, False, True, False, False, False] title_e = [True, False, True, False, True, False, False, False, False, False] tm.assert_series_equal(str_s.str.isalnum(), Series(alnum_e)) tm.assert_series_equal(str_s.str.isalpha(), Series(alpha_e)) tm.assert_series_equal(str_s.str.isdigit(), Series(digit_e)) tm.assert_series_equal(str_s.str.isspace(), Series(space_e)) tm.assert_series_equal(str_s.str.islower(), Series(lower_e)) tm.assert_series_equal(str_s.str.isupper(), Series(upper_e)) tm.assert_series_equal(str_s.str.istitle(), Series(title_e)) assert str_s.str.isalnum().tolist() == [v.isalnum() for v in values] assert str_s.str.isalpha().tolist() == [v.isalpha() for v in values] assert str_s.str.isdigit().tolist() == [v.isdigit() for v in values] assert str_s.str.isspace().tolist() == [v.isspace() for v in values] assert str_s.str.islower().tolist() == [v.islower() for v in values] assert str_s.str.isupper().tolist() == [v.isupper() for v in values] assert str_s.str.istitle().tolist() == [v.istitle() for v in values] def test_isnumeric(self): # 0x00bc: ¼ VULGAR FRACTION ONE QUARTER # 0x2605: ★ not number # 0x1378: ፸ ETHIOPIC NUMBER SEVENTY # 0xFF13: 3 Em 3 values = ['A', '3', u'¼', u'★', u'፸', u'3', 'four'] s = Series(values) numeric_e = [False, True, True, False, True, True, False] decimal_e = [False, True, False, False, False, True, False] tm.assert_series_equal(s.str.isnumeric(), Series(numeric_e)) tm.assert_series_equal(s.str.isdecimal(), Series(decimal_e)) unicodes = [u'A', u'3', u'¼', u'★', u'፸', u'3', u'four'] assert s.str.isnumeric().tolist() == [v.isnumeric() for v in unicodes] assert s.str.isdecimal().tolist() == [v.isdecimal() for v in unicodes] values = ['A', np.nan, u'¼', u'★', np.nan, u'3', 'four'] s = Series(values) numeric_e = [False, np.nan, True, False, np.nan, True, False] decimal_e = [False, np.nan, False, False, np.nan, True, False] tm.assert_series_equal(s.str.isnumeric(), Series(numeric_e)) tm.assert_series_equal(s.str.isdecimal(), Series(decimal_e)) def test_get_dummies(self): s = Series(['a|b', 'a|c', np.nan]) result = s.str.get_dummies('|') expected = DataFrame([[1, 1, 0], [1, 0, 1], [0, 0, 0]], columns=list('abc')) tm.assert_frame_equal(result, expected) s = Series(['a;b', 'a', 7]) result = s.str.get_dummies(';') expected = DataFrame([[0, 1, 1], [0, 1, 0], [1, 0, 0]], columns=list('7ab')) tm.assert_frame_equal(result, expected) # GH9980, GH8028 idx = Index(['a|b', 'a|c', 'b|c']) result = idx.str.get_dummies('|') expected = MultiIndex.from_tuples([(1, 1, 0), (1, 0, 1), (0, 1, 1)], names=('a', 'b', 'c')) tm.assert_index_equal(result, expected) def test_get_dummies_with_name_dummy(self): # GH 12180 # Dummies named 'name' should work as expected s = Series(['a', 'b,name', 'b']) result = s.str.get_dummies(',') expected = DataFrame([[1, 0, 0], [0, 1, 1], [0, 1, 0]], columns=['a', 'b', 'name']) tm.assert_frame_equal(result, expected) idx = Index(['a|b', 'name|c', 'b|name']) result = idx.str.get_dummies('|') expected = MultiIndex.from_tuples([(1, 1, 0, 0), (0, 0, 1, 1), (0, 1, 0, 1)], names=('a', 'b', 'c', 'name')) tm.assert_index_equal(result, expected) def test_join(self): values = Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h']) result = values.str.split('_').str.join('_') tm.assert_series_equal(values, result) # mixed mixed = Series(['a_b', NA, 'asdf_cas_asdf', True, datetime.today(), 'foo', None, 1, 2.]) rs = Series(mixed).str.split('_').str.join('_') xp = Series(['a_b', NA, 'asdf_cas_asdf', NA, NA, 'foo', NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode values = Series([u('a_b_c'), u('c_d_e'), np.nan, u('f_g_h')]) result = values.str.split('_').str.join('_') tm.assert_series_equal(values, result) def test_len(self): values = Series(['foo', 'fooo', 'fooooo', np.nan, 'fooooooo']) result = values.str.len() exp = values.map(lambda x: len(x) if notna(x) else NA) tm.assert_series_equal(result, exp) # mixed mixed = Series(['a_b', NA, 'asdf_cas_asdf', True, datetime.today(), 'foo', None, 1, 2.]) rs = Series(mixed).str.len() xp = Series([3, NA, 13, NA, NA, 3, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode values = Series([u('foo'), u('fooo'), u('fooooo'), np.nan, u( 'fooooooo')]) result = values.str.len() exp = values.map(lambda x: len(x) if notna(x) else NA) tm.assert_series_equal(result, exp) def test_findall(self): values = Series(['fooBAD__barBAD', NA, 'foo', 'BAD']) result = values.str.findall('BAD[_]*') exp = Series([['BAD__', 'BAD'], NA, [], ['BAD']]) tm.assert_almost_equal(result, exp) # mixed mixed = Series(['fooBAD__barBAD', NA, 'foo', True, datetime.today(), 'BAD', None, 1, 2.]) rs = Series(mixed).str.findall('BAD[_]*') xp = Series([['BAD__', 'BAD'], NA, [], NA, NA, ['BAD'], NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode values = Series([u('fooBAD__barBAD'), NA, u('foo'), u('BAD')]) result = values.str.findall('BAD[_]*') exp = Series([[u('BAD__'), u('BAD')], NA, [], [u('BAD')]]) tm.assert_almost_equal(result, exp) def test_find(self): values = Series(['ABCDEFG', 'BCDEFEF', 'DEFGHIJEF', 'EFGHEF', 'XXXX']) result = values.str.find('EF') tm.assert_series_equal(result, Series([4, 3, 1, 0, -1])) expected = np.array([v.find('EF') for v in values.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = values.str.rfind('EF') tm.assert_series_equal(result, Series([4, 5, 7, 4, -1])) expected = np.array([v.rfind('EF') for v in values.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = values.str.find('EF', 3) tm.assert_series_equal(result, Series([4, 3, 7, 4, -1])) expected = np.array([v.find('EF', 3) for v in values.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = values.str.rfind('EF', 3) tm.assert_series_equal(result, Series([4, 5, 7, 4, -1])) expected = np.array([v.rfind('EF', 3) for v in values.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = values.str.find('EF', 3, 6) tm.assert_series_equal(result, Series([4, 3, -1, 4, -1])) expected = np.array([v.find('EF', 3, 6) for v in values.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = values.str.rfind('EF', 3, 6) tm.assert_series_equal(result, Series([4, 3, -1, 4, -1])) expected = np.array([v.rfind('EF', 3, 6) for v in values.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) with tm.assert_raises_regex(TypeError, "expected a string object, not int"): result = values.str.find(0) with tm.assert_raises_regex(TypeError, "expected a string object, not int"): result = values.str.rfind(0) def test_find_nan(self): values = Series(['ABCDEFG', np.nan, 'DEFGHIJEF', np.nan, 'XXXX']) result = values.str.find('EF') tm.assert_series_equal(result, Series([4, np.nan, 1, np.nan, -1])) result = values.str.rfind('EF') tm.assert_series_equal(result, Series([4, np.nan, 7, np.nan, -1])) result = values.str.find('EF', 3) tm.assert_series_equal(result, Series([4, np.nan, 7, np.nan, -1])) result = values.str.rfind('EF', 3) tm.assert_series_equal(result, Series([4, np.nan, 7, np.nan, -1])) result = values.str.find('EF', 3, 6) tm.assert_series_equal(result, Series([4, np.nan, -1, np.nan, -1])) result = values.str.rfind('EF', 3, 6) tm.assert_series_equal(result, Series([4, np.nan, -1, np.nan, -1])) def test_index(self): def _check(result, expected): if isinstance(result, Series): tm.assert_series_equal(result, expected) else: tm.assert_index_equal(result, expected) for klass in [Series, Index]: s = klass(['ABCDEFG', 'BCDEFEF', 'DEFGHIJEF', 'EFGHEF']) result = s.str.index('EF') _check(result, klass([4, 3, 1, 0])) expected = np.array([v.index('EF') for v in s.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = s.str.rindex('EF') _check(result, klass([4, 5, 7, 4])) expected = np.array([v.rindex('EF') for v in s.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = s.str.index('EF', 3) _check(result, klass([4, 3, 7, 4])) expected = np.array([v.index('EF', 3) for v in s.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = s.str.rindex('EF', 3) _check(result, klass([4, 5, 7, 4])) expected = np.array([v.rindex('EF', 3) for v in s.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = s.str.index('E', 4, 8) _check(result, klass([4, 5, 7, 4])) expected = np.array([v.index('E', 4, 8) for v in s.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) result = s.str.rindex('E', 0, 5) _check(result, klass([4, 3, 1, 4])) expected = np.array([v.rindex('E', 0, 5) for v in s.values], dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) with tm.assert_raises_regex(ValueError, "substring not found"): result = s.str.index('DE') with tm.assert_raises_regex(TypeError, "expected a string " "object, not int"): result = s.str.index(0) # test with nan s = Series(['abcb', 'ab', 'bcbe', np.nan]) result = s.str.index('b') tm.assert_series_equal(result, Series([1, 1, 0, np.nan])) result = s.str.rindex('b') tm.assert_series_equal(result, Series([3, 1, 2, np.nan])) def test_pad(self): values = Series(['a', 'b', NA, 'c', NA, 'eeeeee']) result = values.str.pad(5, side='left') exp = Series([' a', ' b', NA, ' c', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) result = values.str.pad(5, side='right') exp = Series(['a ', 'b ', NA, 'c ', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) result = values.str.pad(5, side='both') exp = Series([' a ', ' b ', NA, ' c ', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) # mixed mixed = Series(['a', NA, 'b', True, datetime.today(), 'ee', None, 1, 2. ]) rs = Series(mixed).str.pad(5, side='left') xp = Series([' a', NA, ' b', NA, NA, ' ee', NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) mixed = Series(['a', NA, 'b', True, datetime.today(), 'ee', None, 1, 2. ]) rs = Series(mixed).str.pad(5, side='right') xp = Series(['a ', NA, 'b ', NA, NA, 'ee ', NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) mixed = Series(['a', NA, 'b', True, datetime.today(), 'ee', None, 1, 2. ]) rs = Series(mixed).str.pad(5, side='both') xp = Series([' a ', NA, ' b ', NA, NA, ' ee ', NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode values = Series([u('a'), u('b'), NA, u('c'), NA, u('eeeeee')]) result = values.str.pad(5, side='left') exp = Series([u(' a'), u(' b'), NA, u(' c'), NA, u('eeeeee')]) tm.assert_almost_equal(result, exp) result = values.str.pad(5, side='right') exp = Series([u('a '), u('b '), NA, u('c '), NA, u('eeeeee')]) tm.assert_almost_equal(result, exp) result = values.str.pad(5, side='both') exp = Series([u(' a '), u(' b '), NA, u(' c '), NA, u('eeeeee')]) tm.assert_almost_equal(result, exp) def test_pad_fillchar(self): values = Series(['a', 'b', NA, 'c', NA, 'eeeeee']) result = values.str.pad(5, side='left', fillchar='X') exp = Series(['XXXXa', 'XXXXb', NA, 'XXXXc', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) result = values.str.pad(5, side='right', fillchar='X') exp = Series(['aXXXX', 'bXXXX', NA, 'cXXXX', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) result = values.str.pad(5, side='both', fillchar='X') exp = Series(['XXaXX', 'XXbXX', NA, 'XXcXX', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) with tm.assert_raises_regex(TypeError, "fillchar must be a " "character, not str"): result = values.str.pad(5, fillchar='XY') with tm.assert_raises_regex(TypeError, "fillchar must be a " "character, not int"): result = values.str.pad(5, fillchar=5) def test_pad_width(self): # GH 13598 s = Series(['1', '22', 'a', 'bb']) for f in ['center', 'ljust', 'rjust', 'zfill', 'pad']: with tm.assert_raises_regex(TypeError, "width must be of " "integer type, not*"): getattr(s.str, f)('f') def test_translate(self): def _check(result, expected): if isinstance(result, Series): tm.assert_series_equal(result, expected) else: tm.assert_index_equal(result, expected) for klass in [Series, Index]: s = klass(['abcdefg', 'abcc', 'cdddfg', 'cdefggg']) if not compat.PY3: import string table = string.maketrans('abc', 'cde') else: table = str.maketrans('abc', 'cde') result = s.str.translate(table) expected = klass(['cdedefg', 'cdee', 'edddfg', 'edefggg']) _check(result, expected) # use of deletechars is python 2 only if not compat.PY3: result = s.str.translate(table, deletechars='fg') expected = klass(['cdede', 'cdee', 'eddd', 'ede']) _check(result, expected) result = s.str.translate(None, deletechars='fg') expected = klass(['abcde', 'abcc', 'cddd', 'cde']) _check(result, expected) else: with tm.assert_raises_regex( ValueError, "deletechars is not a valid argument"): result = s.str.translate(table, deletechars='fg') # Series with non-string values s = Series(['a', 'b', 'c', 1.2]) expected = Series(['c', 'd', 'e', np.nan]) result = s.str.translate(table) tm.assert_series_equal(result, expected) def test_center_ljust_rjust(self): values = Series(['a', 'b', NA, 'c', NA, 'eeeeee']) result = values.str.center(5) exp = Series([' a ', ' b ', NA, ' c ', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) result = values.str.ljust(5) exp = Series(['a ', 'b ', NA, 'c ', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) result = values.str.rjust(5) exp = Series([' a', ' b', NA, ' c', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) # mixed mixed = Series(['a', NA, 'b', True, datetime.today(), 'c', 'eee', None, 1, 2.]) rs = Series(mixed).str.center(5) xp = Series([' a ', NA, ' b ', NA, NA, ' c ', ' eee ', NA, NA, NA ]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.ljust(5) xp = Series(['a ', NA, 'b ', NA, NA, 'c ', 'eee ', NA, NA, NA ]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.rjust(5) xp = Series([' a', NA, ' b', NA, NA, ' c', ' eee', NA, NA, NA ]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode values = Series([u('a'), u('b'), NA, u('c'), NA, u('eeeeee')]) result = values.str.center(5) exp = Series([u(' a '), u(' b '), NA, u(' c '), NA, u('eeeeee')]) tm.assert_almost_equal(result, exp) result = values.str.ljust(5) exp = Series([u('a '), u('b '), NA, u('c '), NA, u('eeeeee')]) tm.assert_almost_equal(result, exp) result = values.str.rjust(5) exp = Series([u(' a'), u(' b'), NA, u(' c'), NA, u('eeeeee')]) tm.assert_almost_equal(result, exp) def test_center_ljust_rjust_fillchar(self): values = Series(['a', 'bb', 'cccc', 'ddddd', 'eeeeee']) result = values.str.center(5, fillchar='X') expected = Series(['XXaXX', 'XXbbX', 'Xcccc', 'ddddd', 'eeeeee']) tm.assert_series_equal(result, expected) expected = np.array([v.center(5, 'X') for v in values.values], dtype=np.object_) tm.assert_numpy_array_equal(result.values, expected) result = values.str.ljust(5, fillchar='X') expected = Series(['aXXXX', 'bbXXX', 'ccccX', 'ddddd', 'eeeeee']) tm.assert_series_equal(result, expected) expected = np.array([v.ljust(5, 'X') for v in values.values], dtype=np.object_) tm.assert_numpy_array_equal(result.values, expected) result = values.str.rjust(5, fillchar='X') expected = Series(['XXXXa', 'XXXbb', 'Xcccc', 'ddddd', 'eeeeee']) tm.assert_series_equal(result, expected) expected = np.array([v.rjust(5, 'X') for v in values.values], dtype=np.object_) tm.assert_numpy_array_equal(result.values, expected) # If fillchar is not a charatter, normal str raises TypeError # 'aaa'.ljust(5, 'XY') # TypeError: must be char, not str with tm.assert_raises_regex(TypeError, "fillchar must be a " "character, not str"): result = values.str.center(5, fillchar='XY') with tm.assert_raises_regex(TypeError, "fillchar must be a " "character, not str"): result = values.str.ljust(5, fillchar='XY') with tm.assert_raises_regex(TypeError, "fillchar must be a " "character, not str"): result = values.str.rjust(5, fillchar='XY') with tm.assert_raises_regex(TypeError, "fillchar must be a " "character, not int"): result = values.str.center(5, fillchar=1) with tm.assert_raises_regex(TypeError, "fillchar must be a " "character, not int"): result = values.str.ljust(5, fillchar=1) with tm.assert_raises_regex(TypeError, "fillchar must be a " "character, not int"): result = values.str.rjust(5, fillchar=1) def test_zfill(self): values = Series(['1', '22', 'aaa', '333', '45678']) result = values.str.zfill(5) expected = Series(['00001', '00022', '00aaa', '00333', '45678']) tm.assert_series_equal(result, expected) expected = np.array([v.zfill(5) for v in values.values], dtype=np.object_) tm.assert_numpy_array_equal(result.values, expected) result = values.str.zfill(3) expected = Series(['001', '022', 'aaa', '333', '45678']) tm.assert_series_equal(result, expected) expected = np.array([v.zfill(3) for v in values.values], dtype=np.object_) tm.assert_numpy_array_equal(result.values, expected) values = Series(['1', np.nan, 'aaa', np.nan, '45678']) result = values.str.zfill(5) expected = Series(['00001', np.nan, '00aaa', np.nan, '45678']) tm.assert_series_equal(result, expected) def test_split(self): values = Series(['a_b_c', 'c_d_e', NA, 'f_g_h']) result = values.str.split('_') exp = Series([['a', 'b', 'c'], ['c', 'd', 'e'], NA, ['f', 'g', 'h']]) tm.assert_series_equal(result, exp) # more than one char values = Series(['a__b__c', 'c__d__e', NA, 'f__g__h']) result = values.str.split('__') tm.assert_series_equal(result, exp) result = values.str.split('__', expand=False) tm.assert_series_equal(result, exp) # mixed mixed = Series(['a_b_c', NA, 'd_e_f', True, datetime.today(), None, 1, 2.]) result = mixed.str.split('_') exp = Series([['a', 'b', 'c'], NA, ['d', 'e', 'f'], NA, NA, NA, NA, NA ]) assert isinstance(result, Series) tm.assert_almost_equal(result, exp) result = mixed.str.split('_', expand=False) assert isinstance(result, Series) tm.assert_almost_equal(result, exp) # unicode values = Series([u('a_b_c'), u('c_d_e'), NA, u('f_g_h')]) result = values.str.split('_') exp = Series([[u('a'), u('b'), u('c')], [u('c'), u('d'), u('e')], NA, [u('f'), u('g'), u('h')]]) tm.assert_series_equal(result, exp) result = values.str.split('_', expand=False) tm.assert_series_equal(result, exp) # regex split values = Series([u('a,b_c'), u('c_d,e'), NA, u('f,g,h')]) result = values.str.split('[,_]') exp = Series([[u('a'), u('b'), u('c')], [u('c'), u('d'), u('e')], NA, [u('f'), u('g'), u('h')]]) tm.assert_series_equal(result, exp) def test_rsplit(self): values = Series(['a_b_c', 'c_d_e', NA, 'f_g_h']) result = values.str.rsplit('_') exp = Series([['a', 'b', 'c'], ['c', 'd', 'e'], NA, ['f', 'g', 'h']]) tm.assert_series_equal(result, exp) # more than one char values = Series(['a__b__c', 'c__d__e', NA, 'f__g__h']) result = values.str.rsplit('__') tm.assert_series_equal(result, exp) result = values.str.rsplit('__', expand=False) tm.assert_series_equal(result, exp) # mixed mixed = Series(['a_b_c', NA, 'd_e_f', True, datetime.today(), None, 1, 2.]) result = mixed.str.rsplit('_') exp = Series([['a', 'b', 'c'], NA, ['d', 'e', 'f'], NA, NA, NA, NA, NA ]) assert isinstance(result, Series) tm.assert_almost_equal(result, exp) result = mixed.str.rsplit('_', expand=False) assert isinstance(result, Series) tm.assert_almost_equal(result, exp) # unicode values = Series([u('a_b_c'), u('c_d_e'), NA, u('f_g_h')]) result = values.str.rsplit('_') exp = Series([[u('a'), u('b'), u('c')], [u('c'), u('d'), u('e')], NA, [u('f'), u('g'), u('h')]]) tm.assert_series_equal(result, exp) result = values.str.rsplit('_', expand=False) tm.assert_series_equal(result, exp) # regex split is not supported by rsplit values = Series([u('a,b_c'), u('c_d,e'), NA, u('f,g,h')]) result = values.str.rsplit('[,_]') exp = Series([[u('a,b_c')], [
u('c_d,e')
pandas.compat.u
""" Implements a series of technical indicators used in finance and trading. """ import pandas as pd def ADX(data, ma, full_output=False): """ Calculate average directional index (ADX) for a given ohlc dataframe. Parameters ---------- data: pd.DataFrame DataFrame containing OHLC data. Columns must have the following labels: High, Low, Close. Open column is not mandatory. ma: int How many obversations will be used to calculate moving average full_output: bool Returns input data and support series used in calculation Returns ---------- pd.DataFrame With columns adx and dx For full output, dm_pos, dm_neg, tr, roll_tr, roll_dmp, roll_dmn, di_pos, di_neg, di_sum, di_diff are shown too """ # Handles input data if not isinstance(data, pd.DataFrame): raise TypeError('Input data is not a pandas DataFrame.') if not set(['High', 'Low', 'Close']).issubset(data.columns): raise IndexError('Missing necessary columns (High, Low or Close).') # Handles parameter input if not isinstance(ma, int): raise TypeError('ma parameter is not integer type.') full_df = pd.DataFrame() # Compute true range full_df['diff_hl'] = abs(data['High'] - data['Low']) full_df['diff_hc'] = abs(data['High'] - data['Close'].shift(1)) full_df['diff_lc'] = abs(data['Low'] - data['Close'].shift(1)) full_df['tr'] = full_df[['diff_hl', 'diff_hc', 'diff_lc']].max(axis=1) # Delete diff columns full_df = full_df.drop(['diff_hl', 'diff_hc', 'diff_lc'], axis=1) # Compute directional momentum full_df['dm_pos'] = data['High'] - data['High'].shift(1) full_df['dm_neg'] = data['Low'].shift(1) - data['Low'] # Only positive values full_df.loc[full_df['dm_pos'] < 0, 'dm_pos'] = 0 full_df.loc[full_df['dm_neg'] < 0, 'dm_neg'] = 0 # Take rolling sum full_df['roll_tr'] = full_df['tr'].rolling(ma).sum() full_df['roll_dmp'] = full_df['dm_pos'].rolling(ma).sum() full_df['roll_dmn'] = full_df['dm_neg'].rolling(ma).sum() # Compute new rolling sum roll_tr = [None for i in range(ma)] roll_dmp = [None for i in range(ma)] roll_dmn = [None for i in range(ma)] roll_tr.append(full_df['roll_tr'].iloc[ma]) roll_dmp.append(full_df['roll_dmp'].iloc[ma]) roll_dmn.append(full_df['roll_dmn'].iloc[ma]) # Don't know if there is a vector method to do that for i in range(ma+1, full_df.shape[0]): temp_tr = (roll_tr[-1] - (roll_tr[-1] / ma) + full_df.iloc[i, -6]) roll_tr.append(temp_tr) temp_dmp = (roll_dmp[-1] - (roll_dmp[-1] / ma) + full_df.iloc[i, -5]) roll_dmp.append(temp_dmp) temp_dmn = (roll_dmn[-1] - (roll_dmn[-1] / ma) + full_df.iloc[i, -4]) roll_dmn.append(temp_dmn) # Change series in df full_df['roll_tr'] = roll_tr full_df['roll_dmp'] = roll_dmp full_df['roll_dmn'] = roll_dmn # Compute directional indicator full_df['di_pos'] = 100 * (full_df['roll_dmp'] / full_df['roll_tr']) full_df['di_neg'] = 100 * (full_df['roll_dmn'] / full_df['roll_tr']) # Compute sum and diff full_df['di_sum'] = full_df['di_pos'] + full_df['di_neg'] full_df['di_diff'] = abs(full_df['di_pos'] - full_df['di_neg']) # Compute dx and rolling for adx full_df['dx'] = (full_df['di_diff'] / full_df['di_sum']) * 100 full_df['adx'] = full_df['dx'].rolling(ma).mean() # Same trick as for roll series adx = [None for i in range(2*ma-1)] adx.append(full_df['adx'].iloc[2*ma-1]) for i in range((2*ma), full_df.shape[0]): temp = (adx[-1] * (ma - 1) + full_df.iloc[i, -2]) / ma adx.append(temp) full_df['adx'] = adx # Prepares return df if full_output == True: df = data.copy() df = pd.concat([df, full_df], axis=1) else: df = full_df[['adx', 'dx']] return df def ATR(data, ma, full_output=False): """ Calculate average true range (ATR) for a given ohlc data. Parameters ---------- data: pd.DataFrame DataFrame containing OHLC data. Columns must have the following labels: High, Low, Close. Open column is not mandatory. ma: int How many obversations will be used to calculate moving average full_output: bool Returns input data and support series used in calculation Returns ---------- pd.DataFrame With columns atr and tr (true range) For full output, dff_hl, dff_hc and dff_lc are shown too """ # Handles input data if not isinstance(data, pd.DataFrame): raise TypeError('Input data is not a pandas DataFrame.') if not set(['High', 'Low', 'Close']).issubset(data.columns): raise IndexError('Missing necessary columns (High, Low or Close).') # Handles parameter input if not isinstance(ma, int): raise TypeError('ma parameter is not integer type.') full_df = pd.DataFrame() # Compute ranges full_df['dff_hl'] = abs(data['High'] - data['Low']) full_df['dff_hc'] = abs(data['High'] - data['Close'].shift(1)) full_df['dff_lc'] = abs(data['Low'] - data['Close'].shift(1)) full_df['tr'] = full_df[['dff_hl', 'dff_hc', 'dff_lc']].max(axis=1) full_df['atr'] = full_df['tr'].rolling(ma).mean() # Prepares return df if full_output == True: df = data.copy() df = pd.concat([df, full_df], axis=1) else: df = full_df[['atr', 'tr']] return df def bollband(data, ma, full_output=False): ''' Calculate bollinger bands for a given series. Parameters ---------- data: pd.Series/pd.DataFrame Series or dataframe to calculate bands. If df is passed, it must have a close or adjusted close column with the following labels: - Close - close - Adj Close - adj close ma: int Moving average parameter Returns ---------- pd.DataFrame With columns bollband_up and bollband_low. For full output, ma is shown too ''' # Handles input data if isinstance(data, pd.DataFrame): # All possibles names for close column possible_cols = ['Close', 'close', 'Adj Close', 'adj close'] # Select them cols = cols = [col for col in data.columns if col in possible_cols] # Check if there's only one close column if len(cols) > 1: raise KeyError('Ambiguous number of possible close prices column.') elif len(cols) == 0: raise IndexError('No close column. Pass desired column as a pd.Series.') # Copy data as series series = data[cols[0]].copy() elif isinstance(data, pd.Series): series = data.copy() else: raise TypeError('Input data is not a pandas Series or DataFrame.') # Handles parameter input if not isinstance(ma, int): raise TypeError('ma parameter is not integer type.') full_df = pd.DataFrame() full_df['ma'] = series.rolling(ma).mean() full_df['bollband_up'] = full_df['ma'] + 2 * full_df['ma'].rolling(ma).std() full_df['bollband_low'] = full_df['ma'] - 2 * full_df['ma'].rolling(ma).std() # Prepares return df if full_output == True: df = data.copy() df = pd.concat([df, full_df], axis=1) else: df = full_df[['bollband_up', 'bollband_low']] return df def MACD(data, slow, fast, ma, full_output=False): """ Calculate moving average convergence divergence (MACD) for a given time series (usually close prices). Parameters ---------- data: pd.Series/pd.DataFrame Series or dataframe to calculate MACD. If df is passed, it must have a close or adjusted close column with the following labels: - Close - close - Adj Close - adj close slow: int How many observations the slow line will look back fast: int How many obversations the fast line will look back ma: int How many obversations will be used to calculate moving average full_output: bool Returns input data and support series used in calculation Returns ---------- pd.DataFrame With columns macd_line and macd_signal For full output, slow_ma and fast_ma are shown too """ # Handles input data if isinstance(data, pd.DataFrame): # All possibles names for close column possible_cols = ['Close', 'close', 'Adj Close', 'adj close'] # Select them cols = cols = [col for col in data.columns if col in possible_cols] # Check if there's only one close column if len(cols) > 1: raise KeyError('Ambiguous number of possible close prices column.') elif len(cols) == 0: raise IndexError('No close column. Pass desired column as a pd.Series.') # Copy data as series series = data[cols[0]].copy() elif isinstance(data, pd.Series): series = data.copy() else: raise TypeError('Input data is not a pandas Series or DataFrame.') # Handles parameters inputs for parameter in [slow, fast, ma]: if not isinstance(parameter, int): raise TypeError('One or more parameters are not integer type.') if slow <= fast: raise ValueError('Slow line must have a value bigger than fast line') full_df = pd.DataFrame() # Calculate lines full_df['slow_ma'] = series.ewm(span=slow).mean() full_df['fast_ma'] = series.ewm(span=fast).mean() full_df['macd_line'] = abs(full_df['slow_ma'] - full_df['fast_ma']) full_df['macd_signal'] = full_df['macd_line'].ewm(span=ma).mean() # Prepares return df if full_output == True: df = data.copy() df =
pd.concat([df, full_df], axis=1)
pandas.concat
""" Analysis plots of transient sources $Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/like2/analyze/transientinfo.py,v 1.7 2017/11/18 22:26:38 burnett Exp $ """ import os, pickle, glob from astropy.io import fits as pyfits from uw.like2.analyze import (sourceinfo, associations,) from uw.like2.tools import DateStamp from pointlike import IntVector from skymaps import Band, SkyDir from uw.like2.pub import healpix_map import numpy as np import pylab as plt import pandas as pd from analysis_base import (html_table, FloatFormat,) from . import (sourceinfo, localization, associations,) class TransientInfo(sourceinfo.SourceInfo): """Transient source properties """ require='pickle.zip' def setup(self, **kw): super(TransientInfo, self).setup(**kw) self.plotfolder='transients' #needed by superclass print ('transients:', sum(self.df.transient)) self.df = self.df.ix[self.df.transient] assert len(self.df)>0, 'No transients found' self.loc=localization.Localization(df=self.df) # to make plots using code self.assoc = associations.Associations(df=self.df) def cumulative_ts(self): """ Cumulative test statistic TS A logN-logS plot, but using TS. Important thresholds at TS=10 and 25 are shown. """ df = self.df df['prefix'] = [n[:2] for n in df.index] other_ts=[] other_label=[] if sum(df.prefix=='PG')>0: other_ts.append(df.ts[df.prefix=='PG']) other_label.append('PGwave') tsmap_sel = (df.prefix=='Sh') | (df.prefix=='S ')|(df.prefix=='TS') if sum(tsmap_sel)>0: other_ts.append(df.ts[tsmap_sel]) other_label.append('TSmap') fig=super(TransientInfo, self).cumulative_ts(check_localized=False, ts = df.ts, label='all', other_ts=other_ts, other_label=other_label, legend=True, ); plt.setp(fig.axes[0], ylim=(1,1000), xlim=(9,100)) fig.set_facecolor('white') return fig def association_summary(self): """Summary %(summary_html)s """ self.assoc.summary() self.summary_html = self.assoc.summary_html def bzcat_study(self): """AGN analysis %(self.bzcat_html)s """ fig = self.assoc.bzcat_study(tsmax=200, title='Cumulative bzcat associations') self.bzcat_html = self.assoc.bzcat_html fig.set_facecolor('white') return fig def all_plots(self): self.runfigures([ self.census, self.cumulative_ts, self.non_psr_spectral_plots, self.fit_quality, self.pivot_vs_e0, self.loc.localization, self.loc.locqual_hist, self.association_summary, self.bzcat_study, ]) class ExtTransientInfo(TransientInfo): """ subclass invoked with a specific path """ def __init__(self, model_path, quiet=True): self.curdir = os.getcwd() try: self.model_path=model_path os.chdir(model_path) if not quiet: print (os.getcwd()) self.skymodel = os.path.split(os.getcwd())[-1] self.setup(refresh=False, quiet=quiet) self.plotfolder=model_path+'/plots/'+self.plotfolder finally: os.chdir(self.curdir) def all_plots(self): os.chdir(self.model_path) try: super(ExtTransientInfo, self).all_plots() finally: os.chdir(self.curdir) #B12 = Band(12) #def neighbors(i): # iv = IntVector() # n = B12.findNeighbors(int(i),iv) # return list(iv) def legend(ax, **kw): leg = ax.legend(**kw) for box in leg.get_patches(): box._height=0; box._y=0.5 def delta_ts_figure(df, title='', ax=None, xlim=(-4,10), ymax=None, binsize=0.5): """ make a Delta TS figure using the dataframe assuming it has ts and deltats or delta_ts columns """ if ax is None: fig,ax = plt.subplots(figsize=(5,5)) else: fig = ax.figure deltats= np.array(df.adeltats if 'adeltats' in df else df.deltats if 'deltats' in df else df.delta_ts, float) ts = np.array(df.ts, float) bins = np.linspace(xlim[0],xlim[-1],(xlim[-1]-xlim[0])/binsize+1 ) hist_kw=dict(bins=bins, log=True, histtype='step', lw=2) ax.hist( deltats.clip(*xlim), label='all', **hist_kw) ax.hist( deltats[ts<25].clip(*xlim), color='orange', label='TS<25', **hist_kw) plt.setp(ax, xlabel='delta TS', xlim=xlim, ylim=(0.8,ymax), title=title) x = np.linspace(0,10,51) ax.plot(x, len(deltats)*binsize*0.5*np.exp(-x/2),ls='--', color='r', label='expected') ax.grid(True, alpha=0.5); ax.axvline(0, color='k') leg=ax.legend() for box in leg.get_patches(): box._height=0; box._y=0.5 fig.set_facecolor('white') return fig class Analysis(object): """ a place to put code to make plots for all months """ def __init__(self, path=None, prefix='', quiet=False, all_months_model='../P301_6years/uw972'): """ If prefix=='o', then it is obssim """ if path is not None: os.chdir(os.path.expandvars(path)) else: path=os.getcwd() files = sorted(glob.glob(prefix+'month*/sources.pickle')); print ('Found {} "monthxx" folders in folder {}'.format(len(files), path)) self.monthlist = [f.split('/')[0] for f in files]; self.monthinfo=monthinfo=[] for month in self.monthlist: #[:last+1]: sinfo = sourceinfo.ExtSourceInfo(month, quiet=True) monthinfo.append(sinfo) assoc = associations.ExtAssociations(month,quiet=True) for key in 'aprob acat aname aang adeltats'.split(): sinfo.df[key] = assoc.df[key] # concatenate the transient sources dflist= [] for i,month in enumerate(monthinfo): month.df['month'] = i+1 month.df['has_assoc'] = [a is not None for a in month.df.associations] monthdf = month.df[month.df.transient][""" ra dec glat glon ts modelname pindex eflux flux a b ang locqual aprob flux pindex index2 e0 flags flux_unc pindex_unc index2_unc cutoff cutoff_unc fitqual acat adeltats aang has_assoc month""".split()] if prefix=='o': monthdf.index = [s.replace('TSxx','TS%02d' % i) for s in monthdf.index] dflist.append(monthdf) df = pd.concat(dflist) df['skydir'] = skydirs = map(SkyDir, df.ra, df.dec) df['roi'] = map( lambda s: Band(12).index(s), skydirs) # add the photon density from the 6-year dataset filename=os.path.expandvars('$FERMI/skymodels/P301_6years/uw972/hptables_ts_kde_512.fits') kde6 = healpix_map.FromFITS(filename,'kde') kdepercent = np.percentile(kde6.vec, np.arange(0,100)) kdevals = map(kde6, skydirs) df['kdepercentile'] = kdepercent.searchsorted(kdevals) # select those with TS>10 and good localization good = np.logical_not((df.ts<10) | (df.locqual>8) | (df.a<0.001) | (df.a>0.25)) self.df = df[good] self.hilat = np.abs(self.df.glat)>10 self.assoc = np.isfinite(self.df.aprob) if not quiet: print ('good sources: %d/%d' % (len(self.df), len(df))) print ('High latitude (>10 deg)', sum(self.hilat)) print ('Associated', sum(self.assoc)) # get the 6-year dataframe for reference, and access to functions in SourceInfo self.sinfo = sourceinfo.ExtSourceInfo(all_months_model) self.df6y = self.sinfo.df def all_6y_names(self): """ return list of all 6-year names found in the monthly models """ return self.df6y[self.df6y.ts>10].index def psr_names(self): """ return list of unique PSR names found in the monthly models """ names=[] for month in self.monthinfo: df = month.df for nm in list(df.index): if nm.startswith('PSR'): names.append(nm) return list(set(names)) def monthly_info(self, sname): """Return monthly info for sources in all or most months """ s6y = self.df6y assert sname in s6y.index, 'Source %s not found in 6-year list' % sname rec6y = s6y.ix[sname] eflux6y = rec6y.flux * rec6y.e0**2*1e6 fluxunc67 = rec6y.flux_unc ass = rec6y.associations if ass is not None: acat = ass['cat'][0] aprob = ass['prob'][0] else: aprob = 0 acat='' # compile monthly stuff months = dict() for i,month in enumerate(self.monthinfo): if sname not in month.df.index: continue rec = month.df.ix[sname] eflux = rec.flux * rec.e0**2*1e6 relfluxunc = rec.flux_unc/rec.flux months[i+1]= dict( eflux = eflux, relfluxunc = relfluxunc, pull = (1-eflux6y/eflux)/relfluxunc, a = rec.a, ts=rec.ts, locqual=rec.locqual, good= rec.ts>10 and rec.a>0.001 and rec.a<0.25 and rec.locqual<8, adeltats=rec.adeltats, aprob=aprob, acat=acat, ) if len(months)==0: self.notdetected.append(sname) #print ('Source %s not detected in any month' % sname) return None monthly =
pd.DataFrame(months)
pandas.DataFrame
""" Particles and Populations ========================= A particle contains the sampled parameters and simulated data. A population gathers all particles collected in one SMC iteration. """ from typing import Callable, List, Tuple import numpy as np import pandas as pd from pyabc.parameters import Parameter import logging logger = logging.getLogger("Population") class Particle: """ An (accepted or rejected) particle, containing the information that will also be stored in the database. Stores all summary statistics that were generated during the creation of this particle, and a flag indicating whether this particle was accepted or not. Parameters ---------- m: The model index. parameter: The model specific parameter. weight: The weight of the particle. 0 <= weight <= 1. accepted_sum_stats: List of accepted summary statistics. This list is usually of length 1. This list is longer only if more than one sample is taken for a particle. This list has length 0 if the particle is rejected. accepted_distances: A particle can contain more than one sample. If so, the distances of the individual samples are stored in this list. In the most common case of a single sample, this list has length 1. rejected_sum_stats: List of rejected summary statistics. rejected_distances: List of rejected distances. accepted: True if particle was accepted, False if not. preliminary: Whether this particle is only preliminarily accepted. Must be False eventually for all particles. .. note:: There are two different ways of weighting particles: First, the weights can be calculated as emerges from the importance sampling. Second, the weights of particles belonging to one model can be summed to, after normalization, find model probabilities. Then, the weights of all particles belonging to one model can be summed to one. Weighting is transferred to the second way in _normalize_weights() in order to also have access to model probabilities. This mode is also stored in the database. If one needs access to the first weighting scheme later on again, one has to perform backwards transformation, multiplying the weights with the model probabilities. """ def __init__(self, m: int, parameter: Parameter, weight: float, accepted_sum_stats: List[dict], accepted_distances: List[float], rejected_sum_stats: List[dict] = None, rejected_distances: List[float] = None, accepted: bool = True, preliminary: bool = False): self.m = m self.parameter = parameter self.weight = weight self.accepted_sum_stats = accepted_sum_stats self.accepted_distances = accepted_distances if rejected_sum_stats is None: rejected_sum_stats = [] self.rejected_sum_stats = rejected_sum_stats if rejected_distances is None: rejected_distances = [] self.rejected_distances = rejected_distances self.accepted = accepted self.preliminary = preliminary class Population: """ A population contains a list of particles and offers standardized access to them. Upon initialization, the particle weights are normalized and model probabilities computed as described in _normalize_weights. """ def __init__(self, particles: List[Particle]): self._list = particles.copy() self._model_probabilities = None self._normalize_weights() def __len__(self): return len(self._list) def get_list(self) -> List[Particle]: """ Returns ------- A copy of the underlying particle list. """ return self._list.copy() def _normalize_weights(self): """ Normalize the cumulative weight of the particles belonging to a model to 1, and compute the model probabilities. Should only be called once. """ store = self.to_dict() model_total_weights = {m: sum(particle.weight for particle in plist) for m, plist in store.items()} population_total_weight = sum(model_total_weights.values()) model_probabilities = {m: w / population_total_weight for m, w in model_total_weights.items()} # update model_probabilities attribute self._model_probabilities = model_probabilities # normalize weights within each model for m in store: model_total_weight = model_total_weights[m] plist = store[m] for particle in plist: particle.weight /= model_total_weight def update_distances(self, distance_to_ground_truth: Callable[[dict], float]): """ Update the distances of all summary statistics of all particles according to the passed distance function (which is typically different from the distance function with which the original distances were computed). :param distance_to_ground_truth: Distance function to the observed summary statistics. """ for particle in self._list: for i in range(len(particle.accepted_distances)): particle.accepted_distances[i] = distance_to_ground_truth( particle.accepted_sum_stats[i], particle.parameter) def get_model_probabilities(self) -> pd.DataFrame: """ Get probabilities of the individual models. Returns ------- model_probabilities: List The model probabilities. """ # _model_probabilities are assigned during normalization vars = [(key, val) for key, val in self._model_probabilities.items()] ms = [var[0] for var in vars] ps = [var[1] for var in vars] return pd.DataFrame({'m': ms, 'p': ps}).set_index('m') def get_alive_models(self) -> List: return self._model_probabilities.keys() def nr_of_models_alive(self) -> int: return len(self.get_alive_models()) def get_distribution(self, m: int) -> Tuple[pd.DataFrame, np.ndarray]: particles = self.to_dict()[m] parameters =
pd.DataFrame([p.parameter for p in particles])
pandas.DataFrame
import numpy as np import pandas as pd import quandl import urllib.request import requests import json import os from pathlib import Path import threading import shutil from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.common.exceptions import WebDriverException from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from bs4 import BeautifulSoup import time import random import re import datetime as dt from pandas.tseries.offsets import BDay import pandas_market_calendars as mcal import yaml from functools import reduce import findata.utils as fdutils class DataImporter: def __init__(self, start_date='04/30/2011', end_date=None, save_dir='data/raw', config_file='config.yml', yf_error_msgs=('404 Not Found', 'upstream connect error'), yf_headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36', 'content-type': "application/json", 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'} ): self.start_date = dt.datetime.strptime(start_date, '%m/%d/%Y') self.end_date = dt.datetime.now() if end_date is None else dt.datetime.strptime(end_date, '%m/%d/%Y') if self.start_date.month==self.end_date.month and \ self.start_date.day==self.end_date.day and self.start_date.year==self.end_date.year: raise ValueError('Start and end date are the same!') self.save_dir = os.path.join(save_dir, '') if not os.path.exists(self.save_dir): Path(self.save_dir).mkdir(parents=True, exist_ok=True) self.logger = fdutils.new_logger('DataImporter') self.yfheaders = yf_headers self._parse_config(config_file) self.yf_error_msgs = yf_error_msgs def get_ticker_list(self, name='sp500', save_dir='data/symbols', overwrite=False): if not os.path.exists(save_dir): os.makedirs(save_dir) filename = os.path.join(save_dir, name + '.csv') self.ticker_file = filename if os.path.exists(filename) and not overwrite: self.tickers = pd.read_csv(filename) else: if name=='sp500': # Scrape list of S&P500 companies from Wikipedia html = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies') soup = BeautifulSoup(html.text, 'lxml') table = soup.find('table', {'class': 'wikitable sortable'}) tickers = [] for row in table.findAll('tr')[1:]: ticker = row.findAll('td')[0].text ticker = ticker.strip() tickers.append(ticker) self.tickers = pd.DataFrame(data={'symbol':tickers, 'prices_exist': True}) self.tickers.to_csv(filename, index=False) def save_ticker_list(self): self.tickers.to_csv(self.ticker_file, index=False) def _parse_config(self, config_file): with open(config_file) as f: self.config = yaml.load(f, Loader=yaml.FullLoader) def firefox_session(self, url, headless=True): options = Options() options.headless = headless fp = webdriver.FirefoxProfile() fp.set_preference("browser.download.folderList", 2) fp.set_preference("browser.download.manager.showWhenStarting", False) fp.set_preference("browser.download.dir", f'{os.getcwd()}/{self.save_dir}'.replace(r'/','\\')) fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv") self.logger.info(f'Opening {url} in Firefox') driver = webdriver.Firefox(options=options, firefox_profile=fp, executable_path=self.config['geckodriver']['path']) driver.implicitly_wait(10) driver.get(url) time.sleep(5) return driver def import_all(self): functions = [self.import_dix_gex, self.import_yf_indicators] if 'quandl' in self.config.keys(): functions.append(self.import_quandl) if 'investing' in self.config.keys(): functions.append(self.import_move) functions.append(self.import_pmi) threads = [] for f in functions: process = threading.Thread(target=f) process.start() threads.append(process) for process in threads: process.join() self.import_tickers() def download_file(self, save_file, url): self.logger.info(f'Beginning download of {url} to {self.save_dir}{save_file}') try: urllib.request.urlretrieve(url, self.save_dir + save_file) self.logger.info(f'Finished download of {url}') except Exception as e: self.logger.debug(f'Exception encountered while downloading {url}:\n' + str(e)) def import_dix_gex(self, save_file='DIX.csv', url='https://squeezemetrics.com/monitor/static/DIX.csv'): self.download_file(save_file, url) def login_investing(self, driver): # Close stupid popup try: element = driver.find_element_by_class_name("allow-notifications-popup-close-button") ActionChains(driver).move_to_element(element).click().perform() except Exception: pass time.sleep(random.randint(2,4)) # Other stupid popup ActionChains(driver).send_keys('Keys.ESCAPE').perform() self.logger.info("Logging into 'www.investing.com'") # Login element = driver.find_element_by_class_name("login") ActionChains(driver).move_to_element(element).click().perform() time.sleep(random.randint(2,4)) # Enter user name element = driver.find_element_by_id('loginFormUser_email') element.clear() # element.send_keys("<EMAIL>") ActionChains(driver).move_to_element(element).click().perform() ActionChains(driver).send_keys(self.config['investing']['email']).perform() time.sleep(random.randint(1,3)) # Enter password element = driver.find_element_by_id('loginForm_password') element.clear() # element.send_keys("<KEY>") ActionChains(driver).move_to_element(element).click().perform() ActionChains(driver).send_keys(self.config['investing']['pwd']).perform() time.sleep(random.randint(1,3)) # Click submit ActionChains(driver).send_keys(Keys.ENTER).perform() time.sleep(random.randint(4,7)) return driver def import_move(self, default_file='ICE BofAML MOVE Historical Data.csv', save_file='indicator_move.csv', url='https://www.investing.com/indices/ice-bofaml-move-historical-data'): driver = self.firefox_session(url=url, headless=False) driver = self.login_investing(driver) try: self.logger.info('Picking start date and downloading MOVE index') # Pick date range element = driver.find_element_by_id("widgetFieldDateRange") ActionChains(driver).move_to_element(element).click().perform() time.sleep(random.randint(2,4)) for i in range(10): ActionChains(driver).send_keys(Keys.BACKSPACE).perform() time.sleep(0.1) ActionChains(driver).send_keys(self.start_date.strftime('%m/%d/%Y')).perform() time.sleep(random.randint(1,3)) # Click apply ActionChains(driver).send_keys(Keys.ENTER).perform() time.sleep(random.randint(1,3)) # Save file to Downloads element = driver.find_element_by_xpath("//a[@title='Download Data']") ActionChains(driver).move_to_element(element).click().perform() time.sleep(random.randint(5,10)) self.logger.info('Moving downloaded file from temp directory') # Move file to desired directory shutil.move(self.save_dir + default_file, self.save_dir + save_file) except Exception as e: self.logger.debug("Exception occurred while downloading MOVE index':\n" + str(e)) finally: try: driver.quit() except: return None def import_pmi(self, save_file='indicator_pmi.csv', url='https://www.investing.com/economic-calendar/manufacturing-pmi-829'): driver = self.firefox_session(url=url, headless=False) driver = self.login_investing(driver) try: self.logger.info('Expanding PMI table') # Click "Show More" until there is no more to be shown while True: try: element = driver.find_element_by_xpath("//div[@id='showMoreHistory829']/a") if not element.is_displayed(): self.logger.info('Finished expanding PMI table') break element.send_keys(Keys.ENTER) time.sleep(random.uniform(1,5)) except Exception as e: self.logger.debug('Exception occurred while expanding PMI table:\n' + str(e)) break self.logger.info('Scraping PMI table') page = BeautifulSoup(driver.page_source, 'lxml') tab = [] for tr in page.find_all('table')[0].find_all('tr')[2:]: tds = tr.find_all('td') row = [tr.text for tr in tds] tab.append(row) tab = pd.DataFrame(tab, columns=['Date', 'Time', 'Actual', 'Forecast', 'Previous', 'None']) tab.drop(columns=['Time','Previous','None'], inplace=True) tab.Date = [re.sub(' [(].*','',x) for x in tab.Date] tab.replace('\xa0', np.nan,inplace=True) tab.to_csv(self.save_dir + save_file, index=False) except Exception as e: self.logger.debug("Exception occurred while downloading PMI index':\n" + str(e)) finally: try: driver.quit() except: return None def download_yf_prices(self, ticker, save_file): params = { "period1": int(time.mktime(self.start_date.timetuple()))+14400, "period2": int(time.mktime(self.end_date.replace(hour=23, minute=59, second=59).timetuple()))+14400, "interval": '1d', "events": "history", "includeAdjustedClose": 'true' } url = rf"https://query1.finance.yahoo.com/v7/finance/download/{ticker}?" \ + '&'.join('='.join([k, str(params[k])]) for k in params.keys()) r = requests.get(url, headers=self.yfheaders) if not r.text.startswith(self.yf_error_msgs): try: with open(save_file, 'w+') as f: f.write(r.text) except Exception as e: self.logger.debug(f'File save for {ticker} failed in {os.getcwd()}:\n' + str(e)) else: self.logger.debug(f'{ticker} not found in Yahoo Finance') def import_tickers(self, skip_existing=False, save_subdir='tickers', suffix=''): tickers = self.tickers['symbol'] tickers = [ticker + suffix for ticker in tickers] save_subdir = os.path.join(save_subdir, '') if not os.path.exists(self.save_dir + save_subdir): os.makedirs(self.save_dir + save_subdir) self.logger.info('Downloading tickers from Yahoo Finance') for ticker in tickers: save_file = f'{self.save_dir}{save_subdir}{ticker}.csv' if skip_existing: if os.path.exists(save_file): continue self.download_yf_prices(ticker, save_file) time.sleep(random.uniform(0.5,2)) self.logger.info('Finished download of tickers from Yahoo Finance') def rec2row(self, rrr): return pd.DataFrame(data=rrr, index=[0]) def processRecords(self, rr, data): for i in range(0, len(rr)): x = self.rec2row(rr[i]) if not data is None: data = data.append(x) else: data = x return data def download_yf_chain(self, driver, date, tag, ticker, save_dir): try: opt_url = 'https://finance.yahoo.com/quote/' + ticker + '/options?p=' + ticker driver.get(opt_url) page = BeautifulSoup(driver.page_source, 'lxml') # Retrieve all options listed, and their associated ID number optslist = page.select_one('select.Bd') opt_id = list() opt_dt = list() for o in optslist.select('option'): opt_id.append(o['value']) opt_dt.append(o.string) opts_list =
pd.DataFrame(data={'id':opt_id, 'date':opt_dt})
pandas.DataFrame
######################################################################################################################## # |||||||||||||||||||||||||||||||||||||||||||||||||| AQUITANIA ||||||||||||||||||||||||||||||||||||||||||||||||||||||| # # |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| # # |||| To be a thinker means to go by the factual evidence of a case, not by the judgment of others |||||||||||||||||| # # |||| As there is no group stomach to digest collectively, there is no group mind to think collectively. |||||||||||| # # |||| Each man must accept responsibility for his own life, each must be sovereign by his own judgment. ||||||||||||| # # |||| If a man believes a claim to be true, then he must hold to this belief even though society opposes him. ||||||| # # |||| Not only know what you want, but be willing to break all established conventions to accomplish it. |||||||||||| # # |||| The merit of a design is the only credential that you require. |||||||||||||||||||||||||||||||||||||||||||||||| # # |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| # ######################################################################################################################## """ .. moduleauthor:: <NAME> This modules loads from disk the output from the indicators creates a single DataFrame for each currency that unifies all the timestamps, OR a unified DataFrame for all currencies and timestamps, depending on what was requested. Started refactoring this module on 26/04/2018. Currently thinking about dividing it into 2 different modules. Decided to make it only one module but remove AnalyticsLoader class and leave only standalone methods. """ import os.path import pandas as pd from aquitania.data_processing.util import get_stored_ai, add_asset_columns_to_df, save_df, add_to_dataframe def build_liquidation_dfs(broker_instance, asset, list_of_columns, signal): """ This method builds a DataFrame with all possible entries that will be fed to the liquidation module in order to evaluate which are the optimal exit points. :param broker_instance: (DataSource) connection to broker / database :param asset: (str) Asset Name :param list_of_columns: (list of str) detailing column names :param signal: (str) signal name :return: DataFrame with all possible entries :rtype: pandas DataFrame """ # Get column names # TODO this operation is too expansive, need to refactor this for a cheaper operation / pickle_state this inside strategy columns_dict = get_dataframes_that_contain_columns(broker_instance, asset, list_of_columns) # Instantiate variables timestamp = signal[0] final_df = None complete = 'complete_{}'.format(timestamp) # Check if there is an indicator output file for given asset for filename in os.listdir(broker_instance.ds.indicator_output_folder): if asset in filename: break # If no file is found in the for loop, raises error else: raise IOError('No indicator that for selected currency: ' + asset) # Retrieves DataFrame that will be used to filter valid signal rows df = pd.read_hdf(broker_instance.get_indicator_filename(asset, timestamp))[[signal, complete]] # Gets all DataFrames according to key values (each key represents one timestamp) for key in columns_dict.keys(): # Builds filepath str filepath = '{}/{}/{}'.format(broker_instance.ds.indicator_output_folder, asset, key) # Loads Indicators for given timestamp and asset temp_df = pd.read_hdf(filepath)[list(columns_dict[key])] # Instantiates first DataFrame to be joined if final_df is None: # Creates a filter column temp_df['filter'] = (df[complete] == 1) & (df[signal] != 0) # Makes a filter only to select rows where complete and signal are True final_df = temp_df.query('filter == 1') # Deletes filter column del final_df['filter'] else: # Makes inner join with DataFrame that has filtered rows (output will be filtered as well) final_df = pd.concat([final_df, temp_df], join='inner', axis=1) # Returns filtered DataFrame return final_df def get_dataframes_that_contain_columns(broker_instance, asset, set_of_columns): """ Get DataFrames IDs for every column (str) in 'set_of_columns'. :param broker_instance: (DataSource) connection to broker / database :param asset: (str) Asset Name :param set_of_columns: (set of str) names of columns to be selected across multiple DataFrames :return: dictionary of lists where key is the name of the storage file and the relevant column it contains :rtype: dict of lists """ # Get a DataFrame with all columns by key dict_of_columns = broker_instance.get_dict_of_file_columns(asset) # Instantiates new dict selected_keys = {} # For each possible key checks if it contains one of the columns in 'list_of_columns' for key in dict_of_columns.keys(): # Find if there is an intersection between the selected columns and the actual columns in the file set_intersect = set_of_columns.intersection(dict_of_columns[key]) # If there are columns that intersect, pickle_state it to output according to key in 'dict_of_columns' if len(set_intersect) > 0: selected_keys[key] = set_intersect # Returns a dict of sets that contain intersecting values return selected_keys def build_ai_df(broker_instance, asset_list, signal): """ Creates one DataFrame with all columns from all timestamps filtering rows for only the rows where signal is True. This creates a much less computationally expensive DataFrame. :param broker_instance: (DataSource) connection to broker / database :param asset_list: (list of str) list of Asset Names :param signal: (str) entry name :return: DataFrame with all assets and all columns :rtype: pandas DataFrame """ # Initialize output variable final_df = None # Runs routine for each of the assets for asset in asset_list: # Gets stored AI if any cur_df = get_stored_ai(asset, signal) # TODO add verification to check if same size of the liquidation DataFrame if not isinstance(cur_df, pd.DataFrame): # Routine for when a new AI DataFrame needs to be created df_filter = get_signal_filter(broker_instance, asset, signal) # Get asset output (all timestamps combined into a single DataFrame) cur_df = get_asset_output(broker_instance, asset, df_filter, signal) # Add columns relative to asset classification to DataFrame cur_df = add_asset_columns_to_df(cur_df, asset) # Save AI DataFrame into disk save_df(cur_df, 'data/ai/' + asset + '_' + signal) # Combines individual asset output into a single DataFrame final_df = add_to_dataframe(final_df, cur_df, axis=0) # Returns Final DataFrame return final_df def get_signal_filter(broker_instance, asset, signal): """ Creates a filter to only select rows that have a signal on a DataFrame. :param broker_instance: (DataSource) connection to broker / database :param asset: (str) Asset Name :param signal: (str) entry name :return: Boolean values to determine which rows to select in a DataFrame :rtype: numpy Array """ # Generates Timestamp Id - single digit number as (str) timestamp = signal[0] # Gets signal filter with pd.HDFStore(broker_instance.get_indicator_filename(asset, timestamp)) as hdf: df = hdf.select(key='indicators', columns=[signal, 'complete_' + timestamp]) # Returns signal filter return df['complete_' + timestamp].astype(bool) & df[signal].astype(bool) def get_asset_output(broker_instance, asset, df_filter, signal): """ Gets a single huge DataFrame combining all timestamps for a given asset. :param broker_instance: (DataSource) connection to broker / database :param asset: (str) Asset Name :param df_filter: (numpy Array) Boolean values to determine which rows to select in a DataFrame :param signal: (str) entry name :return: DataFrame combining all timestamps for a given asset :rtype: pandas DataFrame """ # Initializes variables folder = broker_instance.ds.indicator_output_folder final_df = None list_dir = sorted(os.listdir(folder)) # Search for directories for directory in list_dir: # Check if it is desired asset directory if asset in directory: # Gets folder name for current directory asset_dir = '{}/{}/'.format(folder, asset) # Sorts file names to create DataFrame in a logical order of columns list_output = sorted(os.listdir(asset_dir)) # Runs file by file routine to append them into a single DataFrame for the_file in list_output: # Reads and filters DataFrame temp_df =
pd.read_hdf(asset_dir + the_file)
pandas.read_hdf
import os import copy import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import matplotlib.dates as mdates from datetime import date, timedelta, datetime import seaborn as sns import geopandas as gpd import matplotlib.colors as colors from plotting.colors import load_color_palette mpl.rcParams['pdf.fonttype'] = 42 LL_date = '210412' idph_data_path = '/Volumes/fsmresfiles/PrevMed/Covid-19-Modeling/IDPH line list' cleaned_line_list_fname = os.path.join(idph_data_path, 'LL_%s_JGcleaned_no_race.csv' % LL_date) box_data_path = '/Users/jlg1657/Box/NU-malaria-team/data/covid_IDPH' project_path = '/Users/jlg1657/Box/NU-malaria-team/projects/covid_chicago' plot_path = os.path.join(project_path, 'Plots + Graphs', '_trend_tracking') emr_fname = os.path.join(box_data_path, 'emresource_by_region.csv') spec_coll_fname = os.path.join(box_data_path, 'Corona virus reports', '%s_LL_cases_by_EMS_spec_collection.csv' % LL_date) shp_path = os.path.join(box_data_path, 'shapefiles') def load_cleaned_line_list() : df = pd.read_csv(cleaned_line_list_fname) return df def make_heatmap(ax, adf, col) : palette = sns.color_palette('RdYlBu_r', 101) df = adf.dropna(subset=[col]) df = df.groupby([col, 'EMS'])['id'].agg(len).reset_index() df = df.rename(columns={'id' : col, col : 'date'}) df['date'] = pd.to_datetime(df['date']) df = df.sort_values(by=['EMS', 'date']) ax.fill_between([np.min(df['date']), np.max(df['date']) + timedelta(days=1)], [0.5, 0.5], [11.5, 11.5], linewidth=0, color=palette[0]) for ems, edf in df.groupby('EMS') : max_in_col = np.max(edf[col]) print(ems, max_in_col) for r, row in edf.iterrows() : ax.fill_between([row['date'], row['date'] + timedelta(days=1)], [ems-0.5, ems-0.5], [ems+0.5, ems+0.5], color=palette[int(row[col]/max_in_col*100)], linewidth=0) ax.set_title(col) ax.set_ylabel('EMS region') formatter = mdates.DateFormatter("%m-%d") ax.xaxis.set_major_formatter(formatter) ax.xaxis.set_major_locator(mdates.MonthLocator()) def heatmap() : adf = load_cleaned_line_list() fig = plt.figure(figsize=(10,5)) fig.subplots_adjust(left=0.05, right=0.97) cols = ['specimen_collection', 'deceased_date'] for c, col in enumerate(cols) : ax = fig.add_subplot(1,len(cols),c+1) make_heatmap(ax, adf, col) plt.savefig(os.path.join(plot_path, 'EMS_cases_deaths_heatmap_%sLL.png' % LL_date)) plt.show() def aggregate_to_date_spec_collection() : adf = load_cleaned_line_list() col = 'specimen_collection' df = adf.dropna(subset=[col]) df = df.groupby([col, 'EMS'])['id'].agg(len).reset_index() df = df.rename(columns={'id' : col, col : 'date'}) df = df.sort_values(by=['EMS', 'date']) df.to_csv(spec_coll_fname, index=False) def plot_EMS_by_line(colname) : df = pd.read_csv(os.path.join(box_data_path, 'Cleaned Data', '%s_jg_aggregated_covidregion.csv' % LL_date)) df = df[df['covid_region'].isin(range(1,12))] df['date'] =
pd.to_datetime(df['date'])
pandas.to_datetime
# Copyright (c) 2019-2021 - for information on the respective copyright owner # see the NOTICE file and/or the repository # https://github.com/boschresearch/pylife # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = "<NAME>" __maintainer__ = __author__ import pytest import numpy as np import pandas as pd from pylife.core import * foo_bar_baz = pd.DataFrame({'foo': [1.0, 1.0], 'bar': [1.0, 1.0], 'baz': [1.0, 1.0]}) def test_keys_dataframe(): pd.testing.assert_index_equal(foo_bar_baz.test_accessor_none.keys(), pd.Index(['foo', 'bar', 'baz'])) def test_keys_series(): pd.testing.assert_index_equal(foo_bar_baz.iloc[0].test_accessor_none.keys(), pd.Index(['foo', 'bar', 'baz'])) def test_missing_keys_none(): assert foo_bar_baz.test_accessor_none.get_missing_keys(['foo', 'bar']) == [] def test_missing_keys_one(): assert foo_bar_baz.test_accessor_none.get_missing_keys(['foo', 'foobar']) == ['foobar'] def test_missing_keys_two(): assert set(foo_bar_baz.test_accessor_none.get_missing_keys(['foo', 'foobar', 'barfoo'])) == set(['foobar', 'barfoo']) def test_from_parameters_frame(): foo = [1.0, 2.0, 3.0] bar = [10.0, 20.0, 30.0] baz = [11.0, 12.0, 13.0] accessor = AccessorNone.from_parameters(foo=foo, bar=bar, baz=baz) pd.testing.assert_index_equal(accessor.keys(), pd.Index(['foo', 'bar', 'baz'])) expected_obj = pd.DataFrame({'foo': foo, 'bar': bar, 'baz': baz}) pd.testing.assert_frame_equal(accessor._obj, expected_obj) assert accessor.some_property == 42 def test_from_parameters_series_columns(): foo = 1.0 bar = 10.0 baz = 11.0 accessor = AccessorNone.from_parameters(foo=foo, bar=bar, baz=baz) pd.testing.assert_index_equal(accessor.keys(), pd.Index(['foo', 'bar', 'baz'])) expected_obj = pd.Series({'foo': foo, 'bar': bar, 'baz': baz}) pd.testing.assert_series_equal(accessor._obj, expected_obj) assert accessor.some_property == 42 def test_from_parameters_series_index(): foo = [1.0, 2.0, 3.0] accessor = AccessorOneDim.from_parameters(foo=foo) pd.testing.assert_index_equal(accessor.keys(), pd.Index(['foo'])) expected_obj = pd.Series({'foo': foo}) pd.testing.assert_series_equal(accessor._obj, expected_obj) assert accessor.some_property == 42 def test_from_parameters_missing_keys(): foo = 1.0 baz = 10.0 with pytest.raises(AttributeError, match=r'^AccessorNone.*bar'): AccessorNone.from_parameters(foo=foo, baz=baz) @pd.api.extensions.register_series_accessor('test_accessor_one_dim') class AccessorOneDim(PylifeSignal): def _validate(self): if not isinstance(self._obj, pd.Series): raise TypeError("This accessor takes only pd.Series") @property def some_property(self): return 42 @pd.api.extensions.register_series_accessor('test_accessor_none') @pd.api.extensions.register_dataframe_accessor('test_accessor_none') class AccessorNone(PylifeSignal): def _validate(self): self.fail_if_key_missing(['foo', 'bar']) def already_here(self): return 23 @property def some_property(self): return 42 @property def not_working_property(self): self._missing_attribute @pd.api.extensions.register_series_accessor('test_accessor_one') @
pd.api.extensions.register_dataframe_accessor('test_accessor_one')
pandas.api.extensions.register_dataframe_accessor
from django.shortcuts import render, redirect from django.contrib import messages from sqlalchemy import inspect import sqlalchemy import pandas as pd import ast import numpy as np from sqlalchemy.sql import exists import xgboost as xgb import plotly.express as px import plotly.io as pio import plotly.graph_objs as po import plotly from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import MinMaxScaler # function for processing the "lessons" dataframe def lessons_process(lessons): # turn strdict into dict, assign to same column variable lessons['resources'] = [ast.literal_eval(x) for x in lessons['resources']] dataframes = [] lesson_id_iter = iter(list(lessons['id'])) for row in lessons['resources']: row_dict = {'content_id': [], 'channel_id': [], 'contentnode_id': [], } try: for diction in row: keys = diction.keys() for key in keys: row_dict[key].append(diction[key]) dataframe = pd.DataFrame(row_dict) dataframe['lesson_id'] = next(lesson_id_iter) dataframes.append(dataframe) except Exception as err: print(err) pass dataframe_1 = dataframes[0] for dataframe in dataframes[1:]: dataframe_1 = pd.concat([dataframe_1, dataframe], axis=0) final_merge = pd.merge(lessons, dataframe_1, left_on='id', right_on='lesson_id', how='inner') final_merge['difficulty'] = [x.split()[1] if x != '' else np.NaN for x in final_merge['description']] final_merge['subject'] = [x.split()[0] if x != '' else np.NaN for x in final_merge['description']] return final_merge # Create your views here. def menu(request): sql = """ SELECT * FROM kolibriauth_facilityuser """ db_conn = sqlalchemy.create_engine('sqlite:///path\\to\\kolibri\\db.sqlite3') local_db_conn = sqlalchemy.create_engine('sqlite:///db.sqlite3') from sqlalchemy import MetaData db_conn.connect() request.session['user'] = [] facilusers = pd.read_sql(sql, db_conn) users = [str(x) for x in facilusers['username']] if local_db_conn.dialect.has_table(local_db_conn, "facilityuserstable"): pass else: facilusers['survey'] = 0 facilusers.to_sql('facilityuserstable', local_db_conn, if_exists='replace') if request.method == 'POST': # if user == admin user if request.POST['users'] == 'pn1eto': request.session['user'] = request.POST['users'] return redirect('admin_dashboard/') else: request.session['user'] = request.POST['users'] print(facilusers) messages.success(request, f'Hola, ahora estás en tu cuenta {str(request.POST["users"])}') return redirect('dashboard/') return render(request, 'menu.html', {'users': users, }) def dashboard(request): localengine = sqlalchemy.create_engine('sqlite:///db.sqlite3') sql = """ SELECT * FROM facilityuserstable """ user_local = pd.read_sql(sql, localengine) if int(user_local[user_local['username'] == str(request.session['user'])]['survey']) == 0: return redirect('/survey') else: engine2 = sqlalchemy.create_engine('sqlite:///path\\to\\kolibri\\db.sqlite3') sql = """ SELECT * FROM kolibriauth_facilityuser """ facilusers = pd.read_sql(sql, engine2) sql = """ SELECT * FROM logger_contentsessionlog """ lessons_log = pd.read_sql(sql, engine2) sql = """ SELECT * FROM logger_contentsummarylog """ contentsummary = pd.read_sql(sql, engine2) sql = """ SELECT * FROM content_contentnode where available = 1 """ channelcont = pd.read_sql(sql, engine2) sql = """ SELECT * FROM logger_attemptlog """ attempts = pd.read_sql(sql, engine2) sql = """ SELECT * FROM lessons_lesson """ lessons = pd.read_sql(sql, engine2) lessons = lessons_process(lessons) lessons_meta = pd.merge(lessons_log, facilusers, right_on='id', left_on='user_id', how='inner') lessons_meta = pd.merge(lessons_meta, channelcont, on='content_id', how='inner', ) lessons_meta = pd.merge(lessons_meta, contentsummary, on='content_id', how='inner', ) lessons_meta = pd.merge(lessons_meta, lessons, on='content_id', ) lessons_meta['video_loc'] = np.NaN video_loc = [0 if x == '{}' else ast.literal_eval(x)['contentState']['savedLocation'] for x in lessons_meta[lessons_meta['kind'] == 'video']['extra_fields_y']] lessons_meta.loc[lessons_meta['kind'] == 'video', 'extra_fields_y'] = video_loc materias = set([x for x in lessons_meta['subject'].dropna(axis=0)]) lessons_detailed = lessons.groupby('title').sum() lessons_detailed = lessons_detailed.rename({'is_active': 'number_resources', }, axis='columns') lessons_detailed = lessons_detailed.drop(['_morango_dirty_bit'], axis=1) lessons_detailed = pd.merge(lessons_detailed, lessons[['id', 'difficulty', 'subject', 'title']].drop_duplicates(subset='id'), on='title' , how='left') # todo add user sorting # todo remove changed or deleted lessons lessons_meta = lessons_meta[lessons_meta.title_y != 'Segundo grado - Decenas y centenas'] lessons_meta_agg = lessons_meta.drop_duplicates(subset='id_y').groupby('title_y').sum() lessons_detailed = pd.merge(lessons_detailed, lessons_meta_agg, left_on='title', right_on='title_y', how='left') lessons_detailed['Completed'] = lessons_detailed['number_resources'] - lessons_detailed['progress_x'] lessons_detailed['Completed'] = [1 if x == 0 else 0 for x in lessons_detailed['Completed']] # todo add video watch and right exercises to the mix lessons_detailed['video_watch'] = lessons_detailed['time_spent_x'] / lessons_detailed['video_loc'] lessons_detailed['video_watch'] = (lessons_detailed['video_watch'] * 100) / 1.5 localengine = sqlalchemy.create_engine('sqlite:///db.sqlite3') lessons_detailed.to_sql('curr_iter_detailed_lessons', localengine, if_exists='replace') lessons_detailed.to_csv('datasets/lessons_detailed_merged.csv') lessons_completed = lessons_detailed[lessons_detailed.Completed == 1] lessons_completed = [x for x in lessons_completed['title']] # lessons_detailed = pd.merge(lessons_detailed, l) # lessons_detailed.to_csv('lessons_agg.csv') # todo fix sorting by subject # plots import plotly.express as px import plotly.io as pio import plotly.graph_objs as po import plotly fig = plotly.graph_objs.Figure() # Add traces fill_na_df = lessons_detailed.fillna(value=0) fig.add_trace( po.Scatter(x=[str(x) for x in lessons_detailed.title], y=[x for x in fill_na_df.progress_x], name='Materials completed')) fig.add_trace(po.Scatter(x=[str(x) for x in lessons_detailed.title], y=[x for x in fill_na_df.number_resources], name='Number of materials', line=dict(color='Red'))) fig.update_layout(title='Progress on lessons', showlegend=True) plot = plotly.offline.plot(fig, include_plotlyjs=False, output_type='div') try: lesson_difficulty = int(list(lessons_detailed['difficulty'].dropna(axis='rows'))[-1]) + int( request.session['lesson_level']) recommended_lesson = lessons_detailed.loc[lessons_detailed['difficulty'] == str(lesson_difficulty), :] return render(request, 'dashboard.html', {'user': str(request.session['user']), 'materias': materias, 'lessons': lessons_completed, 'plot': plot, 'recommended_lesson': list(recommended_lesson.title)[0]}) except Exception as err: print(err) pass if request.method == 'POST': request.session['lesson'] = request.POST['lesson'] return redirect('/lesson_eval') return render(request, 'dashboard.html', {'user': str(request.session['user']), 'materias': materias, 'lessons': lessons_completed, 'plot': plot, }) def survey(request): if request.method == 'POST': localengine = sqlalchemy.create_engine('sqlite:///db.sqlite3') messages.success(request, 'Tus respuestas fueron guardadas') sql = """ SELECT * FROM facilityuserstable """ db_df = pd.read_sql(sql, localengine) info_dict = {'username': request.session['user'], 'school': request.POST['school'], 'age': request.POST['age'], 'paternal_status': request.POST['paternal_status'], 'study_time': request.POST['study_time'], 'grade_average': request.POST['grade_average'] , 'free_time': request.POST['free_time'], 'job_mother': request.POST['job_mother'] , 'job_father': request.POST['job_father'] , 'extra_activities': request.POST['extra_activities'], 'alcohol': request.POST['alcohol'], 'drugs': request.POST['drugs']} info_df = pd.DataFrame(info_dict, index=[0]) db_df.loc[db_df['username'] == str(request.session['user']), ['survey']] = 1 try: print(db_df['school']) for col in list(info_df.columns): print(col) user = request.session['user'] db_df.index = db_df.username db_df.loc[user, col] = list(info_df[col])[0] db_df = db_df.reset_index(drop=True) print(db_df) print(db_df.columns) db_df = db_df.drop('level_0', axis='columns') db_df.to_sql('facilityuserstable', localengine, if_exists='replace') except Exception as err: print(err) merged_df = pd.merge(db_df, info_df, left_on='username', right_on='username', how='left') print(merged_df) merged_df.to_sql('facilityuserstable', localengine, if_exists='replace') # merged_df.to_csv('merge_from_survey.csv') # todo fix innecesary merging return redirect('/dashboard') return render(request, 'survey.html', {}) def evaluation(request): if request.method == 'POST': localengine = sqlalchemy.create_engine('sqlite:///db.sqlite3') messages.success(request, 'Tus respuestas fueron guardadas') if localengine.dialect.has_table(localengine, "lesson_feedback"): # todo fix for new lessons in curr_iter_detailed_lessons sql = """ SELECT * FROM curr_iter_detailed_lessons """ db_df = pd.read_sql(sql, localengine) sql = """ SELECT * FROM lesson_feedback """ info_df_db =
pd.read_sql(sql, localengine)
pandas.read_sql
import codecs import imageio import matplotlib.pyplot as plt from wordcloud import WordCloud, STOPWORDS import plotly.offline as py import plotly.graph_objs as go import pandas as pd import tweepy import locale import emoji import sys import re import string import os def get_user_tweets(api, username, count=200): tweets = api.user_timeline(username, count=count) texts = [tweet.text for tweet in tweets] return texts def get_mentions_names(tweets2): users=[] usernamesForTwitter = re.findall( r'(^|[^@\w])@(\w{1,15})\b',tweets2) for user in usernamesForTwitter: users.append(user[1]) return users def show_html_table(words): data = [go.Bar( x = words.index.values[:30], y = words.values[:30], marker= dict(colorscale='Jet', color = words.values[:30]), text='ranking' )] layout = go.Layout( title='Word Frequency Ranking' ) fig = go.Figure(data=data, layout=layout) py.plot(fig, filename=username) def show_cloud(listData,typeFormat): a = ' '.join(str(v) for v in listData) wc = WordCloud(background_color="black", max_words=1000, mask=sherlock_mask, stopwords=stopwords) wc.generate(a) filename=typeFormat+'.png' wc.recolor(colormap='PuBu' , random_state=42).to_file(filename) #plt.figure(figsize=(80,80)) #plt.imshow(wc.recolor(colormap='PuBu' , random_state=42),interpolation='bilinear') #plt.axis("off") #plt.show(block=False) def get_analysis(retweets,tweets,mentions): df_retweets =
pd.DataFrame({'retweets': retweets})
pandas.DataFrame
import pandas as pd v_4 = pd.read_csv('50/predictions_dev_queries_50k_normalized_exp.csv') temp = list(v_4['query_id']) v_4['query_id'] = list(v_4['reference_id']) v_4['reference_id'] = temp v_5 = pd.read_csv('ibn/predictions_dev_queries_50k_normalized_exp.csv') temp = list(v_5['query_id']) v_5['query_id'] = list(v_5['reference_id']) v_5['reference_id'] = temp v_6 = pd.read_csv('152/predictions_dev_queries_50k_normalized_exp.csv') temp = list(v_6['query_id']) v_6['query_id'] = list(v_6['reference_id']) v_6['reference_id'] = temp v_4_query = list(v_4['query_id']) v_4_reference = list(v_4['reference_id']) v_4_com = [] for i in range(len(v_4)): v_4_com.append((v_4_query[i],v_4_reference[i])) v_5_query = list(v_5['query_id']) v_5_reference = list(v_5['reference_id']) v_5_com = [] for i in range(len(v_5)): v_5_com.append((v_5_query[i],v_5_reference[i])) v_6_query = list(v_6['query_id']) v_6_reference = list(v_6['reference_id']) v_6_com = [] for i in range(len(v_6)): v_6_com.append((v_6_query[i],v_6_reference[i])) inter_45 = list(set(v_4_com).intersection(set(v_5_com))) inter_46 = list(set(v_4_com).intersection(set(v_6_com))) inter_456 = list(set(inter_45).intersection(set(inter_46))) new_456 = pd.DataFrame() q = [] for i in range(len(inter_456)): q.append(inter_456[i][0]) r = [] for i in range(len(inter_456)): r.append(inter_456[i][1]) new_456['query_id'] = q new_456['reference_id'] = r df_2 = pd.merge(new_456, v_4, on=['query_id','reference_id'], how='inner') df_3 =
pd.merge(new_456, v_5, on=['query_id','reference_id'], how='inner')
pandas.merge
import pandas as pd import numpy as np import lightgbm as lgb import xgboost as xgb from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder from sklearn.model_selection import KFold, RepeatedKFold from scipy import sparse # 显示所有列 pd.set_option('display.max_columns', None) # 显示所有行 pd.set_option('display.max_rows', None) from datetime import datetime # 把一天的时间分段 def hour_cut(x): if 0 <= x < 6: return 0 elif 6 <= x < 8: return 1 elif 8 <= x < 12: return 2 elif 12 <= x < 14: return 3 elif 14 <= x < 18: return 4 elif 18 <= x < 21: return 5 elif 21 <= x < 24: return 6 def birth_split(x): if 1920 <= x <= 1930: return 0 elif 1930 < x <= 1940: return 1 elif 1940 < x <= 1950: return 2 elif 1950 < x <= 1960: return 3 elif 1960 < x <= 1970: return 4 elif 1970 < x <= 1980: return 5 elif 1980 < x <= 1990: return 6 elif 1990 < x <= 2000: return 7 def income_cut(x): if x < 0: return 0 elif 0 <= x < 1200: return 1 elif 1200 < x <= 10000: return 2 elif 10000 < x < 24000: return 3 elif 24000 < x < 40000: return 4 elif 40000 <= x: return 5 def data_process(): # 导入数据 train_abbr = pd.read_csv("../dataset/happiness/happiness_train_abbr.csv", encoding='ISO-8859-1') train = pd.read_csv("../dataset/happiness/happiness_train_complete.csv", encoding='ISO-8859-1') test_abbr = pd.read_csv("../dataset/happiness/happiness_test_abbr.csv", encoding='ISO-8859-1') test = pd.read_csv("../dataset/happiness/happiness_test_complete.csv", encoding='ISO-8859-1') test_sub = pd.read_csv("../dataset/happiness/happiness_submit.csv", encoding='ISO-8859-1') # 查看label分布 y_train_ = train["happiness"] # y_train_.value_counts() y_train_ = y_train_.map(lambda x: 3 if x == -8 else x) y_train_ = y_train_.map(lambda x: x - 1) data = pd.concat([train, test], axis=0, ignore_index=True) # 数据预处理 data['survey_time'] = pd.to_datetime(data['survey_time'], format='%Y-%m-%d %H:%M:%S') data["weekday"] = data["survey_time"].dt.weekday data["year"] = data["survey_time"].dt.year data["quarter"] = data["survey_time"].dt.quarter data["hour"] = data["survey_time"].dt.hour data["month"] = data["survey_time"].dt.month data["hour_cut"] = data["hour"].map(hour_cut) data["survey_age"] = data["year"] - data["birth"] data["happiness"] = data["happiness"].map(lambda x: x - 1) #去掉三个缺失值很多的 data=data.drop(["edu_other"], axis=1) data=data.drop(["happiness"], axis=1) data=data.drop(["survey_time"], axis=1) data["join_party"] = data["join_party"].map(lambda x:0 if pd.isnull(x) else 1) data["birth_s"] = data["birth"].map(birth_split) data["income_cut"] = data["income"].map(income_cut) #填充数据 data["edu_status"]=data["edu_status"].fillna(5) data["edu_yr"]=data["edu_yr"].fillna(-2) data["property_other"]=data["property_other"].map(lambda x:0 if
pd.isnull(x)
pandas.isnull
""" config for drug target challenge. """ import pandas as pd import os import sys import evaluation_metrics_python2 as eval CHALLENGE_SYN_ID = "syn15667962" CHALLENGE_NAME = "IDG-DREAM Drug-Kinase Binding Prediction Challenge" ADMIN_USER_IDS = [3360851] REQUIRED_COLUMNS = [ "Compound_SMILES", "Compound_InchiKeys", "Compound_Name", "UniProt_Id", "Entrez_Gene_Symbol", "DiscoveRx_Gene_Symbol", "pKd_[M]_pred"] CONFIG_DIR = os.path.dirname(os.path.realpath(sys.argv[0])) def validate_func(submission, goldstandard_path): try: sub_df = pd.read_csv(submission.filePath) except Exception as e: error_string = "Error reading in submission file: " + str(e) raise AssertionError(error_string) gs_df = pd.read_csv(goldstandard_path) for col in REQUIRED_COLUMNS: assert col in sub_df.columns, ( "Submission file is missing column: " + col) assert sub_df.shape[0] == sub_df.shape[0], ( "Submission file has missing values.") sub_df["pKd_[M]_pred"] = pd.to_numeric(sub_df["pKd_[M]_pred"], errors='coerce') assert sub_df.shape[0] == sub_df.dropna().shape[0], ( "Submission file has missing values, after converting prediction " + "column to float values.") assert sub_df.shape[0] == gs_df.shape[0], ( "Submission file should have " + str(gs_df.shape[0]) + " predictions") try: combined_df = pd.merge(sub_df, gs_df, how='inner') except Exception as e: error_string = "Error combing submission and gold standard file" raise AssertionError(error_string) left_join_df = pd.merge(sub_df, gs_df, how='left') left_join_na_df = left_join_df[left_join_df.isnull().any(1)] na_row_indeces = left_join_na_df.index.tolist() na_row_numbers = ", ".join([str(i + 2) for i in na_row_indeces]) assert combined_df.shape[0] == gs_df.shape[0], ( "Merge failed due to inconsistent values between submission file and" + " validation file in one or more label columns at rows: " + na_row_numbers) assert combined_df["pKd_[M]_pred"].var() != 0, ( "After merging submission file and gold standard, prediction column" + " has variance of 0.") return(True, "Passed Validation") def score1(submission, goldstandard_path): sub_df =
pd.read_csv(submission.filePath)
pandas.read_csv
import os import locale import codecs import nose import numpy as np from numpy.testing import assert_equal import pandas as pd from pandas import date_range, Index import pandas.util.testing as tm from pandas.tools.util import cartesian_product, to_numeric CURRENT_LOCALE = locale.getlocale() LOCALE_OVERRIDE = os.environ.get('LOCALE_OVERRIDE', None) class TestCartesianProduct(tm.TestCase): def test_simple(self): x, y = list('ABC'), [1, 22] result = cartesian_product([x, y]) expected = [np.array(['A', 'A', 'B', 'B', 'C', 'C']), np.array([1, 22, 1, 22, 1, 22])] assert_equal(result, expected) def test_datetimeindex(self): # regression test for GitHub issue #6439 # make sure that the ordering on datetimeindex is consistent x = date_range('2000-01-01', periods=2) result = [Index(y).day for y in cartesian_product([x, x])] expected = [np.array([1, 1, 2, 2]), np.array([1, 2, 1, 2])] assert_equal(result, expected) class TestLocaleUtils(tm.TestCase): @classmethod def setUpClass(cls): super(TestLocaleUtils, cls).setUpClass() cls.locales = tm.get_locales() if not cls.locales: raise nose.SkipTest("No locales found") tm._skip_if_windows() @classmethod def tearDownClass(cls): super(TestLocaleUtils, cls).tearDownClass() del cls.locales def test_get_locales(self): # all systems should have at least a single locale assert len(tm.get_locales()) > 0 def test_get_locales_prefix(self): if len(self.locales) == 1: raise nose.SkipTest("Only a single locale found, no point in " "trying to test filtering locale prefixes") first_locale = self.locales[0] assert len(tm.get_locales(prefix=first_locale[:2])) > 0 def test_set_locale(self): if len(self.locales) == 1: raise nose.SkipTest("Only a single locale found, no point in " "trying to test setting another locale") if LOCALE_OVERRIDE is not None: lang, enc = LOCALE_OVERRIDE.split('.') else: lang, enc = 'it_CH', 'UTF-8' enc = codecs.lookup(enc).name new_locale = lang, enc if not tm._can_set_locale(new_locale): with tm.assertRaises(locale.Error): with tm.set_locale(new_locale): pass else: with tm.set_locale(new_locale) as normalized_locale: new_lang, new_enc = normalized_locale.split('.') new_enc = codecs.lookup(enc).name normalized_locale = new_lang, new_enc self.assertEqual(normalized_locale, new_locale) current_locale = locale.getlocale() self.assertEqual(current_locale, CURRENT_LOCALE) class TestToNumeric(tm.TestCase): def test_series(self): s = pd.Series(['1', '-3.14', '7']) res = to_numeric(s) expected = pd.Series([1, -3.14, 7]) tm.assert_series_equal(res, expected) s = pd.Series(['1', '-3.14', 7]) res = to_numeric(s) tm.assert_series_equal(res, expected) def test_series_numeric(self): s = pd.Series([1, 3, 4, 5], index=list('ABCD'), name='XXX') res = to_numeric(s) tm.assert_series_equal(res, s) s = pd.Series([1., 3., 4., 5.], index=list('ABCD'), name='XXX') res = to_numeric(s) tm.assert_series_equal(res, s) # bool is regarded as numeric s = pd.Series([True, False, True, True], index=list('ABCD'), name='XXX') res = to_numeric(s) tm.assert_series_equal(res, s) def test_error(self): s = pd.Series([1, -3.14, 'apple']) with tm.assertRaises(ValueError): to_numeric(s, errors='raise') res = to_numeric(s, errors='ignore') expected = pd.Series([1, -3.14, 'apple']) tm.assert_series_equal(res, expected) res = to_numeric(s, errors='coerce') expected = pd.Series([1, -3.14, np.nan]) tm.assert_series_equal(res, expected) def test_error_seen_bool(self): s = pd.Series([True, False, 'apple']) with tm.assertRaises(ValueError): to_numeric(s, errors='raise') res = to_numeric(s, errors='ignore') expected = pd.Series([True, False, 'apple']) tm.assert_series_equal(res, expected) # coerces to float res = to_numeric(s, errors='coerce') expected = pd.Series([1., 0., np.nan]) tm.assert_series_equal(res, expected) def test_list(self): s = ['1', '-3.14', '7'] res = to_numeric(s) expected = np.array([1, -3.14, 7]) tm.assert_numpy_array_equal(res, expected) def test_list_numeric(self): s = [1, 3, 4, 5] res = to_numeric(s) tm.assert_numpy_array_equal(res, np.array(s, dtype=np.int64)) s = [1., 3., 4., 5.] res = to_numeric(s) tm.assert_numpy_array_equal(res, np.array(s)) # bool is regarded as numeric s = [True, False, True, True] res = to_numeric(s) tm.assert_numpy_array_equal(res, np.array(s)) def test_numeric(self): s = pd.Series([1, -3.14, 7], dtype='O') res = to_numeric(s) expected = pd.Series([1, -3.14, 7]) tm.assert_series_equal(res, expected) s = pd.Series([1, -3.14, 7]) res = to_numeric(s) tm.assert_series_equal(res, expected) def test_all_nan(self): s = pd.Series(['a', 'b', 'c']) res = to_numeric(s, errors='coerce') expected = pd.Series([np.nan, np.nan, np.nan]) tm.assert_series_equal(res, expected) def test_type_check(self): # GH 11776 df = pd.DataFrame({'a': [1, -3.14, 7], 'b': ['4', '5', '6']}) with tm.assertRaisesRegexp(TypeError, "1-d array"): to_numeric(df) for errors in ['ignore', 'raise', 'coerce']: with tm.assertRaisesRegexp(TypeError, "1-d array"): to_numeric(df, errors=errors) def test_scalar(self): self.assertEqual(pd.to_numeric(1), 1) self.assertEqual(pd.to_numeric(1.1), 1.1) self.assertEqual(pd.to_numeric('1'), 1) self.assertEqual(pd.to_numeric('1.1'), 1.1) with tm.assertRaises(ValueError): to_numeric('XX', errors='raise') self.assertEqual(to_numeric('XX', errors='ignore'), 'XX') self.assertTrue(np.isnan(to_numeric('XX', errors='coerce'))) def test_numeric_dtypes(self): idx = pd.Index([1, 2, 3], name='xxx') res = pd.to_numeric(idx) tm.assert_index_equal(res, idx) res = pd.to_numeric(pd.Series(idx, name='xxx')) tm.assert_series_equal(res, pd.Series(idx, name='xxx')) res = pd.to_numeric(idx.values) tm.assert_numpy_array_equal(res, idx.values) idx = pd.Index([1., np.nan, 3., np.nan], name='xxx') res = pd.to_numeric(idx) tm.assert_index_equal(res, idx) res = pd.to_numeric(pd.Series(idx, name='xxx')) tm.assert_series_equal(res, pd.Series(idx, name='xxx')) res = pd.to_numeric(idx.values) tm.assert_numpy_array_equal(res, idx.values) def test_str(self): idx = pd.Index(['1', '2', '3'], name='xxx') exp = np.array([1, 2, 3], dtype='int64') res = pd.to_numeric(idx) tm.assert_index_equal(res, pd.Index(exp, name='xxx')) res = pd.to_numeric(pd.Series(idx, name='xxx')) tm.assert_series_equal(res, pd.Series(exp, name='xxx')) res = pd.to_numeric(idx.values) tm.assert_numpy_array_equal(res, exp) idx =
pd.Index(['1.5', '2.7', '3.4'], name='xxx')
pandas.Index
# pylint: disable-msg=E1101,W0612 from datetime import datetime, timedelta import nose import numpy as np import pandas as pd from pandas import (Index, Series, DataFrame, Timestamp, isnull, notnull, bdate_range, date_range, _np_version_under1p7) import pandas.core.common as com from pandas.compat import StringIO, lrange, range, zip, u, OrderedDict, long from pandas import compat, to_timedelta, tslib from pandas.tseries.timedeltas import _coerce_scalar_to_timedelta_type as ct from pandas.util.testing import (assert_series_equal, assert_frame_equal, assert_almost_equal, ensure_clean) import pandas.util.testing as tm def _skip_if_numpy_not_friendly(): # not friendly for < 1.7 if _np_version_under1p7: raise nose.SkipTest("numpy < 1.7") class TestTimedeltas(tm.TestCase): _multiprocess_can_split_ = True def setUp(self): pass def test_numeric_conversions(self): _skip_if_numpy_not_friendly() self.assertEqual(ct(0), np.timedelta64(0,'ns')) self.assertEqual(ct(10), np.timedelta64(10,'ns')) self.assertEqual(ct(10,unit='ns'), np.timedelta64(10,'ns').astype('m8[ns]')) self.assertEqual(ct(10,unit='us'), np.timedelta64(10,'us').astype('m8[ns]')) self.assertEqual(ct(10,unit='ms'), np.timedelta64(10,'ms').astype('m8[ns]')) self.assertEqual(ct(10,unit='s'), np.timedelta64(10,'s').astype('m8[ns]')) self.assertEqual(ct(10,unit='d'), np.timedelta64(10,'D').astype('m8[ns]')) def test_timedelta_conversions(self): _skip_if_numpy_not_friendly() self.assertEqual(ct(timedelta(seconds=1)), np.timedelta64(1,'s').astype('m8[ns]')) self.assertEqual(ct(timedelta(microseconds=1)), np.timedelta64(1,'us').astype('m8[ns]')) self.assertEqual(ct(timedelta(days=1)), np.timedelta64(1,'D').astype('m8[ns]')) def test_short_format_converters(self): _skip_if_numpy_not_friendly() def conv(v): return v.astype('m8[ns]') self.assertEqual(ct('10'), np.timedelta64(10,'ns')) self.assertEqual(ct('10ns'), np.timedelta64(10,'ns')) self.assertEqual(ct('100'), np.timedelta64(100,'ns')) self.assertEqual(ct('100ns'), np.timedelta64(100,'ns')) self.assertEqual(ct('1000'), np.timedelta64(1000,'ns')) self.assertEqual(ct('1000ns'), np.timedelta64(1000,'ns')) self.assertEqual(ct('1000NS'), np.timedelta64(1000,'ns')) self.assertEqual(ct('10us'), np.timedelta64(10000,'ns')) self.assertEqual(ct('100us'), np.timedelta64(100000,'ns')) self.assertEqual(ct('1000us'), np.timedelta64(1000000,'ns')) self.assertEqual(ct('1000Us'), np.timedelta64(1000000,'ns')) self.assertEqual(ct('1000uS'), np.timedelta64(1000000,'ns')) self.assertEqual(ct('1ms'), np.timedelta64(1000000,'ns')) self.assertEqual(ct('10ms'), np.timedelta64(10000000,'ns')) self.assertEqual(ct('100ms'), np.timedelta64(100000000,'ns')) self.assertEqual(ct('1000ms'), np.timedelta64(1000000000,'ns')) self.assertEqual(ct('-1s'), -np.timedelta64(1000000000,'ns')) self.assertEqual(ct('1s'), np.timedelta64(1000000000,'ns')) self.assertEqual(ct('10s'), np.timedelta64(10000000000,'ns')) self.assertEqual(ct('100s'), np.timedelta64(100000000000,'ns')) self.assertEqual(ct('1000s'), np.timedelta64(1000000000000,'ns')) self.assertEqual(ct('1d'), conv(np.timedelta64(1,'D'))) self.assertEqual(ct('-1d'), -conv(np.timedelta64(1,'D'))) self.assertEqual(ct('1D'), conv(np.timedelta64(1,'D'))) self.assertEqual(ct('10D'), conv(np.timedelta64(10,'D'))) self.assertEqual(ct('100D'), conv(np.timedelta64(100,'D'))) self.assertEqual(ct('1000D'), conv(np.timedelta64(1000,'D'))) self.assertEqual(ct('10000D'), conv(np.timedelta64(10000,'D'))) # space self.assertEqual(ct(' 10000D '), conv(np.timedelta64(10000,'D'))) self.assertEqual(ct(' - 10000D '), -conv(np.timedelta64(10000,'D'))) # invalid self.assertRaises(ValueError, ct, '1foo') self.assertRaises(ValueError, ct, 'foo') def test_full_format_converters(self): _skip_if_numpy_not_friendly() def conv(v): return v.astype('m8[ns]') d1 = np.timedelta64(1,'D') self.assertEqual(ct('1days'), conv(d1)) self.assertEqual(ct('1days,'), conv(d1)) self.assertEqual(ct('- 1days,'), -conv(d1)) self.assertEqual(ct('00:00:01'), conv(np.timedelta64(1,'s'))) self.assertEqual(ct('06:00:01'), conv(np.timedelta64(6*3600+1,'s'))) self.assertEqual(ct('06:00:01.0'), conv(np.timedelta64(6*3600+1,'s'))) self.assertEqual(ct('06:00:01.01'), conv(np.timedelta64(1000*(6*3600+1)+10,'ms'))) self.assertEqual(ct('- 1days, 00:00:01'), -conv(d1+np.timedelta64(1,'s'))) self.assertEqual(ct('1days, 06:00:01'), conv(d1+np.timedelta64(6*3600+1,'s'))) self.assertEqual(ct('1days, 06:00:01.01'), conv(d1+np.timedelta64(1000*(6*3600+1)+10,'ms'))) # invalid self.assertRaises(ValueError, ct, '- 1days, 00') def test_nat_converters(self): _skip_if_numpy_not_friendly() self.assertEqual(to_timedelta('nat',box=False), tslib.iNaT) self.assertEqual(to_timedelta('nan',box=False), tslib.iNaT) def test_to_timedelta(self): _skip_if_numpy_not_friendly() def conv(v): return v.astype('m8[ns]') d1 = np.timedelta64(1,'D') self.assertEqual(to_timedelta('1 days 06:05:01.00003',box=False), conv(d1+np.timedelta64(6*3600+5*60+1,'s')+np.timedelta64(30,'us'))) self.assertEqual(to_timedelta('15.5us',box=False), conv(np.timedelta64(15500,'ns'))) # empty string result = to_timedelta('',box=False) self.assertEqual(result, tslib.iNaT) result = to_timedelta(['', '']) self.assert_(isnull(result).all()) # pass thru result = to_timedelta(np.array([np.timedelta64(1,'s')])) expected = np.array([np.timedelta64(1,'s')]) tm.assert_almost_equal(result,expected) # ints result = np.timedelta64(0,'ns') expected = to_timedelta(0,box=False) self.assertEqual(result, expected) # Series expected = Series([timedelta(days=1), timedelta(days=1, seconds=1)]) result = to_timedelta(Series(['1d','1days 00:00:01'])) tm.assert_series_equal(result, expected) # with units result = Series([ np.timedelta64(0,'ns'), np.timedelta64(10,'s').astype('m8[ns]') ],dtype='m8[ns]') expected = to_timedelta([0,10],unit='s') tm.assert_series_equal(result, expected) # single element conversion v = timedelta(seconds=1) result = to_timedelta(v,box=False) expected = np.timedelta64(timedelta(seconds=1)) self.assertEqual(result, expected) v = np.timedelta64(timedelta(seconds=1)) result = to_timedelta(v,box=False) expected = np.timedelta64(timedelta(seconds=1)) self.assertEqual(result, expected) def test_to_timedelta_via_apply(self): _skip_if_numpy_not_friendly() # GH 5458 expected = Series([np.timedelta64(1,'s')]) result = Series(['00:00:01']).apply(to_timedelta) tm.assert_series_equal(result, expected) result = Series([
to_timedelta('00:00:01')
pandas.to_timedelta
import pandas as pd import requests import dropbox from bs4 import BeautifulSoup from tqdm import tqdm from datetime import datetime import re from datetime import date from os.path import join DATADIR = 'data' def get_word_parenthesis(s: str) -> str: return s[s.find("(") + 1:s.find(")")] def get_features(url: str): page = requests.get(url) my_soup = BeautifulSoup(page.content, 'html.parser') likes = get_likes(my_soup) symbol = get_symbol(my_soup) price = get_price(my_soup) market_cap = get_market_cap(my_soup) volume_cap = get_volume_cap(my_soup) return symbol, price, likes, market_cap, volume_cap # print(f'likes: {likes}, symbol: {symbol}, price: {price}, market_cap: {market_cap}, volume_cap: {volume_cap}') # return my_soup def get_price(my_soup: BeautifulSoup) -> float: try: values = my_soup.find_all(class_="no-wrap") price = float(values[0].text.replace(',', '.').replace('$', '')) except: price = -1 return price def get_market_cap(my_soup: BeautifulSoup) -> int: try: values = my_soup.find_all(class_="no-wrap") market_cap = int(values[1].text.replace('.', '').replace('$', '')) except: market_cap = -1 return market_cap def get_volume_cap(my_soup: BeautifulSoup) -> float: try: values = my_soup.find_all(class_="no-wrap") volume_cap = int(values[2].text.replace('.', '').replace('$', '')) except: volume_cap = -1 return volume_cap def get_likes(my_soup: BeautifulSoup) -> int: try: # page = requests.get(url) # my_soup = BeautifulSoup(page.content, 'html.parser') txt = my_soup.find_all('span', 'ml-1')[-1].text rgx = re.search("\d*\.\d*", txt) likes = int(rgx.group(0).replace('.', '')) except: likes = -1 return likes def get_symbol(my_soup: BeautifulSoup) -> str: try: txt = my_soup.find(class_="mr-md-3 mx-2 mb-md-0 text-3xl font-semibold").text symbol = get_word_parenthesis(txt) except: symbol = "UNK" return symbol def get_links(url: str) -> pd.DataFrame: # Get Soup response = requests.get(URL) soup = BeautifulSoup(response.text, 'html.parser') # Get all links of table table = soup.find('table') links = [] for tr in table.findAll("tr"): trs = tr.findAll("td") for each in trs: try: link = each.find('a')['href'] links.append(link) except: pass # Get DataFrame with links df = pd.DataFrame(['https://www.coingecko.com' + link for link in links]).rename(columns={0: 'link'}) # Get only useful links df = df.iloc[::3] # Reset index df.reset_index(drop=True) return df class TransferData: def __init__(self, access_token): self.access_token = access_token def upload_file(self, file_from, file_to): """upload a file to Dropbox using API v2 """ dbx = dropbox.Dropbox(self.access_token) with open(file_from, 'rb') as f: dbx.files_upload(f.read(), file_to, mode=dropbox.files.WriteMode.overwrite) TOKEN = '<KEY>3DSKuBpmh13w8JtnJu2jCm85xPSIeu6nH4s ' if __name__ == "__main__": today_date = date.today().strftime("%y-%m-%d-") + '.csv' FILENAME = join(DATADIR, today_date) transferData = TransferData(TOKEN) tqdm.pandas() URL = 'https://www.coingecko.com/es/monedas/all?utf8=%E2%9C%93&filter_market_cap=&filter_24h_volume=&filter_price' \ '=&filter_24h_change=&filter_category=&filter_market=Binance&filter_asset_platform=&filter_hashing_algorithm' \ '=&sort_by=change30d&commit=Search' # Get links df = get_links(URL) df.drop_duplicates(inplace=True) try: df_crypto = pd.read_csv(FILENAME) except: df_crypto =
pd.DataFrame()
pandas.DataFrame
from sklearn.neighbors import KNeighborsRegressor from sklearn.linear_model import Ridge from sklearn.svm import SVR from sklearn.model_selection import cross_val_predict from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error from sklearn.preprocessing import scale from math import sqrt import numpy as np import pandas as pd # some defaults k = 1 a = 1 g = 0.1 c = 1 CV = 5 n_trials = 10 nn = KNeighborsRegressor(n_neighbors=k) rr = Ridge(alpha=a) svr = SVR(gamma=g, C=c) def pred_errs(trainX, trainY, testX, testY, alg): """ Document me """ mape_sum = [0, 0, 0] rmse_sum = [0, 0, 0] mae_sum = [0, 0, 0] for n in range(0, n_trials): if alg == nn: nn.fit(trainX, trainY) train_pred = nn.predict(trainX) test_pred = nn.predict(testX) cv_pred = cross_val_predict(nn, trainX, trainY, cv = CV) elif alg == rr: rr.fit(trainX, trainY) train_pred = rr.predict(trainX) test_pred = rr.predict(testX) cv_pred = cross_val_predict(rr, trainX, trainY, cv = CV) else: svr.fit(trainX, trainY) train_pred = svr.predict(trainX) test_pred = svr.predict(testX) cv_pred = cross_val_predict(svr, trainX, trainY, cv = CV) # negative errors train_mape = -1 * mean_absolute_percentage_error(trainY, train_pred) test_mape = -1 * mean_absolute_percentage_error(testY, test_pred) cv_mape = -1 * mean_absolute_percentage_error(trainY, cv_pred) train_rmse = -1 * sqrt(mean_squared_error(trainY, train_pred)) test_rmse = -1 * sqrt(mean_squared_error(testY, test_pred)) cv_rmse = -1 * sqrt(mean_squared_error(trainY, cv_pred)) train_mae = -1 * mean_absolute_error(trainY, train_pred) test_mae = -1 * mean_absolute_error(testY, test_pred) cv_mae = -1 * mean_absolute_error(trainY, cv_pred) #maths per = (train_mape, test_mape, cv_mape) rms = (train_rmse, test_rmse, cv_rmse) mae = (train_mae, test_mae, cv_mae) mape_sum = [sum(x) for x in zip(per, mape_sum)] rmse_sum = [sum(x) for x in zip(rms, rmse_sum)] mae_sum = [sum(x) for x in zip(mae, mae_sum)] mape = [x / n_trials for x in mape_sum] rmse = [x / n_trials for x in rmse_sum] mae = [x / n_trials for x in mae_sum] return mape, rmse, mae def m_reduc(m, train_set): """ I document. """ # unsplit train = pd.DataFrame(train_set.nuc_concs) train['burnup'] = pd.Series(train_set.burnup, index=train.index) reduc = train.sample(frac=m) # resplit trainX = reduc.iloc[:, 0:-1] trainY = reduc.iloc[:, -1] return trainX, trainY def mean_absolute_percentage_error(true, pred): """ Given 2 vectors of values, true and pred, calculate the MAP error """ mape = np.mean(np.abs((true - pred) / true)) * 100 return mape def add_error(percent_err, df): """ Given a dataframe of nuclide vectors, add error to each element in each nuclide vector that has a random value within the range [1-err, 1+err] Parameters ---------- percent_err : a float indicating the maximum error that can be added to the nuclide vectors df : dataframe of only nuclide concentrations Returns ------- df_err : dataframe with nuclide concentrations altered by some error """ x = df.shape[0] y = df.shape[1] err = percent_err / 100.0 low = 1 - err high = 1 + err errs = np.random.uniform(low, high, (x, y)) df_err = df * errs df_err_scaled = scale(df_err) return df_err def random_error(train, test): """ Given training and testing data, this script runs some ML algorithms to predict burnup in the face of reduced information Parameters ---------- train : group of dataframes that include training instances and the labels test : group of dataframes that has the testing instances and the labels Returns ------- burnup : tuple of different error metrics for training, testing, and cross validation errors for all three algorithms """ mape_cols = ['TrainNegPercent', 'TestNegPercent', 'CVNegPercent'] rmse_cols = ['TrainNegRMSErr', 'TestNegRMSErr', 'CVNegRMSErr'] mae_cols = ['TrainNegMAErr', 'TestNegMAErr', 'CVNegMAErr'] trainX = train.nuc_concs trainY = train.burnup testX = test.nuc_concs testY = test.burnup #err_percent = np.arange(0, 9.25, 0.25) err_percent = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.25, 2.5, 2.75, 3, 3.25, 3.5, 3.75, 4, 4.25, 4.5, 4.75, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9] for alg in (nn, rr, svr): map_err = [] rms_err = [] ma_err = [] for err in err_percent: trainX = add_error(err, trainX) # *_err format for each err type is [train, test, cv] mape, rmse, mae = pred_errs(trainX, trainY, testX, testY, alg) map_err.append(mape) rms_err.append(rmse) ma_err.append(mae) mape = pd.DataFrame(map_err, columns=mape_cols, index=err_percent) rmse =
pd.DataFrame(rms_err, columns=rmse_cols, index=err_percent)
pandas.DataFrame
# pylint: disable=E1101 from datetime import datetime, timedelta from pandas.compat import range, lrange, zip, product import numpy as np from pandas import Series, TimeSeries, DataFrame, Panel, isnull, notnull, Timestamp from pandas.tseries.index import date_range from pandas.tseries.offsets import Minute, BDay from pandas.tseries.period import period_range, PeriodIndex, Period from pandas.tseries.resample import DatetimeIndex, TimeGrouper import pandas.tseries.offsets as offsets import pandas as pd import unittest import nose from pandas.util.testing import (assert_series_equal, assert_almost_equal, assert_frame_equal) import pandas.util.testing as tm bday = BDay() def _skip_if_no_pytz(): try: import pytz except ImportError: raise nose.SkipTest class TestResample(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): dti = DatetimeIndex(start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq='Min') self.series = Series(np.random.rand(len(dti)), dti) def test_custom_grouper(self): dti = DatetimeIndex(freq='Min', start=datetime(2005, 1, 1), end=datetime(2005, 1, 10)) s = Series(np.array([1] * len(dti)), index=dti, dtype='int64') b = TimeGrouper(Minute(5)) g = s.groupby(b) # check all cython functions work funcs = ['add', 'mean', 'prod', 'ohlc', 'min', 'max', 'var'] for f in funcs: g._cython_agg_general(f) b = TimeGrouper(Minute(5), closed='right', label='right') g = s.groupby(b) # check all cython functions work funcs = ['add', 'mean', 'prod', 'ohlc', 'min', 'max', 'var'] for f in funcs: g._cython_agg_general(f) self.assertEquals(g.ngroups, 2593) self.assert_(notnull(g.mean()).all()) # construct expected val arr = [1] + [5] * 2592 idx = dti[0:-1:5] idx = idx.append(dti[-1:]) expect = Series(arr, index=idx) # GH2763 - return in put dtype if we can result = g.agg(np.sum) assert_series_equal(result, expect) df = DataFrame(np.random.rand(len(dti), 10), index=dti, dtype='float64') r = df.groupby(b).agg(np.sum) self.assertEquals(len(r.columns), 10) self.assertEquals(len(r.index), 2593) def test_resample_basic(self): rng = date_range('1/1/2000 00:00:00', '1/1/2000 00:13:00', freq='min', name='index') s = Series(np.random.randn(14), index=rng) result = s.resample('5min', how='mean', closed='right', label='right') expected = Series([s[0], s[1:6].mean(), s[6:11].mean(), s[11:].mean()], index=date_range('1/1/2000', periods=4, freq='5min')) assert_series_equal(result, expected) self.assert_(result.index.name == 'index') result = s.resample('5min', how='mean', closed='left', label='right') expected = Series([s[:5].mean(), s[5:10].mean(), s[10:].mean()], index=date_range('1/1/2000 00:05', periods=3, freq='5min')) assert_series_equal(result, expected) s = self.series result = s.resample('5Min', how='last') grouper = TimeGrouper(Minute(5), closed='left', label='left') expect = s.groupby(grouper).agg(lambda x: x[-1]) assert_series_equal(result, expect) def test_resample_basic_from_daily(self): # from daily dti = DatetimeIndex( start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq='D', name='index') s = Series(np.random.rand(len(dti)), dti) # to weekly result = s.resample('w-sun', how='last') self.assertEquals(len(result), 3) self.assert_((result.index.dayofweek == [6, 6, 6]).all()) self.assertEquals(result.irow(0), s['1/2/2005']) self.assertEquals(result.irow(1), s['1/9/2005']) self.assertEquals(result.irow(2), s.irow(-1)) result = s.resample('W-MON', how='last') self.assertEquals(len(result), 2) self.assert_((result.index.dayofweek == [0, 0]).all()) self.assertEquals(result.irow(0), s['1/3/2005']) self.assertEquals(result.irow(1), s['1/10/2005']) result = s.resample('W-TUE', how='last') self.assertEquals(len(result), 2) self.assert_((result.index.dayofweek == [1, 1]).all()) self.assertEquals(result.irow(0), s['1/4/2005']) self.assertEquals(result.irow(1), s['1/10/2005']) result = s.resample('W-WED', how='last') self.assertEquals(len(result), 2) self.assert_((result.index.dayofweek == [2, 2]).all()) self.assertEquals(result.irow(0), s['1/5/2005']) self.assertEquals(result.irow(1), s['1/10/2005']) result = s.resample('W-THU', how='last') self.assertEquals(len(result), 2) self.assert_((result.index.dayofweek == [3, 3]).all()) self.assertEquals(result.irow(0), s['1/6/2005']) self.assertEquals(result.irow(1), s['1/10/2005']) result = s.resample('W-FRI', how='last') self.assertEquals(len(result), 2) self.assert_((result.index.dayofweek == [4, 4]).all()) self.assertEquals(result.irow(0), s['1/7/2005']) self.assertEquals(result.irow(1), s['1/10/2005']) # to biz day result = s.resample('B', how='last') self.assertEquals(len(result), 7) self.assert_((result.index.dayofweek == [4, 0, 1, 2, 3, 4, 0]).all()) self.assertEquals(result.irow(0), s['1/2/2005']) self.assertEquals(result.irow(1), s['1/3/2005']) self.assertEquals(result.irow(5), s['1/9/2005']) self.assert_(result.index.name == 'index') def test_resample_frame_basic(self): df = tm.makeTimeDataFrame() b = TimeGrouper('M') g = df.groupby(b) # check all cython functions work funcs = ['add', 'mean', 'prod', 'min', 'max', 'var'] for f in funcs: g._cython_agg_general(f) result = df.resample('A') assert_series_equal(result['A'], df['A'].resample('A')) result = df.resample('M') assert_series_equal(result['A'], df['A'].resample('M')) df.resample('M', kind='period') df.resample('W-WED', kind='period') def test_resample_loffset(self): rng = date_range('1/1/2000 00:00:00', '1/1/2000 00:13:00', freq='min') s = Series(np.random.randn(14), index=rng) result = s.resample('5min', how='mean', closed='right', label='right', loffset=timedelta(minutes=1)) idx = date_range('1/1/2000', periods=4, freq='5min') expected = Series([s[0], s[1:6].mean(), s[6:11].mean(), s[11:].mean()], index=idx + timedelta(minutes=1)) assert_series_equal(result, expected) expected = s.resample( '5min', how='mean', closed='right', label='right', loffset='1min') assert_series_equal(result, expected) expected = s.resample( '5min', how='mean', closed='right', label='right', loffset=Minute(1)) assert_series_equal(result, expected) self.assert_(result.index.freq == Minute(5)) # from daily dti = DatetimeIndex( start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq='D') ser = Series(np.random.rand(len(dti)), dti) # to weekly result = ser.resample('w-sun', how='last') expected = ser.resample('w-sun', how='last', loffset=-bday) self.assertEqual(result.index[0] - bday, expected.index[0]) def test_resample_upsample(self): # from daily dti = DatetimeIndex( start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq='D', name='index') s = Series(np.random.rand(len(dti)), dti) # to minutely, by padding result = s.resample('Min', fill_method='pad') self.assertEquals(len(result), 12961) self.assertEquals(result[0], s[0]) self.assertEquals(result[-1], s[-1]) self.assert_(result.index.name == 'index') def test_upsample_with_limit(self): rng =
date_range('1/1/2000', periods=3, freq='5t')
pandas.tseries.index.date_range
import csv import pandas as pd import threading from helpers.movie_helper import get_one_movie_resource_pt, get_one_movie_resource_en def merge_links_movies(): # First we merge links and movies to have access to external TMDB API links = pd.read_csv("../movie_data/links.csv", dtype=str) movies = pd.read_csv("../movie_data/movies.csv", dtype=str) result = pd.merge(links, movies, how="inner") # There are 107 missing tmdbIds and we need to drop those movies na = result[result['tmdbId'].isna()] na[['movieId']].to_csv("../movie_data/remove_by_movieId.csv", index=False) result = result.dropna() # We are dropping 5061 movies with genre '(no genres listed)' no_genres_index = result[result['genres'] == '(no genres listed)'].index no_genre = result[result['genres'] == '(no genres listed)'] not_found = pd.read_csv("../movie_data/movies_not_found.csv", dtype=str) removed = pd.concat([no_genre[['tmdbId']], not_found], ignore_index=True) removed.to_csv("../movie_data/remove_by_tmdbId.csv", index=False) result.drop(no_genres_index, inplace=True) result.to_csv("../movie_data/dataset.csv", index=False) def check_missing_movies(): complete = pd.read_csv("../movie_data/movie_details_complete.csv", dtype=str, lineterminator='\n')[['tmdbId']] dataset = pd.read_csv("../movie_data/movie_details_1.csv", dtype=str)[['tmdbId']] # not_found = pd.read_csv("../movie_data/movies_not_found.csv", dtype=str) missing1 = pd.concat([dataset, complete]).drop_duplicates(keep=False) # missing2 = pd.concat([not_found, missing1]).drop_duplicates(keep=False) missing1.to_csv("../movie_data/missing_on_count.csv", index=False) def merge_detail_files(): files = [] for i in range(1, 59): file = pd.read_csv(f"../movie_details/movie_details_{i}.csv", dtype=str) files.append(file) missing = pd.read_csv(f"../movie_details/movie_details_missing.csv", dtype=str) files.append(missing) result = pd.concat(files, ignore_index=True) # result[['movieId', 'tmdbId']].to_csv("../movie_data/movie_details_tmdbids.csv", index=False) result.to_csv("../movie_data/movie_details.csv", index=False) def get_missing_movies(): details = pd.read_csv(f"../movie_data/movie_details_tmdbids.csv", dtype=str) dataset = pd.read_csv("../movie_data/dataset.csv", dtype=str) movie_details = details[['movieId', 'tmdbId']] all_movies = dataset[['movieId', 'tmdbId']] missing =
pd.concat([all_movies, movie_details])
pandas.concat
""" Quantilization functions and related stuff """ from functools import partial import numpy as np from pandas._libs.lib import infer_dtype from pandas.core.dtypes.common import ( ensure_int64, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_integer, is_scalar, is_timedelta64_dtype) from pandas.core.dtypes.missing import isna from pandas import ( Categorical, Index, Interval, IntervalIndex, Series, Timedelta, Timestamp, to_datetime, to_timedelta) import pandas.core.algorithms as algos import pandas.core.nanops as nanops def cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates='raise'): """ Bin values into discrete intervals. Use `cut` when you need to segment and sort data values into bins. This function is also useful for going from a continuous variable to a categorical variable. For example, `cut` could convert ages to groups of age ranges. Supports binning into an equal number of bins, or a pre-specified array of bins. Parameters ---------- x : array-like The input array to be binned. Must be 1-dimensional. bins : int, sequence of scalars, or pandas.IntervalIndex The criteria to bin by. * int : Defines the number of equal-width bins in the range of `x`. The range of `x` is extended by .1% on each side to include the minimum and maximum values of `x`. * sequence of scalars : Defines the bin edges allowing for non-uniform width. No extension of the range of `x` is done. * IntervalIndex : Defines the exact bins to be used. right : bool, default True Indicates whether `bins` includes the rightmost edge or not. If ``right == True`` (the default), then the `bins` ``[1, 2, 3, 4]`` indicate (1,2], (2,3], (3,4]. This argument is ignored when `bins` is an IntervalIndex. labels : array or bool, optional Specifies the labels for the returned bins. Must be the same length as the resulting bins. If False, returns only integer indicators of the bins. This affects the type of the output container (see below). This argument is ignored when `bins` is an IntervalIndex. retbins : bool, default False Whether to return the bins or not. Useful when bins is provided as a scalar. precision : int, default 3 The precision at which to store and display the bins labels. include_lowest : bool, default False Whether the first interval should be left-inclusive or not. duplicates : {default 'raise', 'drop'}, optional If bin edges are not unique, raise ValueError or drop non-uniques. .. versionadded:: 0.23.0 Returns ------- out : pandas.Categorical, Series, or ndarray An array-like object representing the respective bin for each value of `x`. The type depends on the value of `labels`. * True (default) : returns a Series for Series `x` or a pandas.Categorical for all other inputs. The values stored within are Interval dtype. * sequence of scalars : returns a Series for Series `x` or a pandas.Categorical for all other inputs. The values stored within are whatever the type in the sequence is. * False : returns an ndarray of integers. bins : numpy.ndarray or IntervalIndex. The computed or specified bins. Only returned when `retbins=True`. For scalar or sequence `bins`, this is an ndarray with the computed bins. If set `duplicates=drop`, `bins` will drop non-unique bin. For an IntervalIndex `bins`, this is equal to `bins`. See Also -------- qcut : Discretize variable into equal-sized buckets based on rank or based on sample quantiles. pandas.Categorical : Array type for storing data that come from a fixed set of values. Series : One-dimensional array with axis labels (including time series). pandas.IntervalIndex : Immutable Index implementing an ordered, sliceable set. Notes ----- Any NA values will be NA in the result. Out of bounds values will be NA in the resulting Series or pandas.Categorical object. Examples -------- Discretize into three equal-sized bins. >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3) ... # doctest: +ELLIPSIS [(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ... Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ... >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True) ... # doctest: +ELLIPSIS ([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ... Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ... array([0.994, 3. , 5. , 7. ])) Discovers the same bins, but assign them specific labels. Notice that the returned Categorical's categories are `labels` and is ordered. >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), ... 3, labels=["bad", "medium", "good"]) [bad, good, medium, medium, good, bad] Categories (3, object): [bad < medium < good] ``labels=False`` implies you just want the bins back. >>> pd.cut([0, 1, 1, 2], bins=4, labels=False) array([0, 1, 1, 3]) Passing a Series as an input returns a Series with categorical dtype: >>> s = pd.Series(np.array([2, 4, 6, 8, 10]), ... index=['a', 'b', 'c', 'd', 'e']) >>> pd.cut(s, 3) ... # doctest: +ELLIPSIS a (1.992, 4.667] b (1.992, 4.667] c (4.667, 7.333] d (7.333, 10.0] e (7.333, 10.0] dtype: category Categories (3, interval[float64]): [(1.992, 4.667] < (4.667, ... Passing a Series as an input returns a Series with mapping value. It is used to map numerically to intervals based on bins. >>> s = pd.Series(np.array([2, 4, 6, 8, 10]), ... index=['a', 'b', 'c', 'd', 'e']) >>> pd.cut(s, [0, 2, 4, 6, 8, 10], labels=False, retbins=True, right=False) ... # doctest: +ELLIPSIS (a 0.0 b 1.0 c 2.0 d 3.0 e 4.0 dtype: float64, array([0, 2, 4, 6, 8])) Use `drop` optional when bins is not unique >>> pd.cut(s, [0, 2, 4, 6, 10, 10], labels=False, retbins=True, ... right=False, duplicates='drop') ... # doctest: +ELLIPSIS (a 0.0 b 1.0 c 2.0 d 3.0 e 3.0 dtype: float64, array([0, 2, 4, 6, 8])) Passing an IntervalIndex for `bins` results in those categories exactly. Notice that values not covered by the IntervalIndex are set to NaN. 0 is to the left of the first bin (which is closed on the right), and 1.5 falls between two bins. >>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)]) >>> pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins) [NaN, (0, 1], NaN, (2, 3], (4, 5]] Categories (3, interval[int64]): [(0, 1] < (2, 3] < (4, 5]] """ # NOTE: this binning code is changed a bit from histogram for var(x) == 0 # for handling the cut for datetime and timedelta objects x_is_series, series_index, name, x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) if not np.iterable(bins): if is_scalar(bins) and bins < 1: raise ValueError("`bins` should be a positive integer.") try: # for array-like sz = x.size except AttributeError: x = np.asarray(x) sz = x.size if sz == 0: raise ValueError('Cannot cut empty array') rng = (nanops.nanmin(x), nanops.nanmax(x)) mn, mx = [mi + 0.0 for mi in rng] if mn == mx: # adjust end points before binning mn -= .001 * abs(mn) if mn != 0 else .001 mx += .001 * abs(mx) if mx != 0 else .001 bins = np.linspace(mn, mx, bins + 1, endpoint=True) else: # adjust end points after binning bins = np.linspace(mn, mx, bins + 1, endpoint=True) adj = (mx - mn) * 0.001 # 0.1% of the range if right: bins[0] -= adj else: bins[-1] += adj elif isinstance(bins, IntervalIndex): pass else: bins = np.asarray(bins) bins = _convert_bin_to_numeric_type(bins, dtype) if (np.diff(bins) < 0).any(): raise ValueError('bins must increase monotonically.') fac, bins = _bins_to_cuts(x, bins, right=right, labels=labels, precision=precision, include_lowest=include_lowest, dtype=dtype, duplicates=duplicates) return _postprocess_for_cut(fac, bins, retbins, x_is_series, series_index, name, dtype) def qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'): """ Quantile-based discretization function. Discretize variable into equal-sized buckets based on rank or based on sample quantiles. For example 1000 values for 10 quantiles would produce a Categorical object indicating quantile membership for each data point. Parameters ---------- x : 1d ndarray or Series q : integer or array of quantiles Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles labels : array or boolean, default None Used as labels for the resulting bins. Must be of the same length as the resulting bins. If False, return only integer indicators of the bins. retbins : bool, optional Whether to return the (bins, labels) or not. Can be useful if bins is given as a scalar. precision : int, optional The precision at which to store and display the bins labels duplicates : {default 'raise', 'drop'}, optional If bin edges are not unique, raise ValueError or drop non-uniques. .. versionadded:: 0.20.0 Returns ------- out : Categorical or Series or array of integers if labels is False The return type (Categorical or Series) depends on the input: a Series of type category if input is a Series else Categorical. Bins are represented as categories when categorical data is returned. bins : ndarray of floats Returned only if `retbins` is True. Notes ----- Out of bounds values will be NA in the resulting Categorical object Examples -------- >>> pd.qcut(range(5), 4) ... # doctest: +ELLIPSIS [(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]] Categories (4, interval[float64]): [(-0.001, 1.0] < (1.0, 2.0] ... >>> pd.qcut(range(5), 3, labels=["good", "medium", "bad"]) ... # doctest: +SKIP [good, good, medium, bad, bad] Categories (3, object): [good < medium < bad] >>> pd.qcut(range(5), 4, labels=False) array([0, 0, 1, 2, 3]) """ x_is_series, series_index, name, x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) if is_integer(q): quantiles = np.linspace(0, 1, q + 1) else: quantiles = q bins = algos.quantile(x, quantiles) fac, bins = _bins_to_cuts(x, bins, labels=labels, precision=precision, include_lowest=True, dtype=dtype, duplicates=duplicates) return _postprocess_for_cut(fac, bins, retbins, x_is_series, series_index, name, dtype) def _bins_to_cuts(x, bins, right=True, labels=None, precision=3, include_lowest=False, dtype=None, duplicates='raise'): if duplicates not in ['raise', 'drop']: raise ValueError("invalid value for 'duplicates' parameter, " "valid options are: raise, drop") if isinstance(bins, IntervalIndex): # we have a fast-path here ids = bins.get_indexer(x) result = algos.take_nd(bins, ids) result = Categorical(result, categories=bins, ordered=True) return result, bins unique_bins = algos.unique(bins) if len(unique_bins) < len(bins) and len(bins) != 2: if duplicates == 'raise': raise ValueError("Bin edges must be unique: {bins!r}.\nYou " "can drop duplicate edges by setting " "the 'duplicates' kwarg".format(bins=bins)) else: bins = unique_bins side = 'left' if right else 'right' ids = ensure_int64(bins.searchsorted(x, side=side)) if include_lowest: ids[x == bins[0]] = 1 na_mask = isna(x) | (ids == len(bins)) | (ids == 0) has_nas = na_mask.any() if labels is not False: if labels is None: labels = _format_labels(bins, precision, right=right, include_lowest=include_lowest, dtype=dtype) else: if len(labels) != len(bins) - 1: raise ValueError('Bin labels must be one fewer than ' 'the number of bin edges') if not is_categorical_dtype(labels): labels = Categorical(labels, categories=labels, ordered=True) np.putmask(ids, na_mask, 0) result = algos.take_nd(labels, ids - 1) else: result = ids - 1 if has_nas: result = result.astype(np.float64) np.putmask(result, na_mask, np.nan) return result, bins def _trim_zeros(x): while len(x) > 1 and x[-1] == '0': x = x[:-1] if len(x) > 1 and x[-1] == '.': x = x[:-1] return x def _coerce_to_type(x): """ if the passed data is of datetime/timedelta type, this method converts it to numeric so that cut method can handle it """ dtype = None if is_datetime64tz_dtype(x): dtype = x.dtype elif
is_datetime64_dtype(x)
pandas.core.dtypes.common.is_datetime64_dtype
# -*- coding: utf-8 -*- """ Created on Thu Nov 4 23:37:00 2021 @author: Usuario """ from selenium import webdriver import pandas as pd import re from bs4 import BeautifulSoup import requests from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) url = "http://webtool.framenetbr.ufjf.br/index.php/webtool/report/frame/main" driver.get(url) html_content = requests.get(url).text soup = BeautifulSoup(html_content, "lxml") frame_title = driver.find_elements_by_class_name('tree-title') frame_list = [] for x in frame_title: frame_list.append(x.text) frame_list = [x for x in frame_list if x != "Frames"] driver.find_elements_by_class_name('tree-node')[6].click() frame_name_list = [] frame_definition_list = [] lexical_units_list = [] from time import sleep for x in range(0, len(frame_list)): pasta_frames = driver.find_elements_by_class_name('tree-node')[x].click() sleep(2) if len(driver.find_elements_by_class_name('tableLU')) > 0: frame_name = driver.find_elements_by_class_name('frameName') frame_definition = driver.find_elements_by_class_name('text') lexical_units = driver.find_elements_by_class_name('tableLU') for y in frame_name: frame_name_list.append(y.text) for z in frame_definition: frame_definition_list.append(z.text) for l in lexical_units: lexical_units_list.append(l.text) else: continue driver.close() df =
pd.DataFrame()
pandas.DataFrame
from datetime import datetime import numpy as np import pandas as pd import pytest from numba import njit import vectorbt as vbt from tests.utils import record_arrays_close from vectorbt.generic.enums import range_dt, drawdown_dt from vectorbt.portfolio.enums import order_dt, trade_dt, log_dt day_dt = np.timedelta64(86400000000000) example_dt = np.dtype([ ('id', np.int64), ('col', np.int64), ('idx', np.int64), ('some_field1', np.float64), ('some_field2', np.float64) ], align=True) records_arr = np.asarray([ (0, 0, 0, 10, 21), (1, 0, 1, 11, 20), (2, 0, 2, 12, 19), (3, 1, 0, 13, 18), (4, 1, 1, 14, 17), (5, 1, 2, 13, 18), (6, 2, 0, 12, 19), (7, 2, 1, 11, 20), (8, 2, 2, 10, 21) ], dtype=example_dt) records_nosort_arr = np.concatenate(( records_arr[0::3], records_arr[1::3], records_arr[2::3] )) group_by = pd.Index(['g1', 'g1', 'g2', 'g2']) wrapper = vbt.ArrayWrapper( index=['x', 'y', 'z'], columns=['a', 'b', 'c', 'd'], ndim=2, freq='1 days' ) wrapper_grouped = wrapper.replace(group_by=group_by) records = vbt.records.Records(wrapper, records_arr) records_grouped = vbt.records.Records(wrapper_grouped, records_arr) records_nosort = records.replace(records_arr=records_nosort_arr) records_nosort_grouped = vbt.records.Records(wrapper_grouped, records_nosort_arr) # ############# Global ############# # def setup_module(): vbt.settings.numba['check_func_suffix'] = True vbt.settings.caching.enabled = False vbt.settings.caching.whitelist = [] vbt.settings.caching.blacklist = [] def teardown_module(): vbt.settings.reset() # ############# col_mapper.py ############# # class TestColumnMapper: def test_col_arr(self): np.testing.assert_array_equal( records['a'].col_mapper.col_arr, np.array([0, 0, 0]) ) np.testing.assert_array_equal( records.col_mapper.col_arr, np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]) ) def test_get_col_arr(self): np.testing.assert_array_equal( records.col_mapper.get_col_arr(), records.col_mapper.col_arr ) np.testing.assert_array_equal( records_grouped['g1'].col_mapper.get_col_arr(), np.array([0, 0, 0, 0, 0, 0]) ) np.testing.assert_array_equal( records_grouped.col_mapper.get_col_arr(), np.array([0, 0, 0, 0, 0, 0, 1, 1, 1]) ) def test_col_range(self): np.testing.assert_array_equal( records['a'].col_mapper.col_range, np.array([ [0, 3] ]) ) np.testing.assert_array_equal( records.col_mapper.col_range, np.array([ [0, 3], [3, 6], [6, 9], [-1, -1] ]) ) def test_get_col_range(self): np.testing.assert_array_equal( records.col_mapper.get_col_range(), np.array([ [0, 3], [3, 6], [6, 9], [-1, -1] ]) ) np.testing.assert_array_equal( records_grouped['g1'].col_mapper.get_col_range(), np.array([[0, 6]]) ) np.testing.assert_array_equal( records_grouped.col_mapper.get_col_range(), np.array([[0, 6], [6, 9]]) ) def test_col_map(self): np.testing.assert_array_equal( records['a'].col_mapper.col_map[0], np.array([0, 1, 2]) ) np.testing.assert_array_equal( records['a'].col_mapper.col_map[1], np.array([3]) ) np.testing.assert_array_equal( records.col_mapper.col_map[0], np.array([0, 1, 2, 3, 4, 5, 6, 7, 8]) ) np.testing.assert_array_equal( records.col_mapper.col_map[1], np.array([3, 3, 3, 0]) ) def test_get_col_map(self): np.testing.assert_array_equal( records.col_mapper.get_col_map()[0], records.col_mapper.col_map[0] ) np.testing.assert_array_equal( records.col_mapper.get_col_map()[1], records.col_mapper.col_map[1] ) np.testing.assert_array_equal( records_grouped['g1'].col_mapper.get_col_map()[0], np.array([0, 1, 2, 3, 4, 5]) ) np.testing.assert_array_equal( records_grouped['g1'].col_mapper.get_col_map()[1], np.array([6]) ) np.testing.assert_array_equal( records_grouped.col_mapper.get_col_map()[0], np.array([0, 1, 2, 3, 4, 5, 6, 7, 8]) ) np.testing.assert_array_equal( records_grouped.col_mapper.get_col_map()[1], np.array([6, 3]) ) def test_is_sorted(self): assert records.col_mapper.is_sorted() assert not records_nosort.col_mapper.is_sorted() # ############# mapped_array.py ############# # mapped_array = records.map_field('some_field1') mapped_array_grouped = records_grouped.map_field('some_field1') mapped_array_nosort = records_nosort.map_field('some_field1') mapped_array_nosort_grouped = records_nosort_grouped.map_field('some_field1') mapping = {x: 'test_' + str(x) for x in pd.unique(mapped_array.values)} mp_mapped_array = mapped_array.replace(mapping=mapping) mp_mapped_array_grouped = mapped_array_grouped.replace(mapping=mapping) class TestMappedArray: def test_config(self, tmp_path): assert vbt.MappedArray.loads(mapped_array.dumps()) == mapped_array mapped_array.save(tmp_path / 'mapped_array') assert vbt.MappedArray.load(tmp_path / 'mapped_array') == mapped_array def test_mapped_arr(self): np.testing.assert_array_equal( mapped_array['a'].values, np.array([10., 11., 12.]) ) np.testing.assert_array_equal( mapped_array.values, np.array([10., 11., 12., 13., 14., 13., 12., 11., 10.]) ) def test_id_arr(self): np.testing.assert_array_equal( mapped_array['a'].id_arr, np.array([0, 1, 2]) ) np.testing.assert_array_equal( mapped_array.id_arr, np.array([0, 1, 2, 3, 4, 5, 6, 7, 8]) ) def test_col_arr(self): np.testing.assert_array_equal( mapped_array['a'].col_arr, np.array([0, 0, 0]) ) np.testing.assert_array_equal( mapped_array.col_arr, np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]) ) def test_idx_arr(self): np.testing.assert_array_equal( mapped_array['a'].idx_arr, np.array([0, 1, 2]) ) np.testing.assert_array_equal( mapped_array.idx_arr, np.array([0, 1, 2, 0, 1, 2, 0, 1, 2]) ) def test_is_sorted(self): assert mapped_array.is_sorted() assert mapped_array.is_sorted(incl_id=True) assert not mapped_array_nosort.is_sorted() assert not mapped_array_nosort.is_sorted(incl_id=True) def test_sort(self): assert mapped_array.sort().is_sorted() assert mapped_array.sort().is_sorted(incl_id=True) assert mapped_array.sort(incl_id=True).is_sorted(incl_id=True) assert mapped_array_nosort.sort().is_sorted() assert mapped_array_nosort.sort().is_sorted(incl_id=True) assert mapped_array_nosort.sort(incl_id=True).is_sorted(incl_id=True) def test_apply_mask(self): mask_a = mapped_array['a'].values >= mapped_array['a'].values.mean() np.testing.assert_array_equal( mapped_array['a'].apply_mask(mask_a).id_arr, np.array([1, 2]) ) mask = mapped_array.values >= mapped_array.values.mean() filtered = mapped_array.apply_mask(mask) np.testing.assert_array_equal( filtered.id_arr, np.array([2, 3, 4, 5, 6]) ) np.testing.assert_array_equal(filtered.col_arr, mapped_array.col_arr[mask]) np.testing.assert_array_equal(filtered.idx_arr, mapped_array.idx_arr[mask]) assert mapped_array_grouped.apply_mask(mask).wrapper == mapped_array_grouped.wrapper assert mapped_array_grouped.apply_mask(mask, group_by=False).wrapper.grouper.group_by is None def test_map_to_mask(self): @njit def every_2_nb(inout, idxs, col, mapped_arr): inout[idxs[::2]] = True np.testing.assert_array_equal( mapped_array.map_to_mask(every_2_nb), np.array([True, False, True, True, False, True, True, False, True]) ) def test_top_n_mask(self): np.testing.assert_array_equal( mapped_array.top_n_mask(1), np.array([False, False, True, False, True, False, True, False, False]) ) def test_bottom_n_mask(self): np.testing.assert_array_equal( mapped_array.bottom_n_mask(1), np.array([True, False, False, True, False, False, False, False, True]) ) def test_top_n(self): np.testing.assert_array_equal( mapped_array.top_n(1).id_arr, np.array([2, 4, 6]) ) def test_bottom_n(self): np.testing.assert_array_equal( mapped_array.bottom_n(1).id_arr, np.array([0, 3, 8]) ) def test_to_pd(self): target = pd.DataFrame( np.array([ [10., 13., 12., np.nan], [11., 14., 11., np.nan], [12., 13., 10., np.nan] ]), index=wrapper.index, columns=wrapper.columns ) pd.testing.assert_series_equal( mapped_array['a'].to_pd(), target['a'] ) pd.testing.assert_frame_equal( mapped_array.to_pd(), target ) pd.testing.assert_frame_equal( mapped_array.to_pd(fill_value=0.), target.fillna(0.) ) mapped_array2 = vbt.MappedArray( wrapper, records_arr['some_field1'].tolist() + [1], records_arr['col'].tolist() + [2], idx_arr=records_arr['idx'].tolist() + [2] ) with pytest.raises(Exception): _ = mapped_array2.to_pd() pd.testing.assert_series_equal( mapped_array['a'].to_pd(ignore_index=True), pd.Series(np.array([10., 11., 12.]), name='a') ) pd.testing.assert_frame_equal( mapped_array.to_pd(ignore_index=True), pd.DataFrame( np.array([ [10., 13., 12., np.nan], [11., 14., 11., np.nan], [12., 13., 10., np.nan] ]), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array.to_pd(fill_value=0, ignore_index=True), pd.DataFrame( np.array([ [10., 13., 12., 0.], [11., 14., 11., 0.], [12., 13., 10., 0.] ]), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array_grouped.to_pd(ignore_index=True), pd.DataFrame( np.array([ [10., 12.], [11., 11.], [12., 10.], [13., np.nan], [14., np.nan], [13., np.nan], ]), columns=pd.Index(['g1', 'g2'], dtype='object') ) ) def test_apply(self): @njit def cumsum_apply_nb(idxs, col, a): return np.cumsum(a) np.testing.assert_array_equal( mapped_array['a'].apply(cumsum_apply_nb).values, np.array([10., 21., 33.]) ) np.testing.assert_array_equal( mapped_array.apply(cumsum_apply_nb).values, np.array([10., 21., 33., 13., 27., 40., 12., 23., 33.]) ) np.testing.assert_array_equal( mapped_array_grouped.apply(cumsum_apply_nb, apply_per_group=False).values, np.array([10., 21., 33., 13., 27., 40., 12., 23., 33.]) ) np.testing.assert_array_equal( mapped_array_grouped.apply(cumsum_apply_nb, apply_per_group=True).values, np.array([10., 21., 33., 46., 60., 73., 12., 23., 33.]) ) assert mapped_array_grouped.apply(cumsum_apply_nb).wrapper == \ mapped_array.apply(cumsum_apply_nb, group_by=group_by).wrapper assert mapped_array.apply(cumsum_apply_nb, group_by=False).wrapper.grouper.group_by is None def test_reduce(self): @njit def mean_reduce_nb(col, a): return np.mean(a) assert mapped_array['a'].reduce(mean_reduce_nb) == 11. pd.testing.assert_series_equal( mapped_array.reduce(mean_reduce_nb), pd.Series(np.array([11., 13.333333333333334, 11., np.nan]), index=wrapper.columns).rename('reduce') ) pd.testing.assert_series_equal( mapped_array.reduce(mean_reduce_nb, fill_value=0.), pd.Series(np.array([11., 13.333333333333334, 11., 0.]), index=wrapper.columns).rename('reduce') ) pd.testing.assert_series_equal( mapped_array.reduce(mean_reduce_nb, fill_value=0., wrap_kwargs=dict(dtype=np.int_)), pd.Series(np.array([11., 13.333333333333334, 11., 0.]), index=wrapper.columns).rename('reduce') ) pd.testing.assert_series_equal( mapped_array.reduce(mean_reduce_nb, wrap_kwargs=dict(to_timedelta=True)), pd.Series(np.array([11., 13.333333333333334, 11., np.nan]), index=wrapper.columns).rename('reduce') * day_dt ) pd.testing.assert_series_equal( mapped_array_grouped.reduce(mean_reduce_nb), pd.Series([12.166666666666666, 11.0], index=pd.Index(['g1', 'g2'], dtype='object')).rename('reduce') ) assert mapped_array_grouped['g1'].reduce(mean_reduce_nb) == 12.166666666666666 pd.testing.assert_series_equal( mapped_array_grouped[['g1']].reduce(mean_reduce_nb), pd.Series([12.166666666666666], index=pd.Index(['g1'], dtype='object')).rename('reduce') ) pd.testing.assert_series_equal( mapped_array.reduce(mean_reduce_nb), mapped_array_grouped.reduce(mean_reduce_nb, group_by=False) ) pd.testing.assert_series_equal( mapped_array.reduce(mean_reduce_nb, group_by=group_by), mapped_array_grouped.reduce(mean_reduce_nb) ) def test_reduce_to_idx(self): @njit def argmin_reduce_nb(col, a): return np.argmin(a) assert mapped_array['a'].reduce(argmin_reduce_nb, returns_idx=True) == 'x' pd.testing.assert_series_equal( mapped_array.reduce(argmin_reduce_nb, returns_idx=True), pd.Series(np.array(['x', 'x', 'z', np.nan], dtype=object), index=wrapper.columns).rename('reduce') ) pd.testing.assert_series_equal( mapped_array.reduce(argmin_reduce_nb, returns_idx=True, to_index=False), pd.Series(np.array([0, 0, 2, -1], dtype=int), index=wrapper.columns).rename('reduce') ) pd.testing.assert_series_equal( mapped_array_grouped.reduce(argmin_reduce_nb, returns_idx=True, to_index=False), pd.Series(np.array([0, 2], dtype=int), index=pd.Index(['g1', 'g2'], dtype='object')).rename('reduce') ) def test_reduce_to_array(self): @njit def min_max_reduce_nb(col, a): return np.array([np.min(a), np.max(a)]) pd.testing.assert_series_equal( mapped_array['a'].reduce(min_max_reduce_nb, returns_array=True, wrap_kwargs=dict(name_or_index=['min', 'max'])), pd.Series([10., 12.], index=pd.Index(['min', 'max'], dtype='object'), name='a') ) pd.testing.assert_frame_equal( mapped_array.reduce(min_max_reduce_nb, returns_array=True, wrap_kwargs=dict(name_or_index=['min', 'max'])), pd.DataFrame( np.array([ [10., 13., 10., np.nan], [12., 14., 12., np.nan] ]), index=pd.Index(['min', 'max'], dtype='object'), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array.reduce(min_max_reduce_nb, returns_array=True, fill_value=0.), pd.DataFrame( np.array([ [10., 13., 10., 0.], [12., 14., 12., 0.] ]), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array.reduce(min_max_reduce_nb, returns_array=True, wrap_kwargs=dict(to_timedelta=True)), pd.DataFrame( np.array([ [10., 13., 10., np.nan], [12., 14., 12., np.nan] ]), columns=wrapper.columns ) * day_dt ) pd.testing.assert_frame_equal( mapped_array_grouped.reduce(min_max_reduce_nb, returns_array=True), pd.DataFrame( np.array([ [10., 10.], [14., 12.] ]), columns=pd.Index(['g1', 'g2'], dtype='object') ) ) pd.testing.assert_frame_equal( mapped_array.reduce(min_max_reduce_nb, returns_array=True), mapped_array_grouped.reduce(min_max_reduce_nb, returns_array=True, group_by=False) ) pd.testing.assert_frame_equal( mapped_array.reduce(min_max_reduce_nb, returns_array=True, group_by=group_by), mapped_array_grouped.reduce(min_max_reduce_nb, returns_array=True) ) pd.testing.assert_series_equal( mapped_array_grouped['g1'].reduce(min_max_reduce_nb, returns_array=True), pd.Series([10., 14.], name='g1') ) pd.testing.assert_frame_equal( mapped_array_grouped[['g1']].reduce(min_max_reduce_nb, returns_array=True), pd.DataFrame([[10.], [14.]], columns=pd.Index(['g1'], dtype='object')) ) def test_reduce_to_idx_array(self): @njit def idxmin_idxmax_reduce_nb(col, a): return np.array([np.argmin(a), np.argmax(a)]) pd.testing.assert_series_equal( mapped_array['a'].reduce( idxmin_idxmax_reduce_nb, returns_array=True, returns_idx=True, wrap_kwargs=dict(name_or_index=['min', 'max']) ), pd.Series( np.array(['x', 'z'], dtype=object), index=pd.Index(['min', 'max'], dtype='object'), name='a' ) ) pd.testing.assert_frame_equal( mapped_array.reduce( idxmin_idxmax_reduce_nb, returns_array=True, returns_idx=True, wrap_kwargs=dict(name_or_index=['min', 'max']) ), pd.DataFrame( { 'a': ['x', 'z'], 'b': ['x', 'y'], 'c': ['z', 'x'], 'd': [np.nan, np.nan] }, index=pd.Index(['min', 'max'], dtype='object') ) ) pd.testing.assert_frame_equal( mapped_array.reduce( idxmin_idxmax_reduce_nb, returns_array=True, returns_idx=True, to_index=False ), pd.DataFrame( np.array([ [0, 0, 2, -1], [2, 1, 0, -1] ]), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array_grouped.reduce( idxmin_idxmax_reduce_nb, returns_array=True, returns_idx=True, to_index=False ), pd.DataFrame( np.array([ [0, 2], [1, 0] ]), columns=pd.Index(['g1', 'g2'], dtype='object') ) ) def test_nth(self): assert mapped_array['a'].nth(0) == 10. pd.testing.assert_series_equal( mapped_array.nth(0), pd.Series(np.array([10., 13., 12., np.nan]), index=wrapper.columns).rename('nth') ) assert mapped_array['a'].nth(-1) == 12. pd.testing.assert_series_equal( mapped_array.nth(-1), pd.Series(np.array([12., 13., 10., np.nan]), index=wrapper.columns).rename('nth') ) with pytest.raises(Exception): _ = mapped_array.nth(10) pd.testing.assert_series_equal( mapped_array_grouped.nth(0), pd.Series(np.array([10., 12.]), index=pd.Index(['g1', 'g2'], dtype='object')).rename('nth') ) def test_nth_index(self): assert mapped_array['a'].nth(0) == 10. pd.testing.assert_series_equal( mapped_array.nth_index(0), pd.Series( np.array(['x', 'x', 'x', np.nan], dtype='object'), index=wrapper.columns ).rename('nth_index') ) assert mapped_array['a'].nth(-1) == 12. pd.testing.assert_series_equal( mapped_array.nth_index(-1), pd.Series( np.array(['z', 'z', 'z', np.nan], dtype='object'), index=wrapper.columns ).rename('nth_index') ) with pytest.raises(Exception): _ = mapped_array.nth_index(10) pd.testing.assert_series_equal( mapped_array_grouped.nth_index(0), pd.Series( np.array(['x', 'x'], dtype='object'), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('nth_index') ) def test_min(self): assert mapped_array['a'].min() == mapped_array['a'].to_pd().min() pd.testing.assert_series_equal( mapped_array.min(), mapped_array.to_pd().min().rename('min') ) pd.testing.assert_series_equal( mapped_array_grouped.min(), pd.Series([10., 10.], index=pd.Index(['g1', 'g2'], dtype='object')).rename('min') ) def test_max(self): assert mapped_array['a'].max() == mapped_array['a'].to_pd().max() pd.testing.assert_series_equal( mapped_array.max(), mapped_array.to_pd().max().rename('max') ) pd.testing.assert_series_equal( mapped_array_grouped.max(), pd.Series([14., 12.], index=pd.Index(['g1', 'g2'], dtype='object')).rename('max') ) def test_mean(self): assert mapped_array['a'].mean() == mapped_array['a'].to_pd().mean() pd.testing.assert_series_equal( mapped_array.mean(), mapped_array.to_pd().mean().rename('mean') ) pd.testing.assert_series_equal( mapped_array_grouped.mean(), pd.Series([12.166667, 11.], index=pd.Index(['g1', 'g2'], dtype='object')).rename('mean') ) def test_median(self): assert mapped_array['a'].median() == mapped_array['a'].to_pd().median() pd.testing.assert_series_equal( mapped_array.median(), mapped_array.to_pd().median().rename('median') ) pd.testing.assert_series_equal( mapped_array_grouped.median(), pd.Series([12.5, 11.], index=pd.Index(['g1', 'g2'], dtype='object')).rename('median') ) def test_std(self): assert mapped_array['a'].std() == mapped_array['a'].to_pd().std() pd.testing.assert_series_equal( mapped_array.std(), mapped_array.to_pd().std().rename('std') ) pd.testing.assert_series_equal( mapped_array.std(ddof=0), mapped_array.to_pd().std(ddof=0).rename('std') ) pd.testing.assert_series_equal( mapped_array_grouped.std(), pd.Series([1.4719601443879746, 1.0], index=pd.Index(['g1', 'g2'], dtype='object')).rename('std') ) def test_sum(self): assert mapped_array['a'].sum() == mapped_array['a'].to_pd().sum() pd.testing.assert_series_equal( mapped_array.sum(), mapped_array.to_pd().sum().rename('sum') ) pd.testing.assert_series_equal( mapped_array_grouped.sum(), pd.Series([73.0, 33.0], index=pd.Index(['g1', 'g2'], dtype='object')).rename('sum') ) def test_count(self): assert mapped_array['a'].count() == mapped_array['a'].to_pd().count() pd.testing.assert_series_equal( mapped_array.count(), mapped_array.to_pd().count().rename('count') ) pd.testing.assert_series_equal( mapped_array_grouped.count(), pd.Series([6, 3], index=pd.Index(['g1', 'g2'], dtype='object')).rename('count') ) def test_idxmin(self): assert mapped_array['a'].idxmin() == mapped_array['a'].to_pd().idxmin() pd.testing.assert_series_equal( mapped_array.idxmin(), mapped_array.to_pd().idxmin().rename('idxmin') ) pd.testing.assert_series_equal( mapped_array_grouped.idxmin(), pd.Series( np.array(['x', 'z'], dtype=object), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('idxmin') ) def test_idxmax(self): assert mapped_array['a'].idxmax() == mapped_array['a'].to_pd().idxmax() pd.testing.assert_series_equal( mapped_array.idxmax(), mapped_array.to_pd().idxmax().rename('idxmax') ) pd.testing.assert_series_equal( mapped_array_grouped.idxmax(), pd.Series( np.array(['y', 'x'], dtype=object), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('idxmax') ) def test_describe(self): pd.testing.assert_series_equal( mapped_array['a'].describe(), mapped_array['a'].to_pd().describe() ) pd.testing.assert_frame_equal( mapped_array.describe(percentiles=None), mapped_array.to_pd().describe(percentiles=None) ) pd.testing.assert_frame_equal( mapped_array.describe(percentiles=[]), mapped_array.to_pd().describe(percentiles=[]) ) pd.testing.assert_frame_equal( mapped_array.describe(percentiles=np.arange(0, 1, 0.1)), mapped_array.to_pd().describe(percentiles=np.arange(0, 1, 0.1)) ) pd.testing.assert_frame_equal( mapped_array_grouped.describe(), pd.DataFrame( np.array([ [6., 3.], [12.16666667, 11.], [1.47196014, 1.], [10., 10.], [11.25, 10.5], [12.5, 11.], [13., 11.5], [14., 12.] ]), columns=pd.Index(['g1', 'g2'], dtype='object'), index=mapped_array.describe().index ) ) def test_value_counts(self): pd.testing.assert_series_equal( mapped_array['a'].value_counts(), pd.Series( np.array([1, 1, 1]), index=pd.Float64Index([10.0, 11.0, 12.0], dtype='float64'), name='a' ) ) pd.testing.assert_series_equal( mapped_array['a'].value_counts(mapping=mapping), pd.Series( np.array([1, 1, 1]), index=pd.Index(['test_10.0', 'test_11.0', 'test_12.0'], dtype='object'), name='a' ) ) pd.testing.assert_frame_equal( mapped_array.value_counts(), pd.DataFrame( np.array([ [1, 0, 1, 0], [1, 0, 1, 0], [1, 0, 1, 0], [0, 2, 0, 0], [0, 1, 0, 0] ]), index=pd.Float64Index([10.0, 11.0, 12.0, 13.0, 14.0], dtype='float64'), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array_grouped.value_counts(), pd.DataFrame( np.array([ [1, 1], [1, 1], [1, 1], [2, 0], [1, 0] ]), index=pd.Float64Index([10.0, 11.0, 12.0, 13.0, 14.0], dtype='float64'), columns=pd.Index(['g1', 'g2'], dtype='object') ) ) mapped_array2 = mapped_array.replace(mapped_arr=[4, 4, 3, 2, np.nan, 4, 3, 2, 1]) pd.testing.assert_frame_equal( mapped_array2.value_counts(sort_uniques=False), pd.DataFrame( np.array([ [2, 1, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 1, 0, 0] ]), index=pd.Float64Index([4.0, 3.0, 2.0, 1.0, None], dtype='float64'), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array2.value_counts(sort_uniques=True), pd.DataFrame( np.array([ [0, 0, 1, 0], [0, 1, 1, 0], [1, 0, 1, 0], [2, 1, 0, 0], [0, 1, 0, 0] ]), index=pd.Float64Index([1.0, 2.0, 3.0, 4.0, None], dtype='float64'), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array2.value_counts(sort=True), pd.DataFrame( np.array([ [2, 1, 0, 0], [0, 1, 1, 0], [1, 0, 1, 0], [0, 0, 1, 0], [0, 1, 0, 0] ]), index=pd.Float64Index([4.0, 2.0, 3.0, 1.0, np.nan], dtype='float64'), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array2.value_counts(sort=True, ascending=True), pd.DataFrame( np.array([ [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 1, 0], [1, 0, 1, 0], [2, 1, 0, 0] ]), index=pd.Float64Index([1.0, np.nan, 2.0, 3.0, 4.0], dtype='float64'), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array2.value_counts(sort=True, normalize=True), pd.DataFrame( np.array([ [0.2222222222222222, 0.1111111111111111, 0.0, 0.0], [0.0, 0.1111111111111111, 0.1111111111111111, 0.0], [0.1111111111111111, 0.0, 0.1111111111111111, 0.0], [0.0, 0.0, 0.1111111111111111, 0.0], [0.0, 0.1111111111111111, 0.0, 0.0] ]), index=pd.Float64Index([4.0, 2.0, 3.0, 1.0, np.nan], dtype='float64'), columns=wrapper.columns ) ) pd.testing.assert_frame_equal( mapped_array2.value_counts(sort=True, normalize=True, dropna=True), pd.DataFrame( np.array([ [0.25, 0.125, 0.0, 0.0], [0.0, 0.125, 0.125, 0.0], [0.125, 0.0, 0.125, 0.0], [0.0, 0.0, 0.125, 0.0] ]), index=pd.Float64Index([4.0, 2.0, 3.0, 1.0], dtype='float64'), columns=wrapper.columns ) ) @pytest.mark.parametrize( "test_nosort", [False, True], ) def test_indexing(self, test_nosort): if test_nosort: ma = mapped_array_nosort ma_grouped = mapped_array_nosort_grouped else: ma = mapped_array ma_grouped = mapped_array_grouped np.testing.assert_array_equal( ma['a'].id_arr, np.array([0, 1, 2]) ) np.testing.assert_array_equal( ma['a'].col_arr, np.array([0, 0, 0]) ) pd.testing.assert_index_equal( ma['a'].wrapper.columns, pd.Index(['a'], dtype='object') ) np.testing.assert_array_equal( ma['b'].id_arr, np.array([3, 4, 5]) ) np.testing.assert_array_equal( ma['b'].col_arr, np.array([0, 0, 0]) ) pd.testing.assert_index_equal( ma['b'].wrapper.columns, pd.Index(['b'], dtype='object') ) np.testing.assert_array_equal( ma[['a', 'a']].id_arr, np.array([0, 1, 2, 0, 1, 2]) ) np.testing.assert_array_equal( ma[['a', 'a']].col_arr, np.array([0, 0, 0, 1, 1, 1]) ) pd.testing.assert_index_equal( ma[['a', 'a']].wrapper.columns, pd.Index(['a', 'a'], dtype='object') ) np.testing.assert_array_equal( ma[['a', 'b']].id_arr, np.array([0, 1, 2, 3, 4, 5]) ) np.testing.assert_array_equal( ma[['a', 'b']].col_arr, np.array([0, 0, 0, 1, 1, 1]) ) pd.testing.assert_index_equal( ma[['a', 'b']].wrapper.columns, pd.Index(['a', 'b'], dtype='object') ) with pytest.raises(Exception): _ = ma.iloc[::2, :] # changing time not supported pd.testing.assert_index_equal( ma_grouped['g1'].wrapper.columns, pd.Index(['a', 'b'], dtype='object') ) assert ma_grouped['g1'].wrapper.ndim == 2 assert ma_grouped['g1'].wrapper.grouped_ndim == 1 pd.testing.assert_index_equal( ma_grouped['g1'].wrapper.grouper.group_by, pd.Index(['g1', 'g1'], dtype='object') ) pd.testing.assert_index_equal( ma_grouped['g2'].wrapper.columns, pd.Index(['c', 'd'], dtype='object') ) assert ma_grouped['g2'].wrapper.ndim == 2 assert ma_grouped['g2'].wrapper.grouped_ndim == 1 pd.testing.assert_index_equal( ma_grouped['g2'].wrapper.grouper.group_by, pd.Index(['g2', 'g2'], dtype='object') ) pd.testing.assert_index_equal( ma_grouped[['g1']].wrapper.columns, pd.Index(['a', 'b'], dtype='object') ) assert ma_grouped[['g1']].wrapper.ndim == 2 assert ma_grouped[['g1']].wrapper.grouped_ndim == 2 pd.testing.assert_index_equal( ma_grouped[['g1']].wrapper.grouper.group_by, pd.Index(['g1', 'g1'], dtype='object') ) pd.testing.assert_index_equal( ma_grouped[['g1', 'g2']].wrapper.columns, pd.Index(['a', 'b', 'c', 'd'], dtype='object') ) assert ma_grouped[['g1', 'g2']].wrapper.ndim == 2 assert ma_grouped[['g1', 'g2']].wrapper.grouped_ndim == 2 pd.testing.assert_index_equal( ma_grouped[['g1', 'g2']].wrapper.grouper.group_by, pd.Index(['g1', 'g1', 'g2', 'g2'], dtype='object') ) def test_magic(self): a = vbt.MappedArray( wrapper, records_arr['some_field1'], records_arr['col'], id_arr=records_arr['id'], idx_arr=records_arr['idx'] ) a_inv = vbt.MappedArray( wrapper, records_arr['some_field1'][::-1], records_arr['col'][::-1], id_arr=records_arr['id'][::-1], idx_arr=records_arr['idx'][::-1] ) b = records_arr['some_field2'] a_bool = vbt.MappedArray( wrapper, records_arr['some_field1'] > np.mean(records_arr['some_field1']), records_arr['col'], id_arr=records_arr['id'], idx_arr=records_arr['idx'] ) b_bool = records_arr['some_field2'] > np.mean(records_arr['some_field2']) assert a ** a == a ** 2 with pytest.raises(Exception): _ = a * a_inv # binary ops # comparison ops np.testing.assert_array_equal((a == b).values, a.values == b) np.testing.assert_array_equal((a != b).values, a.values != b) np.testing.assert_array_equal((a < b).values, a.values < b) np.testing.assert_array_equal((a > b).values, a.values > b) np.testing.assert_array_equal((a <= b).values, a.values <= b) np.testing.assert_array_equal((a >= b).values, a.values >= b) # arithmetic ops np.testing.assert_array_equal((a + b).values, a.values + b) np.testing.assert_array_equal((a - b).values, a.values - b) np.testing.assert_array_equal((a * b).values, a.values * b) np.testing.assert_array_equal((a ** b).values, a.values ** b) np.testing.assert_array_equal((a % b).values, a.values % b) np.testing.assert_array_equal((a // b).values, a.values // b) np.testing.assert_array_equal((a / b).values, a.values / b) # __r*__ is only called if the left object does not have an __*__ method np.testing.assert_array_equal((10 + a).values, 10 + a.values) np.testing.assert_array_equal((10 - a).values, 10 - a.values) np.testing.assert_array_equal((10 * a).values, 10 * a.values) np.testing.assert_array_equal((10 ** a).values, 10 ** a.values) np.testing.assert_array_equal((10 % a).values, 10 % a.values) np.testing.assert_array_equal((10 // a).values, 10 // a.values) np.testing.assert_array_equal((10 / a).values, 10 / a.values) # mask ops np.testing.assert_array_equal((a_bool & b_bool).values, a_bool.values & b_bool) np.testing.assert_array_equal((a_bool | b_bool).values, a_bool.values | b_bool) np.testing.assert_array_equal((a_bool ^ b_bool).values, a_bool.values ^ b_bool) np.testing.assert_array_equal((True & a_bool).values, True & a_bool.values) np.testing.assert_array_equal((True | a_bool).values, True | a_bool.values) np.testing.assert_array_equal((True ^ a_bool).values, True ^ a_bool.values) # unary ops np.testing.assert_array_equal((-a).values, -a.values) np.testing.assert_array_equal((+a).values, +a.values) np.testing.assert_array_equal((abs(-a)).values, abs((-a.values))) def test_stats(self): stats_index = pd.Index([ 'Start', 'End', 'Period', 'Count', 'Mean', 'Std', 'Min', 'Median', 'Max', 'Min Index', 'Max Index' ], dtype='object') pd.testing.assert_series_equal( mapped_array.stats(), pd.Series([ 'x', 'z', pd.Timedelta('3 days 00:00:00'), 2.25, 11.777777777777779, 0.859116756396542, 11.0, 11.666666666666666, 12.666666666666666 ], index=stats_index[:-2], name='agg_func_mean' ) ) pd.testing.assert_series_equal( mapped_array.stats(column='a'), pd.Series([ 'x', 'z', pd.Timedelta('3 days 00:00:00'), 3, 11.0, 1.0, 10.0, 11.0, 12.0, 'x', 'z' ], index=stats_index, name='a' ) ) pd.testing.assert_series_equal( mapped_array.stats(column='g1', group_by=group_by), pd.Series([ 'x', 'z', pd.Timedelta('3 days 00:00:00'), 6, 12.166666666666666, 1.4719601443879746, 10.0, 12.5, 14.0, 'x', 'y' ], index=stats_index, name='g1' ) ) pd.testing.assert_series_equal( mapped_array['c'].stats(), mapped_array.stats(column='c') ) pd.testing.assert_series_equal( mapped_array['c'].stats(), mapped_array.stats(column='c', group_by=False) ) pd.testing.assert_series_equal( mapped_array_grouped['g2'].stats(), mapped_array_grouped.stats(column='g2') ) pd.testing.assert_series_equal( mapped_array_grouped['g2'].stats(), mapped_array.stats(column='g2', group_by=group_by) ) stats_df = mapped_array.stats(agg_func=None) assert stats_df.shape == (4, 11) pd.testing.assert_index_equal(stats_df.index, mapped_array.wrapper.columns) pd.testing.assert_index_equal(stats_df.columns, stats_index) def test_stats_mapping(self): stats_index = pd.Index([ 'Start', 'End', 'Period', 'Count', 'Value Counts: test_10.0', 'Value Counts: test_11.0', 'Value Counts: test_12.0', 'Value Counts: test_13.0', 'Value Counts: test_14.0' ], dtype='object') pd.testing.assert_series_equal( mp_mapped_array.stats(), pd.Series([ 'x', 'z', pd.Timedelta('3 days 00:00:00'), 2.25, 0.5, 0.5, 0.5, 0.5, 0.25 ], index=stats_index, name='agg_func_mean' ) ) pd.testing.assert_series_equal( mp_mapped_array.stats(column='a'), pd.Series([ 'x', 'z', pd.Timedelta('3 days 00:00:00'), 3, 1, 1, 1, 0, 0 ], index=stats_index, name='a' ) ) pd.testing.assert_series_equal( mp_mapped_array.stats(column='g1', group_by=group_by), pd.Series([ 'x', 'z', pd.Timedelta('3 days 00:00:00'), 6, 1, 1, 1, 2, 1 ], index=stats_index, name='g1' ) ) pd.testing.assert_series_equal( mp_mapped_array.stats(), mapped_array.stats(settings=dict(mapping=mapping)) ) pd.testing.assert_series_equal( mp_mapped_array['c'].stats(settings=dict(incl_all_keys=True)), mp_mapped_array.stats(column='c') ) pd.testing.assert_series_equal( mp_mapped_array['c'].stats(settings=dict(incl_all_keys=True)), mp_mapped_array.stats(column='c', group_by=False) ) pd.testing.assert_series_equal( mp_mapped_array_grouped['g2'].stats(settings=dict(incl_all_keys=True)), mp_mapped_array_grouped.stats(column='g2') ) pd.testing.assert_series_equal( mp_mapped_array_grouped['g2'].stats(settings=dict(incl_all_keys=True)), mp_mapped_array.stats(column='g2', group_by=group_by) ) stats_df = mp_mapped_array.stats(agg_func=None) assert stats_df.shape == (4, 9) pd.testing.assert_index_equal(stats_df.index, mp_mapped_array.wrapper.columns) pd.testing.assert_index_equal(stats_df.columns, stats_index) # ############# base.py ############# # class TestRecords: def test_config(self, tmp_path): assert vbt.Records.loads(records['a'].dumps()) == records['a'] assert vbt.Records.loads(records.dumps()) == records records.save(tmp_path / 'records') assert vbt.Records.load(tmp_path / 'records') == records def test_records(self): pd.testing.assert_frame_equal( records.records, pd.DataFrame.from_records(records_arr) ) def test_recarray(self): np.testing.assert_array_equal(records['a'].recarray.some_field1, records['a'].values['some_field1']) np.testing.assert_array_equal(records.recarray.some_field1, records.values['some_field1']) def test_records_readable(self): pd.testing.assert_frame_equal( records.records_readable, pd.DataFrame([ [0, 'a', 'x', 10.0, 21.0], [1, 'a', 'y', 11.0, 20.0], [2, 'a', 'z', 12.0, 19.0], [3, 'b', 'x', 13.0, 18.0], [4, 'b', 'y', 14.0, 17.0], [5, 'b', 'z', 13.0, 18.0], [6, 'c', 'x', 12.0, 19.0], [7, 'c', 'y', 11.0, 20.0], [8, 'c', 'z', 10.0, 21.0] ], columns=pd.Index(['Id', 'Column', 'Timestamp', 'some_field1', 'some_field2'], dtype='object')) ) def test_is_sorted(self): assert records.is_sorted() assert records.is_sorted(incl_id=True) assert not records_nosort.is_sorted() assert not records_nosort.is_sorted(incl_id=True) def test_sort(self): assert records.sort().is_sorted() assert records.sort().is_sorted(incl_id=True) assert records.sort(incl_id=True).is_sorted(incl_id=True) assert records_nosort.sort().is_sorted() assert records_nosort.sort().is_sorted(incl_id=True) assert records_nosort.sort(incl_id=True).is_sorted(incl_id=True) def test_apply_mask(self): mask_a = records['a'].values['some_field1'] >= records['a'].values['some_field1'].mean() record_arrays_close( records['a'].apply_mask(mask_a).values, np.array([ (1, 0, 1, 11., 20.), (2, 0, 2, 12., 19.) ], dtype=example_dt) ) mask = records.values['some_field1'] >= records.values['some_field1'].mean() filtered = records.apply_mask(mask) record_arrays_close( filtered.values, np.array([ (2, 0, 2, 12., 19.), (3, 1, 0, 13., 18.), (4, 1, 1, 14., 17.), (5, 1, 2, 13., 18.), (6, 2, 0, 12., 19.) ], dtype=example_dt) ) assert records_grouped.apply_mask(mask).wrapper == records_grouped.wrapper def test_map_field(self): np.testing.assert_array_equal( records['a'].map_field('some_field1').values, np.array([10., 11., 12.]) ) np.testing.assert_array_equal( records.map_field('some_field1').values, np.array([10., 11., 12., 13., 14., 13., 12., 11., 10.]) ) assert records_grouped.map_field('some_field1').wrapper == \ records.map_field('some_field1', group_by=group_by).wrapper assert records_grouped.map_field('some_field1', group_by=False).wrapper.grouper.group_by is None def test_map(self): @njit def map_func_nb(record): return record['some_field1'] + record['some_field2'] np.testing.assert_array_equal( records['a'].map(map_func_nb).values, np.array([31., 31., 31.]) ) np.testing.assert_array_equal( records.map(map_func_nb).values, np.array([31., 31., 31., 31., 31., 31., 31., 31., 31.]) ) assert records_grouped.map(map_func_nb).wrapper == \ records.map(map_func_nb, group_by=group_by).wrapper assert records_grouped.map(map_func_nb, group_by=False).wrapper.grouper.group_by is None def test_map_array(self): arr = records_arr['some_field1'] + records_arr['some_field2'] np.testing.assert_array_equal( records['a'].map_array(arr[:3]).values, np.array([31., 31., 31.]) ) np.testing.assert_array_equal( records.map_array(arr).values, np.array([31., 31., 31., 31., 31., 31., 31., 31., 31.]) ) assert records_grouped.map_array(arr).wrapper == \ records.map_array(arr, group_by=group_by).wrapper assert records_grouped.map_array(arr, group_by=False).wrapper.grouper.group_by is None def test_apply(self): @njit def cumsum_apply_nb(records): return np.cumsum(records['some_field1']) np.testing.assert_array_equal( records['a'].apply(cumsum_apply_nb).values, np.array([10., 21., 33.]) ) np.testing.assert_array_equal( records.apply(cumsum_apply_nb).values, np.array([10., 21., 33., 13., 27., 40., 12., 23., 33.]) ) np.testing.assert_array_equal( records_grouped.apply(cumsum_apply_nb, apply_per_group=False).values, np.array([10., 21., 33., 13., 27., 40., 12., 23., 33.]) ) np.testing.assert_array_equal( records_grouped.apply(cumsum_apply_nb, apply_per_group=True).values, np.array([10., 21., 33., 46., 60., 73., 12., 23., 33.]) ) assert records_grouped.apply(cumsum_apply_nb).wrapper == \ records.apply(cumsum_apply_nb, group_by=group_by).wrapper assert records_grouped.apply(cumsum_apply_nb, group_by=False).wrapper.grouper.group_by is None def test_count(self): assert records['a'].count() == 3 pd.testing.assert_series_equal( records.count(), pd.Series( np.array([3, 3, 3, 0]), index=wrapper.columns ).rename('count') ) assert records_grouped['g1'].count() == 6 pd.testing.assert_series_equal( records_grouped.count(), pd.Series( np.array([6, 3]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('count') ) @pytest.mark.parametrize( "test_nosort", [False, True], ) def test_indexing(self, test_nosort): if test_nosort: r = records_nosort r_grouped = records_nosort_grouped else: r = records r_grouped = records_grouped record_arrays_close( r['a'].values, np.array([ (0, 0, 0, 10., 21.), (1, 0, 1, 11., 20.), (2, 0, 2, 12., 19.) ], dtype=example_dt) ) pd.testing.assert_index_equal( r['a'].wrapper.columns, pd.Index(['a'], dtype='object') ) pd.testing.assert_index_equal( r['b'].wrapper.columns, pd.Index(['b'], dtype='object') ) record_arrays_close( r[['a', 'a']].values, np.array([ (0, 0, 0, 10., 21.), (1, 0, 1, 11., 20.), (2, 0, 2, 12., 19.), (0, 1, 0, 10., 21.), (1, 1, 1, 11., 20.), (2, 1, 2, 12., 19.) ], dtype=example_dt) ) pd.testing.assert_index_equal( r[['a', 'a']].wrapper.columns, pd.Index(['a', 'a'], dtype='object') ) record_arrays_close( r[['a', 'b']].values, np.array([ (0, 0, 0, 10., 21.), (1, 0, 1, 11., 20.), (2, 0, 2, 12., 19.), (3, 1, 0, 13., 18.), (4, 1, 1, 14., 17.), (5, 1, 2, 13., 18.) ], dtype=example_dt) ) pd.testing.assert_index_equal( r[['a', 'b']].wrapper.columns, pd.Index(['a', 'b'], dtype='object') ) with pytest.raises(Exception): _ = r.iloc[::2, :] # changing time not supported pd.testing.assert_index_equal( r_grouped['g1'].wrapper.columns, pd.Index(['a', 'b'], dtype='object') ) assert r_grouped['g1'].wrapper.ndim == 2 assert r_grouped['g1'].wrapper.grouped_ndim == 1 pd.testing.assert_index_equal( r_grouped['g1'].wrapper.grouper.group_by, pd.Index(['g1', 'g1'], dtype='object') ) pd.testing.assert_index_equal( r_grouped['g2'].wrapper.columns, pd.Index(['c', 'd'], dtype='object') ) assert r_grouped['g2'].wrapper.ndim == 2 assert r_grouped['g2'].wrapper.grouped_ndim == 1 pd.testing.assert_index_equal( r_grouped['g2'].wrapper.grouper.group_by, pd.Index(['g2', 'g2'], dtype='object') ) pd.testing.assert_index_equal( r_grouped[['g1']].wrapper.columns, pd.Index(['a', 'b'], dtype='object') ) assert r_grouped[['g1']].wrapper.ndim == 2 assert r_grouped[['g1']].wrapper.grouped_ndim == 2 pd.testing.assert_index_equal( r_grouped[['g1']].wrapper.grouper.group_by, pd.Index(['g1', 'g1'], dtype='object') ) pd.testing.assert_index_equal( r_grouped[['g1', 'g2']].wrapper.columns, pd.Index(['a', 'b', 'c', 'd'], dtype='object') ) assert r_grouped[['g1', 'g2']].wrapper.ndim == 2 assert r_grouped[['g1', 'g2']].wrapper.grouped_ndim == 2 pd.testing.assert_index_equal( r_grouped[['g1', 'g2']].wrapper.grouper.group_by, pd.Index(['g1', 'g1', 'g2', 'g2'], dtype='object') ) def test_filtering(self): filtered_records = vbt.Records(wrapper, records_arr[[0, -1]]) record_arrays_close( filtered_records.values, np.array([(0, 0, 0, 10., 21.), (8, 2, 2, 10., 21.)], dtype=example_dt) ) # a record_arrays_close( filtered_records['a'].values, np.array([(0, 0, 0, 10., 21.)], dtype=example_dt) ) np.testing.assert_array_equal( filtered_records['a'].map_field('some_field1').id_arr, np.array([0]) ) assert filtered_records['a'].map_field('some_field1').min() == 10. assert filtered_records['a'].count() == 1. # b record_arrays_close( filtered_records['b'].values, np.array([], dtype=example_dt) ) np.testing.assert_array_equal( filtered_records['b'].map_field('some_field1').id_arr, np.array([]) ) assert np.isnan(filtered_records['b'].map_field('some_field1').min()) assert filtered_records['b'].count() == 0. # c record_arrays_close( filtered_records['c'].values, np.array([(8, 0, 2, 10., 21.)], dtype=example_dt) ) np.testing.assert_array_equal( filtered_records['c'].map_field('some_field1').id_arr, np.array([8]) ) assert filtered_records['c'].map_field('some_field1').min() == 10. assert filtered_records['c'].count() == 1. # d record_arrays_close( filtered_records['d'].values, np.array([], dtype=example_dt) ) np.testing.assert_array_equal( filtered_records['d'].map_field('some_field1').id_arr, np.array([]) ) assert np.isnan(filtered_records['d'].map_field('some_field1').min()) assert filtered_records['d'].count() == 0. def test_stats(self): stats_index = pd.Index([ 'Start', 'End', 'Period', 'Count' ], dtype='object') pd.testing.assert_series_equal( records.stats(), pd.Series([ 'x', 'z', pd.Timedelta('3 days 00:00:00'), 2.25 ], index=stats_index, name='agg_func_mean' ) ) pd.testing.assert_series_equal( records.stats(column='a'), pd.Series([ 'x', 'z', pd.Timedelta('3 days 00:00:00'), 3 ], index=stats_index, name='a' ) ) pd.testing.assert_series_equal( records.stats(column='g1', group_by=group_by), pd.Series([ 'x', 'z', pd.Timedelta('3 days 00:00:00'), 6 ], index=stats_index, name='g1' ) ) pd.testing.assert_series_equal( records['c'].stats(), records.stats(column='c') ) pd.testing.assert_series_equal( records['c'].stats(), records.stats(column='c', group_by=False) ) pd.testing.assert_series_equal( records_grouped['g2'].stats(), records_grouped.stats(column='g2') ) pd.testing.assert_series_equal( records_grouped['g2'].stats(), records.stats(column='g2', group_by=group_by) ) stats_df = records.stats(agg_func=None) assert stats_df.shape == (4, 4) pd.testing.assert_index_equal(stats_df.index, records.wrapper.columns) pd.testing.assert_index_equal(stats_df.columns, stats_index) # ############# ranges.py ############# # ts = pd.DataFrame({ 'a': [1, -1, 3, -1, 5, -1], 'b': [-1, -1, -1, 4, 5, 6], 'c': [1, 2, 3, -1, -1, -1], 'd': [-1, -1, -1, -1, -1, -1] }, index=[ datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4), datetime(2020, 1, 5), datetime(2020, 1, 6) ]) ranges = vbt.Ranges.from_ts(ts, wrapper_kwargs=dict(freq='1 days')) ranges_grouped = vbt.Ranges.from_ts(ts, wrapper_kwargs=dict(freq='1 days', group_by=group_by)) class TestRanges: def test_mapped_fields(self): for name in range_dt.names: np.testing.assert_array_equal( getattr(ranges, name).values, ranges.values[name] ) def test_from_ts(self): record_arrays_close( ranges.values, np.array([ (0, 0, 0, 1, 1), (1, 0, 2, 3, 1), (2, 0, 4, 5, 1), (3, 1, 3, 5, 0), (4, 2, 0, 3, 1) ], dtype=range_dt) ) assert ranges.wrapper.freq == day_dt pd.testing.assert_index_equal( ranges_grouped.wrapper.grouper.group_by, group_by ) def test_records_readable(self): records_readable = ranges.records_readable np.testing.assert_array_equal( records_readable['Range Id'].values, np.array([ 0, 1, 2, 3, 4 ]) ) np.testing.assert_array_equal( records_readable['Column'].values, np.array([ 'a', 'a', 'a', 'b', 'c' ]) ) np.testing.assert_array_equal( records_readable['Start Timestamp'].values, np.array([ '2020-01-01T00:00:00.000000000', '2020-01-03T00:00:00.000000000', '2020-01-05T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-01T00:00:00.000000000' ], dtype='datetime64[ns]') ) np.testing.assert_array_equal( records_readable['End Timestamp'].values, np.array([ '2020-01-02T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-04T00:00:00.000000000' ], dtype='datetime64[ns]') ) np.testing.assert_array_equal( records_readable['Status'].values, np.array([ 'Closed', 'Closed', 'Closed', 'Open', 'Closed' ]) ) def test_to_mask(self): pd.testing.assert_series_equal( ranges['a'].to_mask(), ts['a'] != -1 ) pd.testing.assert_frame_equal( ranges.to_mask(), ts != -1 ) pd.testing.assert_frame_equal( ranges_grouped.to_mask(), pd.DataFrame( [ [True, True], [False, True], [True, True], [True, False], [True, False], [True, False] ], index=ts.index, columns=pd.Index(['g1', 'g2'], dtype='object') ) ) def test_duration(self): np.testing.assert_array_equal( ranges['a'].duration.values, np.array([1, 1, 1]) ) np.testing.assert_array_equal( ranges.duration.values, np.array([1, 1, 1, 3, 3]) ) def test_avg_duration(self): assert ranges['a'].avg_duration() == pd.Timedelta('1 days 00:00:00') pd.testing.assert_series_equal( ranges.avg_duration(), pd.Series( np.array([86400000000000, 259200000000000, 259200000000000, 'NaT'], dtype='timedelta64[ns]'), index=wrapper.columns ).rename('avg_duration') ) pd.testing.assert_series_equal( ranges_grouped.avg_duration(), pd.Series( np.array([129600000000000, 259200000000000], dtype='timedelta64[ns]'), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('avg_duration') ) def test_max_duration(self): assert ranges['a'].max_duration() == pd.Timedelta('1 days 00:00:00') pd.testing.assert_series_equal( ranges.max_duration(), pd.Series( np.array([86400000000000, 259200000000000, 259200000000000, 'NaT'], dtype='timedelta64[ns]'), index=wrapper.columns ).rename('max_duration') ) pd.testing.assert_series_equal( ranges_grouped.max_duration(), pd.Series( np.array([259200000000000, 259200000000000], dtype='timedelta64[ns]'), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('max_duration') ) def test_coverage(self): assert ranges['a'].coverage() == 0.5 pd.testing.assert_series_equal( ranges.coverage(), pd.Series( np.array([0.5, 0.5, 0.5, np.nan]), index=ts2.columns ).rename('coverage') ) pd.testing.assert_series_equal( ranges.coverage(), ranges.replace(records_arr=np.repeat(ranges.values, 2)).coverage() ) pd.testing.assert_series_equal( ranges.replace(records_arr=np.repeat(ranges.values, 2)).coverage(overlapping=True), pd.Series( np.array([1.0, 1.0, 1.0, np.nan]), index=ts2.columns ).rename('coverage') ) pd.testing.assert_series_equal( ranges.coverage(normalize=False), pd.Series( np.array([3.0, 3.0, 3.0, np.nan]), index=ts2.columns ).rename('coverage') ) pd.testing.assert_series_equal( ranges.replace(records_arr=np.repeat(ranges.values, 2)).coverage(overlapping=True, normalize=False), pd.Series( np.array([3.0, 3.0, 3.0, np.nan]), index=ts2.columns ).rename('coverage') ) pd.testing.assert_series_equal( ranges_grouped.coverage(), pd.Series( np.array([0.4166666666666667, 0.25]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('coverage') ) pd.testing.assert_series_equal( ranges_grouped.coverage(), ranges_grouped.replace(records_arr=np.repeat(ranges_grouped.values, 2)).coverage() ) def test_stats(self): stats_index = pd.Index([ 'Start', 'End', 'Period', 'Coverage', 'Overlap Coverage', 'Total Records', 'Duration: Min', 'Duration: Median', 'Duration: Max', 'Duration: Mean', 'Duration: Std' ], dtype='object') pd.testing.assert_series_equal( ranges.stats(), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-06 00:00:00'), pd.Timedelta('6 days 00:00:00'), pd.Timedelta('3 days 00:00:00'), pd.Timedelta('0 days 00:00:00'), 1.25, pd.Timedelta('2 days 08:00:00'), pd.Timedelta('2 days 08:00:00'), pd.Timedelta('2 days 08:00:00'), pd.Timedelta('2 days 08:00:00'), pd.Timedelta('0 days 00:00:00') ], index=stats_index, name='agg_func_mean' ) ) pd.testing.assert_series_equal( ranges.stats(column='a'), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-06 00:00:00'), pd.Timedelta('6 days 00:00:00'), pd.Timedelta('3 days 00:00:00'), pd.Timedelta('0 days 00:00:00'), 3, pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), pd.Timedelta('0 days 00:00:00') ], index=stats_index, name='a' ) ) pd.testing.assert_series_equal( ranges.stats(column='g1', group_by=group_by), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-06 00:00:00'), pd.Timedelta('6 days 00:00:00'), pd.Timedelta('5 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), 4, pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), pd.Timedelta('3 days 00:00:00'), pd.Timedelta('1 days 12:00:00'), pd.Timedelta('1 days 00:00:00') ], index=stats_index, name='g1' ) ) pd.testing.assert_series_equal( ranges['c'].stats(), ranges.stats(column='c') ) pd.testing.assert_series_equal( ranges['c'].stats(), ranges.stats(column='c', group_by=False) ) pd.testing.assert_series_equal( ranges_grouped['g2'].stats(), ranges_grouped.stats(column='g2') ) pd.testing.assert_series_equal( ranges_grouped['g2'].stats(), ranges.stats(column='g2', group_by=group_by) ) stats_df = ranges.stats(agg_func=None) assert stats_df.shape == (4, 11) pd.testing.assert_index_equal(stats_df.index, ranges.wrapper.columns) pd.testing.assert_index_equal(stats_df.columns, stats_index) # ############# drawdowns.py ############# # ts2 = pd.DataFrame({ 'a': [2, 1, 3, 1, 4, 1], 'b': [1, 2, 1, 3, 1, 4], 'c': [1, 2, 3, 2, 1, 2], 'd': [1, 2, 3, 4, 5, 6] }, index=[ datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4), datetime(2020, 1, 5), datetime(2020, 1, 6) ]) drawdowns = vbt.Drawdowns.from_ts(ts2, wrapper_kwargs=dict(freq='1 days')) drawdowns_grouped = vbt.Drawdowns.from_ts(ts2, wrapper_kwargs=dict(freq='1 days', group_by=group_by)) class TestDrawdowns: def test_mapped_fields(self): for name in drawdown_dt.names: np.testing.assert_array_equal( getattr(drawdowns, name).values, drawdowns.values[name] ) def test_ts(self): pd.testing.assert_frame_equal( drawdowns.ts, ts2 ) pd.testing.assert_series_equal( drawdowns['a'].ts, ts2['a'] ) pd.testing.assert_frame_equal( drawdowns_grouped['g1'].ts, ts2[['a', 'b']] ) assert drawdowns.replace(ts=None)['a'].ts is None def test_from_ts(self): record_arrays_close( drawdowns.values, np.array([ (0, 0, 0, 1, 1, 2, 2.0, 1.0, 3.0, 1), (1, 0, 2, 3, 3, 4, 3.0, 1.0, 4.0, 1), (2, 0, 4, 5, 5, 5, 4.0, 1.0, 1.0, 0), (3, 1, 1, 2, 2, 3, 2.0, 1.0, 3.0, 1), (4, 1, 3, 4, 4, 5, 3.0, 1.0, 4.0, 1), (5, 2, 2, 3, 4, 5, 3.0, 1.0, 2.0, 0) ], dtype=drawdown_dt) ) assert drawdowns.wrapper.freq == day_dt pd.testing.assert_index_equal( drawdowns_grouped.wrapper.grouper.group_by, group_by ) def test_records_readable(self): records_readable = drawdowns.records_readable np.testing.assert_array_equal( records_readable['Drawdown Id'].values, np.array([ 0, 1, 2, 3, 4, 5 ]) ) np.testing.assert_array_equal( records_readable['Column'].values, np.array([ 'a', 'a', 'a', 'b', 'b', 'c' ]) ) np.testing.assert_array_equal( records_readable['Peak Timestamp'].values, np.array([ '2020-01-01T00:00:00.000000000', '2020-01-03T00:00:00.000000000', '2020-01-05T00:00:00.000000000', '2020-01-02T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-03T00:00:00.000000000' ], dtype='datetime64[ns]') ) np.testing.assert_array_equal( records_readable['Start Timestamp'].values, np.array([ '2020-01-02T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-03T00:00:00.000000000', '2020-01-05T00:00:00.000000000', '2020-01-04T00:00:00.000000000' ], dtype='datetime64[ns]') ) np.testing.assert_array_equal( records_readable['Valley Timestamp'].values, np.array([ '2020-01-02T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-03T00:00:00.000000000', '2020-01-05T00:00:00.000000000', '2020-01-05T00:00:00.000000000' ], dtype='datetime64[ns]') ) np.testing.assert_array_equal( records_readable['End Timestamp'].values, np.array([ '2020-01-03T00:00:00.000000000', '2020-01-05T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-06T00:00:00.000000000' ], dtype='datetime64[ns]') ) np.testing.assert_array_equal( records_readable['Peak Value'].values, np.array([ 2., 3., 4., 2., 3., 3. ]) ) np.testing.assert_array_equal( records_readable['Valley Value'].values, np.array([ 1., 1., 1., 1., 1., 1. ]) ) np.testing.assert_array_equal( records_readable['End Value'].values, np.array([ 3., 4., 1., 3., 4., 2. ]) ) np.testing.assert_array_equal( records_readable['Status'].values, np.array([ 'Recovered', 'Recovered', 'Active', 'Recovered', 'Recovered', 'Active' ]) ) def test_drawdown(self): np.testing.assert_array_almost_equal( drawdowns['a'].drawdown.values, np.array([-0.5, -0.66666667, -0.75]) ) np.testing.assert_array_almost_equal( drawdowns.drawdown.values, np.array([-0.5, -0.66666667, -0.75, -0.5, -0.66666667, -0.66666667]) ) pd.testing.assert_frame_equal( drawdowns.drawdown.to_pd(), pd.DataFrame( np.array([ [np.nan, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, np.nan], [-0.5, np.nan, np.nan, np.nan], [np.nan, -0.5, np.nan, np.nan], [-0.66666669, np.nan, np.nan, np.nan], [-0.75, -0.66666669, -0.66666669, np.nan] ]), index=ts2.index, columns=ts2.columns ) ) def test_avg_drawdown(self): assert drawdowns['a'].avg_drawdown() == -0.6388888888888888 pd.testing.assert_series_equal( drawdowns.avg_drawdown(), pd.Series( np.array([-0.63888889, -0.58333333, -0.66666667, np.nan]), index=wrapper.columns ).rename('avg_drawdown') ) pd.testing.assert_series_equal( drawdowns_grouped.avg_drawdown(), pd.Series( np.array([-0.6166666666666666, -0.6666666666666666]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('avg_drawdown') ) def test_max_drawdown(self): assert drawdowns['a'].max_drawdown() == -0.75 pd.testing.assert_series_equal( drawdowns.max_drawdown(), pd.Series( np.array([-0.75, -0.66666667, -0.66666667, np.nan]), index=wrapper.columns ).rename('max_drawdown') ) pd.testing.assert_series_equal( drawdowns_grouped.max_drawdown(), pd.Series( np.array([-0.75, -0.6666666666666666]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('max_drawdown') ) def test_recovery_return(self): np.testing.assert_array_almost_equal( drawdowns['a'].recovery_return.values, np.array([2., 3., 0.]) ) np.testing.assert_array_almost_equal( drawdowns.recovery_return.values, np.array([2., 3., 0., 2., 3., 1.]) ) pd.testing.assert_frame_equal( drawdowns.recovery_return.to_pd(), pd.DataFrame( np.array([ [np.nan, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, np.nan], [2.0, np.nan, np.nan, np.nan], [np.nan, 2.0, np.nan, np.nan], [3.0, np.nan, np.nan, np.nan], [0.0, 3.0, 1.0, np.nan] ]), index=ts2.index, columns=ts2.columns ) ) def test_avg_recovery_return(self): assert drawdowns['a'].avg_recovery_return() == 1.6666666666666667 pd.testing.assert_series_equal( drawdowns.avg_recovery_return(), pd.Series( np.array([1.6666666666666667, 2.5, 1.0, np.nan]), index=wrapper.columns ).rename('avg_recovery_return') ) pd.testing.assert_series_equal( drawdowns_grouped.avg_recovery_return(), pd.Series( np.array([2.0, 1.0]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('avg_recovery_return') ) def test_max_recovery_return(self): assert drawdowns['a'].max_recovery_return() == 3.0 pd.testing.assert_series_equal( drawdowns.max_recovery_return(), pd.Series( np.array([3.0, 3.0, 1.0, np.nan]), index=wrapper.columns ).rename('max_recovery_return') ) pd.testing.assert_series_equal( drawdowns_grouped.max_recovery_return(), pd.Series( np.array([3.0, 1.0]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('max_recovery_return') ) def test_duration(self): np.testing.assert_array_almost_equal( drawdowns['a'].duration.values, np.array([1, 1, 1]) ) np.testing.assert_array_almost_equal( drawdowns.duration.values, np.array([1, 1, 1, 1, 1, 3]) ) def test_avg_duration(self): assert drawdowns['a'].avg_duration() == pd.Timedelta('1 days 00:00:00') pd.testing.assert_series_equal( drawdowns.avg_duration(), pd.Series( np.array([86400000000000, 86400000000000, 259200000000000, 'NaT'], dtype='timedelta64[ns]'), index=wrapper.columns ).rename('avg_duration') ) pd.testing.assert_series_equal( drawdowns_grouped.avg_duration(), pd.Series( np.array([86400000000000, 259200000000000], dtype='timedelta64[ns]'), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('avg_duration') ) def test_max_duration(self): assert drawdowns['a'].max_duration() == pd.Timedelta('1 days 00:00:00') pd.testing.assert_series_equal( drawdowns.max_duration(), pd.Series( np.array([86400000000000, 86400000000000, 259200000000000, 'NaT'], dtype='timedelta64[ns]'), index=wrapper.columns ).rename('max_duration') ) pd.testing.assert_series_equal( drawdowns_grouped.max_duration(), pd.Series( np.array([86400000000000, 259200000000000], dtype='timedelta64[ns]'), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('max_duration') ) def test_coverage(self): assert drawdowns['a'].coverage() == 0.5 pd.testing.assert_series_equal( drawdowns.coverage(), pd.Series( np.array([0.5, 0.3333333333333333, 0.5, np.nan]), index=ts2.columns ).rename('coverage') ) pd.testing.assert_series_equal( drawdowns_grouped.coverage(), pd.Series( np.array([0.4166666666666667, 0.25]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('coverage') ) def test_decline_duration(self): np.testing.assert_array_almost_equal( drawdowns['a'].decline_duration.values, np.array([1., 1., 1.]) ) np.testing.assert_array_almost_equal( drawdowns.decline_duration.values, np.array([1., 1., 1., 1., 1., 2.]) ) def test_recovery_duration(self): np.testing.assert_array_almost_equal( drawdowns['a'].recovery_duration.values, np.array([1, 1, 0]) ) np.testing.assert_array_almost_equal( drawdowns.recovery_duration.values, np.array([1, 1, 0, 1, 1, 1]) ) def test_recovery_duration_ratio(self): np.testing.assert_array_almost_equal( drawdowns['a'].recovery_duration_ratio.values, np.array([1., 1., 0.]) ) np.testing.assert_array_almost_equal( drawdowns.recovery_duration_ratio.values, np.array([1., 1., 0., 1., 1., 0.5]) ) def test_active_records(self): assert isinstance(drawdowns.active, vbt.Drawdowns) assert drawdowns.active.wrapper == drawdowns.wrapper record_arrays_close( drawdowns['a'].active.values, np.array([ (2, 0, 4, 5, 5, 5, 4., 1., 1., 0) ], dtype=drawdown_dt) ) record_arrays_close( drawdowns['a'].active.values, drawdowns.active['a'].values ) record_arrays_close( drawdowns.active.values, np.array([ (2, 0, 4, 5, 5, 5, 4.0, 1.0, 1.0, 0), (5, 2, 2, 3, 4, 5, 3.0, 1.0, 2.0, 0) ], dtype=drawdown_dt) ) def test_recovered_records(self): assert isinstance(drawdowns.recovered, vbt.Drawdowns) assert drawdowns.recovered.wrapper == drawdowns.wrapper record_arrays_close( drawdowns['a'].recovered.values, np.array([ (0, 0, 0, 1, 1, 2, 2.0, 1.0, 3.0, 1), (1, 0, 2, 3, 3, 4, 3.0, 1.0, 4.0, 1) ], dtype=drawdown_dt) ) record_arrays_close( drawdowns['a'].recovered.values, drawdowns.recovered['a'].values ) record_arrays_close( drawdowns.recovered.values, np.array([ (0, 0, 0, 1, 1, 2, 2.0, 1.0, 3.0, 1), (1, 0, 2, 3, 3, 4, 3.0, 1.0, 4.0, 1), (3, 1, 1, 2, 2, 3, 2.0, 1.0, 3.0, 1), (4, 1, 3, 4, 4, 5, 3.0, 1.0, 4.0, 1) ], dtype=drawdown_dt) ) def test_active_drawdown(self): assert drawdowns['a'].active_drawdown() == -0.75 pd.testing.assert_series_equal( drawdowns.active_drawdown(), pd.Series( np.array([-0.75, np.nan, -0.3333333333333333, np.nan]), index=wrapper.columns ).rename('active_drawdown') ) with pytest.raises(Exception): drawdowns_grouped.active_drawdown() def test_active_duration(self): assert drawdowns['a'].active_duration() == np.timedelta64(86400000000000) pd.testing.assert_series_equal( drawdowns.active_duration(), pd.Series( np.array([86400000000000, 'NaT', 259200000000000, 'NaT'], dtype='timedelta64[ns]'), index=wrapper.columns ).rename('active_duration') ) with pytest.raises(Exception): drawdowns_grouped.active_duration() def test_active_recovery(self): assert drawdowns['a'].active_recovery() == 0. pd.testing.assert_series_equal( drawdowns.active_recovery(), pd.Series( np.array([0., np.nan, 0.5, np.nan]), index=wrapper.columns ).rename('active_recovery') ) with pytest.raises(Exception): drawdowns_grouped.active_recovery() def test_active_recovery_return(self): assert drawdowns['a'].active_recovery_return() == 0. pd.testing.assert_series_equal( drawdowns.active_recovery_return(), pd.Series( np.array([0., np.nan, 1., np.nan]), index=wrapper.columns ).rename('active_recovery_return') ) with pytest.raises(Exception): drawdowns_grouped.active_recovery_return() def test_active_recovery_duration(self): assert drawdowns['a'].active_recovery_duration() == pd.Timedelta('0 days 00:00:00') pd.testing.assert_series_equal( drawdowns.active_recovery_duration(), pd.Series( np.array([0, 'NaT', 86400000000000, 'NaT'], dtype='timedelta64[ns]'), index=wrapper.columns ).rename('active_recovery_duration') ) with pytest.raises(Exception): drawdowns_grouped.active_recovery_duration() def test_stats(self): stats_index = pd.Index([ 'Start', 'End', 'Period', 'Coverage [%]', 'Total Records', 'Total Recovered Drawdowns', 'Total Active Drawdowns', 'Active Drawdown [%]', 'Active Duration', 'Active Recovery [%]', 'Active Recovery Return [%]', 'Active Recovery Duration', 'Max Drawdown [%]', 'Avg Drawdown [%]', 'Max Drawdown Duration', 'Avg Drawdown Duration', 'Max Recovery Return [%]', 'Avg Recovery Return [%]', 'Max Recovery Duration', 'Avg Recovery Duration', 'Avg Recovery Duration Ratio' ], dtype='object') pd.testing.assert_series_equal( drawdowns.stats(), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-06 00:00:00'), pd.Timedelta('6 days 00:00:00'), 44.444444444444436, 1.5, 1.0, 0.5, 54.166666666666664, pd.Timedelta('2 days 00:00:00'), 25.0, 50.0, pd.Timedelta('0 days 12:00:00'), 66.66666666666666, 58.33333333333333, pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), 300.0, 250.0, pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), 1.0 ], index=stats_index, name='agg_func_mean' ) ) pd.testing.assert_series_equal( drawdowns.stats(settings=dict(incl_active=True)), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-06 00:00:00'), pd.Timedelta('6 days 00:00:00'), 44.444444444444436, 1.5, 1.0, 0.5, 54.166666666666664, pd.Timedelta('2 days 00:00:00'), 25.0, 50.0, pd.Timedelta('0 days 12:00:00'), 69.44444444444444, 62.962962962962955, pd.Timedelta('1 days 16:00:00'), pd.Timedelta('1 days 16:00:00'), 300.0, 250.0, pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), 1.0 ], index=stats_index, name='agg_func_mean' ) ) pd.testing.assert_series_equal( drawdowns.stats(column='a'), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-06 00:00:00'), pd.Timedelta('6 days 00:00:00'), 50.0, 3, 2, 1, 75.0, pd.Timedelta('1 days 00:00:00'), 0.0, 0.0, pd.Timedelta('0 days 00:00:00'), 66.66666666666666, 58.33333333333333, pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), 300.0, 250.0, pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), 1.0 ], index=stats_index, name='a' ) ) pd.testing.assert_series_equal( drawdowns.stats(column='g1', group_by=group_by), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-06 00:00:00'), pd.Timedelta('6 days 00:00:00'), 41.66666666666667, 5, 4, 1, 66.66666666666666, 58.33333333333333, pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), 300.0, 250.0, pd.Timedelta('1 days 00:00:00'), pd.Timedelta('1 days 00:00:00'), 1.0 ], index=pd.Index([ 'Start', 'End', 'Period', 'Coverage [%]', 'Total Records', 'Total Recovered Drawdowns', 'Total Active Drawdowns', 'Max Drawdown [%]', 'Avg Drawdown [%]', 'Max Drawdown Duration', 'Avg Drawdown Duration', 'Max Recovery Return [%]', 'Avg Recovery Return [%]', 'Max Recovery Duration', 'Avg Recovery Duration', 'Avg Recovery Duration Ratio' ], dtype='object'), name='g1' ) ) pd.testing.assert_series_equal( drawdowns['c'].stats(), drawdowns.stats(column='c') ) pd.testing.assert_series_equal( drawdowns['c'].stats(), drawdowns.stats(column='c', group_by=False) ) pd.testing.assert_series_equal( drawdowns_grouped['g2'].stats(), drawdowns_grouped.stats(column='g2') ) pd.testing.assert_series_equal( drawdowns_grouped['g2'].stats(), drawdowns.stats(column='g2', group_by=group_by) ) stats_df = drawdowns.stats(agg_func=None) assert stats_df.shape == (4, 21) pd.testing.assert_index_equal(stats_df.index, drawdowns.wrapper.columns) pd.testing.assert_index_equal(stats_df.columns, stats_index) # ############# orders.py ############# # close = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=[ datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4), datetime(2020, 1, 5), datetime(2020, 1, 6), datetime(2020, 1, 7), datetime(2020, 1, 8) ]).vbt.tile(4, keys=['a', 'b', 'c', 'd']) size = np.full(close.shape, np.nan, dtype=np.float_) size[:, 0] = [1, 0.1, -1, -0.1, np.nan, 1, -1, 2] size[:, 1] = [-1, -0.1, 1, 0.1, np.nan, -1, 1, -2] size[:, 2] = [1, 0.1, -1, -0.1, np.nan, 1, -2, 2] orders = vbt.Portfolio.from_orders(close, size, fees=0.01, freq='1 days').orders orders_grouped = orders.regroup(group_by) class TestOrders: def test_mapped_fields(self): for name in order_dt.names: np.testing.assert_array_equal( getattr(orders, name).values, orders.values[name] ) def test_close(self): pd.testing.assert_frame_equal( orders.close, close ) pd.testing.assert_series_equal( orders['a'].close, close['a'] ) pd.testing.assert_frame_equal( orders_grouped['g1'].close, close[['a', 'b']] ) assert orders.replace(close=None)['a'].close is None def test_records_readable(self): records_readable = orders.records_readable np.testing.assert_array_equal( records_readable['Order Id'].values, np.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]) ) np.testing.assert_array_equal( records_readable['Timestamp'].values, np.array([ '2020-01-01T00:00:00.000000000', '2020-01-02T00:00:00.000000000', '2020-01-03T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-07T00:00:00.000000000', '2020-01-08T00:00:00.000000000', '2020-01-01T00:00:00.000000000', '2020-01-02T00:00:00.000000000', '2020-01-03T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-07T00:00:00.000000000', '2020-01-08T00:00:00.000000000', '2020-01-01T00:00:00.000000000', '2020-01-02T00:00:00.000000000', '2020-01-03T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-07T00:00:00.000000000', '2020-01-08T00:00:00.000000000' ], dtype='datetime64[ns]') ) np.testing.assert_array_equal( records_readable['Column'].values, np.array([ 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c' ]) ) np.testing.assert_array_equal( records_readable['Size'].values, np.array([ 1.0, 0.1, 1.0, 0.1, 1.0, 1.0, 2.0, 1.0, 0.1, 1.0, 0.1, 1.0, 1.0, 2.0, 1.0, 0.1, 1.0, 0.1, 1.0, 2.0, 2.0 ]) ) np.testing.assert_array_equal( records_readable['Price'].values, np.array([ 1.0, 2.0, 3.0, 4.0, 6.0, 7.0, 8.0, 1.0, 2.0, 3.0, 4.0, 6.0, 7.0, 8.0, 1.0, 2.0, 3.0, 4.0, 6.0, 7.0, 8.0 ]) ) np.testing.assert_array_equal( records_readable['Fees'].values, np.array([ 0.01, 0.002, 0.03, 0.004, 0.06, 0.07, 0.16, 0.01, 0.002, 0.03, 0.004, 0.06, 0.07, 0.16, 0.01, 0.002, 0.03, 0.004, 0.06, 0.14, 0.16 ]) ) np.testing.assert_array_equal( records_readable['Side'].values, np.array([ 'Buy', 'Buy', 'Sell', 'Sell', 'Buy', 'Sell', 'Buy', 'Sell', 'Sell', 'Buy', 'Buy', 'Sell', 'Buy', 'Sell', 'Buy', 'Buy', 'Sell', 'Sell', 'Buy', 'Sell', 'Buy' ]) ) def test_buy_records(self): assert isinstance(orders.buy, vbt.Orders) assert orders.buy.wrapper == orders.wrapper record_arrays_close( orders['a'].buy.values, np.array([ (0, 0, 0, 1., 1., 0.01, 0), (1, 0, 1, 0.1, 2., 0.002, 0), (4, 0, 5, 1., 6., 0.06, 0), (6, 0, 7, 2., 8., 0.16, 0) ], dtype=order_dt) ) record_arrays_close( orders['a'].buy.values, orders.buy['a'].values ) record_arrays_close( orders.buy.values, np.array([ (0, 0, 0, 1., 1., 0.01, 0), (1, 0, 1, 0.1, 2., 0.002, 0), (4, 0, 5, 1., 6., 0.06, 0), (6, 0, 7, 2., 8., 0.16, 0), (9, 1, 2, 1., 3., 0.03, 0), (10, 1, 3, 0.1, 4., 0.004, 0), (12, 1, 6, 1., 7., 0.07, 0), (14, 2, 0, 1., 1., 0.01, 0), (15, 2, 1, 0.1, 2., 0.002, 0), (18, 2, 5, 1., 6., 0.06, 0), (20, 2, 7, 2., 8., 0.16, 0) ], dtype=order_dt) ) def test_sell_records(self): assert isinstance(orders.sell, vbt.Orders) assert orders.sell.wrapper == orders.wrapper record_arrays_close( orders['a'].sell.values, np.array([ (2, 0, 2, 1., 3., 0.03, 1), (3, 0, 3, 0.1, 4., 0.004, 1), (5, 0, 6, 1., 7., 0.07, 1) ], dtype=order_dt) ) record_arrays_close( orders['a'].sell.values, orders.sell['a'].values ) record_arrays_close( orders.sell.values, np.array([ (2, 0, 2, 1., 3., 0.03, 1), (3, 0, 3, 0.1, 4., 0.004, 1), (5, 0, 6, 1., 7., 0.07, 1), (7, 1, 0, 1., 1., 0.01, 1), (8, 1, 1, 0.1, 2., 0.002, 1), (11, 1, 5, 1., 6., 0.06, 1), (13, 1, 7, 2., 8., 0.16, 1), (16, 2, 2, 1., 3., 0.03, 1), (17, 2, 3, 0.1, 4., 0.004, 1), (19, 2, 6, 2., 7., 0.14, 1) ], dtype=order_dt) ) def test_stats(self): stats_index = pd.Index([ 'Start', 'End', 'Period', 'Total Records', 'Total Buy Orders', 'Total Sell Orders', 'Min Size', 'Max Size', 'Avg Size', 'Avg Buy Size', 'Avg Sell Size', 'Avg Buy Price', 'Avg Sell Price', 'Total Fees', 'Min Fees', 'Max Fees', 'Avg Fees', 'Avg Buy Fees', 'Avg Sell Fees' ], dtype='object') pd.testing.assert_series_equal( orders.stats(), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'), pd.Timedelta('8 days 00:00:00'), 5.25, 2.75, 2.5, 0.10000000000000002, 2.0, 0.9333333333333335, 0.9166666666666666, 0.9194444444444446, 4.388888888888889, 4.527777777777779, 0.26949999999999996, 0.002, 0.16, 0.051333333333333335, 0.050222222222222224, 0.050222222222222224 ], index=stats_index, name='agg_func_mean' ) ) pd.testing.assert_series_equal( orders.stats(column='a'), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'), pd.Timedelta('8 days 00:00:00'), 7, 4, 3, 0.1, 2.0, 0.8857142857142858, 1.025, 0.7000000000000001, 4.25, 4.666666666666667, 0.33599999999999997, 0.002, 0.16, 0.047999999999999994, 0.057999999999999996, 0.03466666666666667 ], index=stats_index, name='a' ) ) pd.testing.assert_series_equal( orders.stats(column='g1', group_by=group_by), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'), pd.Timedelta('8 days 00:00:00'), 14, 7, 7, 0.1, 2.0, 0.8857142857142858, 0.8857142857142856, 0.8857142857142858, 4.428571428571429, 4.428571428571429, 0.672, 0.002, 0.16, 0.048, 0.048, 0.047999999999999994 ], index=stats_index, name='g1' ) ) pd.testing.assert_series_equal( orders['c'].stats(), orders.stats(column='c') ) pd.testing.assert_series_equal( orders['c'].stats(), orders.stats(column='c', group_by=False) ) pd.testing.assert_series_equal( orders_grouped['g2'].stats(), orders_grouped.stats(column='g2') ) pd.testing.assert_series_equal( orders_grouped['g2'].stats(), orders.stats(column='g2', group_by=group_by) ) stats_df = orders.stats(agg_func=None) assert stats_df.shape == (4, 19) pd.testing.assert_index_equal(stats_df.index, orders.wrapper.columns) pd.testing.assert_index_equal(stats_df.columns, stats_index) # ############# trades.py ############# # exit_trades = vbt.ExitTrades.from_orders(orders) exit_trades_grouped = vbt.ExitTrades.from_orders(orders_grouped) class TestExitTrades: def test_mapped_fields(self): for name in trade_dt.names: if name == 'return': np.testing.assert_array_equal( getattr(exit_trades, 'returns').values, exit_trades.values[name] ) else: np.testing.assert_array_equal( getattr(exit_trades, name).values, exit_trades.values[name] ) def test_close(self): pd.testing.assert_frame_equal( exit_trades.close, close ) pd.testing.assert_series_equal( exit_trades['a'].close, close['a'] ) pd.testing.assert_frame_equal( exit_trades_grouped['g1'].close, close[['a', 'b']] ) assert exit_trades.replace(close=None)['a'].close is None def test_records_arr(self): record_arrays_close( exit_trades.values, np.array([ (0, 0, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 0), (1, 0, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 0), (2, 0, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 1), (3, 0, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 0, 0, 2), (4, 1, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, -1.95, -1.7875, 1, 1, 3), (5, 1, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, -0.296, -2.71333333, 1, 1, 3), (6, 1, 1., 5, 6., 0.06, 6, 7., 0.07, -1.13, -0.18833333, 1, 1, 4), (7, 1, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 1, 0, 5), (8, 2, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 6), (9, 2, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 6), (10, 2, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 7), (11, 2, 1., 6, 7., 0.07, 7, 8., 0.08, -1.15, -0.16428571, 1, 1, 8), (12, 2, 1., 7, 8., 0.08, 7, 8., 0., -0.08, -0.01, 0, 0, 9) ], dtype=trade_dt) ) reversed_col_orders = orders.replace(records_arr=np.concatenate(( orders.values[orders.values['col'] == 2], orders.values[orders.values['col'] == 1], orders.values[orders.values['col'] == 0] ))) record_arrays_close( vbt.ExitTrades.from_orders(reversed_col_orders).values, exit_trades.values ) def test_records_readable(self): records_readable = exit_trades.records_readable np.testing.assert_array_equal( records_readable['Exit Trade Id'].values, np.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]) ) np.testing.assert_array_equal( records_readable['Column'].values, np.array([ 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c' ]) ) np.testing.assert_array_equal( records_readable['Size'].values, np.array([ 1.0, 0.10000000000000009, 1.0, 2.0, 1.0, 0.10000000000000009, 1.0, 2.0, 1.0, 0.10000000000000009, 1.0, 1.0, 1.0 ]) ) np.testing.assert_array_equal( records_readable['Entry Timestamp'].values, np.array([ '2020-01-01T00:00:00.000000000', '2020-01-01T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-08T00:00:00.000000000', '2020-01-01T00:00:00.000000000', '2020-01-01T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-08T00:00:00.000000000', '2020-01-01T00:00:00.000000000', '2020-01-01T00:00:00.000000000', '2020-01-06T00:00:00.000000000', '2020-01-07T00:00:00.000000000', '2020-01-08T00:00:00.000000000' ], dtype='datetime64[ns]') ) np.testing.assert_array_equal( records_readable['Avg Entry Price'].values, np.array([ 1.0909090909090908, 1.0909090909090908, 6.0, 8.0, 1.0909090909090908, 1.0909090909090908, 6.0, 8.0, 1.0909090909090908, 1.0909090909090908, 6.0, 7.0, 8.0 ]) ) np.testing.assert_array_equal( records_readable['Entry Fees'].values, np.array([ 0.010909090909090908, 0.0010909090909090918, 0.06, 0.16, 0.010909090909090908, 0.0010909090909090918, 0.06, 0.16, 0.010909090909090908, 0.0010909090909090918, 0.06, 0.07, 0.08 ]) ) np.testing.assert_array_equal( records_readable['Exit Timestamp'].values, np.array([ '2020-01-03T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-07T00:00:00.000000000', '2020-01-08T00:00:00.000000000', '2020-01-03T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-07T00:00:00.000000000', '2020-01-08T00:00:00.000000000', '2020-01-03T00:00:00.000000000', '2020-01-04T00:00:00.000000000', '2020-01-07T00:00:00.000000000', '2020-01-08T00:00:00.000000000', '2020-01-08T00:00:00.000000000' ], dtype='datetime64[ns]') ) np.testing.assert_array_equal( records_readable['Avg Exit Price'].values, np.array([ 3.0, 4.0, 7.0, 8.0, 3.0, 4.0, 7.0, 8.0, 3.0, 4.0, 7.0, 8.0, 8.0 ]) ) np.testing.assert_array_equal( records_readable['Exit Fees'].values, np.array([ 0.03, 0.004, 0.07, 0.0, 0.03, 0.004, 0.07, 0.0, 0.03, 0.004, 0.07, 0.08, 0.0 ]) ) np.testing.assert_array_equal( records_readable['PnL'].values, np.array([ 1.8681818181818182, 0.2858181818181821, 0.8699999999999999, -0.16, -1.9500000000000002, -0.29600000000000026, -1.1300000000000001, -0.16, 1.8681818181818182, 0.2858181818181821, 0.8699999999999999, -1.1500000000000001, -0.08 ]) ) np.testing.assert_array_equal( records_readable['Return'].values, np.array([ 1.7125000000000001, 2.62, 0.145, -0.01, -1.7875000000000003, -2.7133333333333334, -0.18833333333333335, -0.01, 1.7125000000000001, 2.62, 0.145, -0.1642857142857143, -0.01 ]) ) np.testing.assert_array_equal( records_readable['Direction'].values, np.array([ 'Long', 'Long', 'Long', 'Long', 'Short', 'Short', 'Short', 'Short', 'Long', 'Long', 'Long', 'Short', 'Long' ]) ) np.testing.assert_array_equal( records_readable['Status'].values, np.array([ 'Closed', 'Closed', 'Closed', 'Open', 'Closed', 'Closed', 'Closed', 'Open', 'Closed', 'Closed', 'Closed', 'Closed', 'Open' ]) ) np.testing.assert_array_equal( records_readable['Position Id'].values, np.array([ 0, 0, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9 ]) ) def test_duration(self): np.testing.assert_array_almost_equal( exit_trades['a'].duration.values, np.array([2, 3, 1, 1]) ) np.testing.assert_array_almost_equal( exit_trades.duration.values, np.array([2, 3, 1, 1, 2, 3, 1, 1, 2, 3, 1, 1, 1]) ) def test_winning_records(self): assert isinstance(exit_trades.winning, vbt.ExitTrades) assert exit_trades.winning.wrapper == exit_trades.wrapper record_arrays_close( exit_trades['a'].winning.values, np.array([ (0, 0, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 0), (1, 0, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 0), (2, 0, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 1) ], dtype=trade_dt) ) record_arrays_close( exit_trades['a'].winning.values, exit_trades.winning['a'].values ) record_arrays_close( exit_trades.winning.values, np.array([ (0, 0, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 0), (1, 0, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 0), (2, 0, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 1), (8, 2, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 6), (9, 2, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 6), (10, 2, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 7) ], dtype=trade_dt) ) def test_losing_records(self): assert isinstance(exit_trades.losing, vbt.ExitTrades) assert exit_trades.losing.wrapper == exit_trades.wrapper record_arrays_close( exit_trades['a'].losing.values, np.array([ (3, 0, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 0, 0, 2) ], dtype=trade_dt) ) record_arrays_close( exit_trades['a'].losing.values, exit_trades.losing['a'].values ) record_arrays_close( exit_trades.losing.values, np.array([ (3, 0, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 0, 0, 2), (4, 1, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, -1.95, -1.7875, 1, 1, 3), (5, 1, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, -0.296, -2.71333333, 1, 1, 3), (6, 1, 1., 5, 6., 0.06, 6, 7., 0.07, -1.13, -0.18833333, 1, 1, 4), (7, 1, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 1, 0, 5), (11, 2, 1., 6, 7., 0.07, 7, 8., 0.08, -1.15, -0.16428571, 1, 1, 8), (12, 2, 1., 7, 8., 0.08, 7, 8., 0., -0.08, -0.01, 0, 0, 9) ], dtype=trade_dt) ) def test_win_rate(self): assert exit_trades['a'].win_rate() == 0.75 pd.testing.assert_series_equal( exit_trades.win_rate(), pd.Series( np.array([0.75, 0., 0.6, np.nan]), index=close.columns ).rename('win_rate') ) pd.testing.assert_series_equal( exit_trades_grouped.win_rate(), pd.Series( np.array([0.375, 0.6]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('win_rate') ) def test_winning_streak(self): np.testing.assert_array_almost_equal( exit_trades['a'].winning_streak.values, np.array([1, 2, 3, 0]) ) np.testing.assert_array_almost_equal( exit_trades.winning_streak.values, np.array([1, 2, 3, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0]) ) def test_losing_streak(self): np.testing.assert_array_almost_equal( exit_trades['a'].losing_streak.values, np.array([0, 0, 0, 1]) ) np.testing.assert_array_almost_equal( exit_trades.losing_streak.values, np.array([0, 0, 0, 1, 1, 2, 3, 4, 0, 0, 0, 1, 2]) ) def test_profit_factor(self): assert exit_trades['a'].profit_factor() == 18.9 pd.testing.assert_series_equal( exit_trades.profit_factor(), pd.Series( np.array([18.9, 0., 2.45853659, np.nan]), index=ts2.columns ).rename('profit_factor') ) pd.testing.assert_series_equal( exit_trades_grouped.profit_factor(), pd.Series( np.array([0.81818182, 2.45853659]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('profit_factor') ) def test_expectancy(self): assert exit_trades['a'].expectancy() == 0.716 pd.testing.assert_series_equal( exit_trades.expectancy(), pd.Series( np.array([0.716, -0.884, 0.3588, np.nan]), index=ts2.columns ).rename('expectancy') ) pd.testing.assert_series_equal( exit_trades_grouped.expectancy(), pd.Series( np.array([-0.084, 0.3588]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('expectancy') ) def test_sqn(self): assert exit_trades['a'].sqn() == 1.634155521947584 pd.testing.assert_series_equal( exit_trades.sqn(), pd.Series( np.array([1.63415552, -2.13007307, 0.71660403, np.nan]), index=ts2.columns ).rename('sqn') ) pd.testing.assert_series_equal( exit_trades_grouped.sqn(), pd.Series( np.array([-0.20404671, 0.71660403]), index=pd.Index(['g1', 'g2'], dtype='object') ).rename('sqn') ) def test_long_records(self): assert isinstance(exit_trades.long, vbt.ExitTrades) assert exit_trades.long.wrapper == exit_trades.wrapper record_arrays_close( exit_trades['a'].long.values, np.array([ (0, 0, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 0), (1, 0, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 0), (2, 0, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 1), (3, 0, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 0, 0, 2) ], dtype=trade_dt) ) record_arrays_close( exit_trades['a'].long.values, exit_trades.long['a'].values ) record_arrays_close( exit_trades.long.values, np.array([ (0, 0, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 0), (1, 0, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 0), (2, 0, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 1), (3, 0, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 0, 0, 2), (8, 2, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 6), (9, 2, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 6), (10, 2, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 7), (12, 2, 1., 7, 8., 0.08, 7, 8., 0., -0.08, -0.01, 0, 0, 9) ], dtype=trade_dt) ) def test_short_records(self): assert isinstance(exit_trades.short, vbt.ExitTrades) assert exit_trades.short.wrapper == exit_trades.wrapper record_arrays_close( exit_trades['a'].short.values, np.array([], dtype=trade_dt) ) record_arrays_close( exit_trades['a'].short.values, exit_trades.short['a'].values ) record_arrays_close( exit_trades.short.values, np.array([ (4, 1, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, -1.95, -1.7875, 1, 1, 3), (5, 1, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, -0.296, -2.71333333, 1, 1, 3), (6, 1, 1., 5, 6., 0.06, 6, 7., 0.07, -1.13, -0.18833333, 1, 1, 4), (7, 1, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 1, 0, 5), (11, 2, 1., 6, 7., 0.07, 7, 8., 0.08, -1.15, -0.16428571, 1, 1, 8) ], dtype=trade_dt) ) def test_open_records(self): assert isinstance(exit_trades.open, vbt.ExitTrades) assert exit_trades.open.wrapper == exit_trades.wrapper record_arrays_close( exit_trades['a'].open.values, np.array([ (3, 0, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 0, 0, 2) ], dtype=trade_dt) ) record_arrays_close( exit_trades['a'].open.values, exit_trades.open['a'].values ) record_arrays_close( exit_trades.open.values, np.array([ (3, 0, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 0, 0, 2), (7, 1, 2., 7, 8., 0.16, 7, 8., 0., -0.16, -0.01, 1, 0, 5), (12, 2, 1., 7, 8., 0.08, 7, 8., 0., -0.08, -0.01, 0, 0, 9) ], dtype=trade_dt) ) def test_closed_records(self): assert isinstance(exit_trades.closed, vbt.ExitTrades) assert exit_trades.closed.wrapper == exit_trades.wrapper record_arrays_close( exit_trades['a'].closed.values, np.array([ (0, 0, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 0), (1, 0, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 0), (2, 0, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 1) ], dtype=trade_dt) ) record_arrays_close( exit_trades['a'].closed.values, exit_trades.closed['a'].values ) record_arrays_close( exit_trades.closed.values, np.array([ (0, 0, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 0), (1, 0, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 0), (2, 0, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 1), (4, 1, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, -1.95, -1.7875, 1, 1, 3), (5, 1, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, -0.296, -2.71333333, 1, 1, 3), (6, 1, 1., 5, 6., 0.06, 6, 7., 0.07, -1.13, -0.18833333, 1, 1, 4), (8, 2, 1., 0, 1.09090909, 0.01090909, 2, 3., 0.03, 1.86818182, 1.7125, 0, 1, 6), (9, 2, 0.1, 0, 1.09090909, 0.00109091, 3, 4., 0.004, 0.28581818, 2.62, 0, 1, 6), (10, 2, 1., 5, 6., 0.06, 6, 7., 0.07, 0.87, 0.145, 0, 1, 7), (11, 2, 1., 6, 7., 0.07, 7, 8., 0.08, -1.15, -0.16428571, 1, 1, 8) ], dtype=trade_dt) ) def test_stats(self): stats_index = pd.Index([ 'Start', 'End', 'Period', 'First Trade Start', 'Last Trade End', 'Coverage', 'Overlap Coverage', 'Total Records', 'Total Long Trades', 'Total Short Trades', 'Total Closed Trades', 'Total Open Trades', 'Open Trade PnL', 'Win Rate [%]', 'Max Win Streak', 'Max Loss Streak', 'Best Trade [%]', 'Worst Trade [%]', 'Avg Winning Trade [%]', 'Avg Losing Trade [%]', 'Avg Winning Trade Duration', 'Avg Losing Trade Duration', 'Profit Factor', 'Expectancy', 'SQN' ], dtype='object') pd.testing.assert_series_equal( exit_trades.stats(), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'), pd.Timedelta('8 days 00:00:00'), pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'), pd.Timedelta('5 days 08:00:00'), pd.Timedelta('2 days 00:00:00'), 3.25, 2.0, 1.25, 2.5, 0.75, -0.1, 58.333333333333336, 2.0, 1.3333333333333333, 168.38888888888889, -91.08730158730158, 149.25, -86.3670634920635, pd.Timedelta('2 days 00:00:00'), pd.Timedelta('1 days 12:00:00'), np.inf, 0.11705555555555548, 0.18931590012681135 ], index=stats_index, name='agg_func_mean' ) ) pd.testing.assert_series_equal( exit_trades.stats(settings=dict(incl_open=True)), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'), pd.Timedelta('8 days 00:00:00'), pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'), pd.Timedelta('5 days 08:00:00'), pd.Timedelta('2 days 00:00:00'), 3.25, 2.0, 1.25, 2.5, 0.75, -0.1, 58.333333333333336, 2.0, 2.3333333333333335, 174.33333333333334, -96.25396825396825, 149.25, -42.39781746031746, pd.Timedelta('2 days 00:00:00'), pd.Timedelta('1 days 06:00:00'), 7.11951219512195, 0.06359999999999993, 0.07356215977397455 ], index=stats_index, name='agg_func_mean' ) ) pd.testing.assert_series_equal( exit_trades.stats(column='a'), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'), pd.Timedelta('8 days 00:00:00'), pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'), pd.Timedelta('5 days 00:00:00'), pd.Timedelta('2 days 00:00:00'), 4, 4, 0, 3, 1, -0.16, 100.0, 3, 0, 262.0, 14.499999999999998, 149.25, np.nan, pd.Timedelta('2 days 00:00:00'), pd.NaT, np.inf, 1.008, 2.181955050824476 ], index=stats_index, name='a' ) ) pd.testing.assert_series_equal( exit_trades.stats(column='g1', group_by=group_by), pd.Series([ pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2020-01-08 00:00:00'),
pd.Timedelta('8 days 00:00:00')
pandas.Timedelta
# Author: <NAME>, PhD # University of Los Angeles California import os import sys import re import tkinter as tk from tkinter import ttk from tkinter import filedialog import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib import pyplot as plt import numpy as np import pandas as pd import scipy.stats as stats from scipy import optimize from itertools import groupby # from https://gist.github.com/walkermatt/2871026 from threading import Timer def debounce(wait): """ Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked. """ def decorator(fn): def debounced(*args, **kwargs): def call_it(): fn(*args, **kwargs) try: debounced.t.cancel() except(AttributeError): pass debounced.t = Timer(wait, call_it) debounced.t.start() return debounced return decorator ############################################################################# # --------- Natural Abundance Correction CLASS -----------------------------# ############################################################################# class NAProcess: # Adapted from IsoCor code (https://github.com/MetaSys-LISBP/IsoCor) ################## ## Init and setup ################## def __init__(self, entry, atomTracer="H", purityTracer=[0, 1], FAMES=True, CHOL=False): self.NaturalAbundanceDistributions = self.__getNaturalAbundanceDistributions() self.formula = self.getFAFormulaString(entry, FAMES, CHOL) self.elementsDict = self.parseFormula(self.formula) self.atomTracer = atomTracer self.purityTracer = purityTracer self.correctionMatrix = self.computeCorrectionMatrix(self.elementsDict, self.atomTracer, self.NaturalAbundanceDistributions, purityTracer) def getFAFormulaString(self, entry, FAMES, CHOL=False): ''' Return formula string e.g.: C3H2O3''' regex = "C([0-9]+):([0-9]+)" carbon,doubleBond = [int(val) for val in re.findall(regex, entry)[0]] hydrogen = 3+(carbon-2)*2+1-2*doubleBond oxygen = 2 silicon = 0 if (FAMES): carbon=carbon+1 hydrogen=hydrogen-1+3 if (CHOL): carbon, hydrogen, oxygen, silicon = 30, 54, 1, 1 return "".join(["".join([letter,str(n)]) for [letter,n] in [ ["C", carbon], ["H", hydrogen], ["Si", silicon], ["O", oxygen]] if n>0]) def parseFormula(self, formula): """ Parse the elemental formula and return the number of each element in a dictionnary d={'El_1':x,'El_2':y,...}. """ regex = f"({'|'.join(self.NaturalAbundanceDistributions.keys())})([0-9]{{0,}})" elementDict = dict((element, 0) for element in self.NaturalAbundanceDistributions.keys()) for element,n in re.findall(regex, formula): if n: elementDict[element] += int(n) else: elementDict[element] += 1 return elementDict def __getNaturalAbundanceDistributions(self): '''Return a dictionary of the isotopic proportions at natural abundance desribed in https://www.ncbi.nlm.nih.gov/pubmed/27989585''' H1, H2 = 0.999885, 0.000115 C12, C13 = 0.9893, 0.0107 N14, N15 = 0.99632, 0.00368 O16, O17, O18 = 0.99757, 0.00038, 0.00205 Si28, Si29, Si30 = 0.922297, 0.046832, 0.030872 S32, S33, S34, S36 = 0.9493, 0.0076, 0.0429, 0.0002 return {'H': np.array([H1, H2]), # hydrogen 'C': np.array([C12, C13]), # carbon 'N': np.array([N14, N15]), # nitrogen 'O': np.array([O16, O17, O18]), # oxygen 'Si': np.array([Si28, Si29, Si30]), # silicon 'S': np.array([S32, S33, S34, S36])} # sulphur def __calculateMassDistributionVector(self, elementDict, atomTracer, NADistributions): """ Calculate a mass distribution vector (at natural abundancy), based on the elemental compositions of metabolite. The element corresponding to the isotopic tracer is not taken into account in the metabolite moiety. """ result = np.array([1.]) for atom,n in elementDict.items(): if atom not in [atomTracer]: for i in range(n): result = np.convolve(result, NADistributions[atom]) return result def computeCorrectionMatrix(self, elementDict, atomTracer, NADistributions, purityTracer): # calculate correction vector used for correction matrix construction # it corresponds to the mdv at natural abundance of all elements except the # isotopic tracer correctionVector = self.__calculateMassDistributionVector(elementDict, atomTracer, NADistributions) # check if the isotopic tracer is present in formula try: nAtomTracer = elementDict[atomTracer] except: print("The isotopic tracer must to be present in the metabolite formula!") tracerNADistribution = NADistributions[atomTracer] m = 1+nAtomTracer*(len(tracerNADistribution)-1) c = len(correctionVector) if m > c + nAtomTracer*(len(tracerNADistribution)-1): print("There might be a problem in matrix size.\nFragment does not contains enough atoms to generate this isotopic cluster.") if c < m: # padd with zeros correctionVector.resize(m) # create correction matrix correctionMatrix = np.zeros((m, nAtomTracer+1)) for i in range(nAtomTracer+1): column = correctionVector[:m] for na in range(i): column = np.convolve(column, purityTracer)[:m] for nb in range(nAtomTracer-i): column = np.convolve(column, tracerNADistribution)[:m] correctionMatrix[:,i] = column return correctionMatrix ################## ## Data processing ################## def _computeCost(self, currentMID, target, correctionMatrix): """ Cost function used for BFGS minimization. return : (sum(target - correctionMatrix * currentMID)^2, gradient) """ difference = target - np.dot(correctionMatrix, currentMID) # calculate sum of square differences and gradient return (np.dot(difference, difference), np.dot(correctionMatrix.transpose(), difference)*-2) def _minimizeCost(self, args): ''' Wrapper to perform least-squares optimization via the limited-memory Broyden-Fletcher-Goldfarb-Shanno algorithm, with an explicit lower boundary set to zero to eliminate any potential negative fractions. ''' costFunction, initialMID, target, correctionMatrix = args res = optimize.minimize(costFunction, initialMID, jac=True, args=(target, correctionMatrix), method='L-BFGS-B', bounds=[(0., float('inf'))]*len(initialMID), options={'gtol': 1e-10, 'eps': 1e-08, 'maxiter': 15000, 'ftol': 2.220446049250313e-09, 'maxcor': 10, 'maxfun': 15000}) return res def correctForNaturalAbundance(self, dataFrame, method="LSC"): ''' Correct the Mass Isotope Distributions (MID) from a given dataFrame. Method: SMC (skewed Matrix correction) / LSC (Least Squares Skewed Correction) ''' correctionMatrix = self.computeCorrectionMatrix(self.elementsDict, self.atomTracer, self.NaturalAbundanceDistributions, self.purityTracer) nRows, nCols = correctionMatrix.shape # ensure compatible sizes (will extend data) if nCols<dataFrame.shape[1]: print("The measure MID has more clusters than the correction matrix.") else: dfData = np.zeros((len(dataFrame), nCols)) dfData[:dataFrame.shape[0], :dataFrame.shape[1]] = dataFrame.values if method == "SMC": # will mltiply the data by inverse of the correction matrix correctionMatrix = np.linalg.pinv(correctionMatrix) correctedData = np.matmul(dfData, correctionMatrix.transpose()) # flatten unrealistic negative values to zero correctedData[correctedData<0] = 0 elif method == "LSC": # Prepare multiprocessing optimization targetMIDList = dfData.tolist() initialMID = np.zeros_like(targetMIDList[0]) argsList = [(self._computeCost, initialMID, targetMID, correctionMatrix) for targetMID in targetMIDList] # minimize for each MID allRes = [self._minimizeCost(args) for args in argsList] correctedData = np.vstack([res.x for res in allRes]) return pd.DataFrame(columns=dataFrame.columns, data=correctedData[:, :dataFrame.shape[1]]) ############################################################################# # --------- DATA OBJECT CLASS ----------------------------------------------# ############################################################################# class MSDataContainer: ################## ## Init and setup ################## def __init__(self, fileNames, internalRef="C19:0", tracer="H", tracerPurity=[0.00, 1.00]): assert len(fileNames)==2 , "You must choose 2 files!" self.internalRef = internalRef self._cholesterol = False self.tracer = tracer self.tracerPurity = tracerPurity self.NACMethod = "LSC" # least squares skewed matrix correction self.dataFileName, self.templateFileName = self.__getDataAndTemplateFileNames(fileNames) self._baseFileName = os.path.basename(self.dataFileName).split('.')[0] self.pathDirName = os.path.dirname(self.dataFileName) self.__regexExpression = {"Samples": '^(?!neg|S\d+$)', "colNames": '(\d+)_(\d+)(?:\.\d+)?_(\d+)'} self.dataDf = self._computeFileAttributes() self.__standardDf_template = self.__getStandardsTemplateDf() self.volumeMixTotal = 500 self.volumeMixForPrep = 100 self.volumeStandards = [1, 5, 10, 20, 40, 80] self.standardDf_nMoles = self.computeStandardMoles() # for normalization # volume (uL) in which the original sample was diluted samplesLoc = self.dataDf.SampleName.str.match(self.__regexExpression["Samples"], na=False) self.numberOfSamples = len(self.dataDf.loc[samplesLoc]) self.volumesOfDilution = [750]*self.numberOfSamples # volume (uL) of sample used in MS self.volumesOfSampleSoupUsed = [5]*self.numberOfSamples self.weightNormalization = False def __getDataAndTemplateFileNames(self, fileNames, templateKeyword="template"): '''Classify files (data or template) based on fileName''' dataFileName = [fileName for fileName in fileNames if templateKeyword not in fileName][0] templateFileName = [fileName for fileName in fileNames if fileName != dataFileName][0] return [dataFileName, templateFileName] def __parseIon(self, ion): ionID, ionMass, ionDescription = re.findall(self.__regexExpression["colNames"], ion)[0] return {"id": int(ionID), "mass": int(ionMass), "description": ionDescription} def __parseSampleColumns(self, columnNames): # indexed ions from columns ions = map(lambda name: self.__parseIon(name), columnNames) return list(ions)#[self.__getIndexedIon(ion, i) for i,ion in enumerate(ions)] def __isLabeledExperiment(self, ionsDetected): # if more than 40% of the ions are duplicate, it probably means that the file is # from a labeled experimnets (lots of fragments for each ion) ionsList = list(map(lambda ion: ion["description"], ionsDetected)) uniqueIons = set(ionsList) return len(uniqueIons)/len(ionsList) < 0.6 def __getIonParentedGroups(self, ionsDetected): # groupby parental ions (save initial index for sorting later) groupedIons = groupby(enumerate(ionsDetected), key=lambda ion: ion[1]['description']) groupsIntraSorted = list(map(lambda group: (group[0], sorted(group[1], key=lambda ion: ion[1]['mass'])), groupedIons)) # split groups if most abundant ion present finalGroups = [] for key,group in groupsIntraSorted: # only process groups that have more than 1 ion if len(group) != 1: masses = np.array([ion[1]["mass"] for ion in group]) differences = masses[1:]-masses[0:-1] idx = np.where(differences != 1) # and that have non unitary jumps in differences from ion to ion if len(idx[0])>0: start = 0 for i in range(len(idx[0])+1): if i < len(idx[0]): end = idx[0][i]+1 subgroup = group[start:end] start = idx[0][i] + 1 finalGroups.append((f"{key}-{i}", subgroup)) else: subgroup = group[start:] finalGroups.append((f"{key}-{i}", subgroup)) else: finalGroups.append((key, group)) else: finalGroups.append((key, group)) return finalGroups def _computeFileAttributes(self): # extract columns columnsOfInterest = pd.read_excel(self.dataFileName, nrows=2).filter(regex=self.__regexExpression["colNames"]).columns # load data and template files and isolate data part df = pd.read_excel(self.dataFileName, skiprows=1) templateMap =
pd.read_excel(self.templateFileName, sheet_name="MAP")
pandas.read_excel
## 1. Recap ## import pandas as pd loans = pd.read_csv("cleaned_loans_2007.csv") print(loans.info()) ## 3. Picking an error metric ## import pandas as pd # False positives. fp_filter = (predictions == 1) & (loans["loan_status"] == 0) fp = len(predictions[fp_filter]) # True positives. tp_filter = (predictions == 1) & (loans["loan_status"] == 1) tp = len(predictions[tp_filter]) # False negatives. fn_filter = (predictions == 0) & (loans["loan_status"] == 1) fn = len(predictions[fn_filter]) # True negatives tn_filter = (predictions == 0) & (loans["loan_status"] == 0) tn = len(predictions[tn_filter]) ## 5. Class imbalance ## import pandas as pd import numpy # Predict that all loans will be paid off on time. predictions = pd.Series(numpy.ones(loans.shape[0])) # False positives. fp_filter = (predictions == 1) & (loans["loan_status"] == 0) fp = len(predictions[fp_filter]) # True positives. tp_filter = (predictions == 1) & (loans["loan_status"] == 1) tp = len(predictions[tp_filter]) # False negatives. fn_filter = (predictions == 0) & (loans["loan_status"] == 1) fn = len(predictions[fn_filter]) # True negatives tn_filter = (predictions == 0) & (loans["loan_status"] == 0) tn = len(predictions[tn_filter]) # Rates tpr = tp / (tp + fn) fpr = fp / (fp + tn) print(tpr) print(fpr) ## 6. Logistic Regression ## from sklearn.linear_model import LogisticRegression lr = LogisticRegression() cols = loans.columns train_cols = cols.drop("loan_status") features = loans[train_cols] target = loans["loan_status"] lr.fit(features, target) predictions = lr.predict(features) ## 7. Cross Validation ## from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_predict lr = LogisticRegression() predictions = cross_val_predict(lr, features, target, cv=3) predictions =
pd.Series(predictions)
pandas.Series
# v 0.1.5 Oct 1 2020 import pandas as pd import numpy as np import shap import matplotlib.pyplot as plt import waterfall_chart class shapwaterfall: def __init__(self, Model, X_tng, X_sc, ref1, ref2, num_feature=5): self.Model = Model self.X_tng = X_tng self.X_sc = X_sc self.ref1 = ref1 self.ref2 = ref2 self.num_feature = num_feature # label names clients_to_show = [ref1, ref2] # Data Frame management if isinstance(X_sc, pd.DataFrame): X_v = X_sc else: X_v = pd.DataFrame(X_sc) if isinstance(X_tng, pd.DataFrame): X_t = X_tng else: X_t = pd.DataFrame(X_tng) # SHAP Values explainer = shap.TreeExplainer(Model, shap.sample(X_t, 100)) # Data data_for_prediction1 = X_v[(X_v.Reference == clients_to_show[0])] data_for_prediction1 = data_for_prediction1.drop('Reference', 1) data_for_prediction2 = X_v[(X_v.Reference == clients_to_show[1])] data_for_prediction2 = data_for_prediction2.drop('Reference', 1) # Insert a binary option to ensure order goes from lower to higher propensity if Model.predict_proba(data_for_prediction1)[:, 1] <= Model.predict_proba(data_for_prediction2)[:, 1]: frames = [data_for_prediction1, data_for_prediction2] else: frames = [data_for_prediction2, data_for_prediction1] clients_to_show = [ref2, ref1] # Computations for Waterfall Chart data_for_prediction = pd.concat(frames) data_for_prediction = pd.DataFrame(data_for_prediction) feature_names = data_for_prediction.columns.values shap_values = explainer.shap_values(data_for_prediction, check_additivity=False) Feat_contrib = pd.DataFrame(list(map(np.ravel, shap_values[1])), columns=feature_names) counter1 = len(Feat_contrib.columns) Feat_contrib['base_line_diff'] = Feat_contrib.sum(axis=1) Feat_contrib['prediction'] = Model.predict_proba(data_for_prediction)[:, 1] Feat_contrib['baseline'] = Feat_contrib.prediction - Feat_contrib.base_line_diff diff_df = pd.DataFrame( {'features': Feat_contrib.diff().iloc[1, :].index, 'contrib': Feat_contrib.diff().iloc[1, :].values})[ :counter1].sort_values(by='contrib', ascending=False).reset_index(drop=True) # Waterfall Chart plt.rcParams.update({'figure.figsize': (16, 12), 'figure.dpi': 100}) xlist = [[clients_to_show[0], 'Other {a} Features'.format(a=counter1-num_feature)], diff_df.features.tolist()[:num_feature]] xlist = [item for sublist in xlist for item in sublist] ylist = [[np.round(Feat_contrib.prediction[0], 6), np.round(diff_df.contrib[num_feature:].sum(), 6)], np.round(diff_df.contrib.tolist(), 6)[:num_feature]] ylist = [item for sublist in ylist for item in sublist] waterfall_df =
pd.DataFrame({"x_values": xlist, 'y_values': ylist})
pandas.DataFrame
""" This module is the main API used to create track collections """ # Standard library imports import copy import random import inspect import logging import itertools from typing import Any from typing import List from typing import Union from typing import Tuple from typing import Callable from dataclasses import dataclass, field, asdict # Third party imports import numpy as np import pandas as pd import networkx as nx # Local imports import spotify_flows.database as database from .login import login from .data_structures import ( EpisodeItem, SpotifyDataStructure, TrackItem, AudioFeaturesItem, ) from .tracks import get_track_id, read_track_from_id from .tracks import get_audio_features from .albums import get_album_id from .albums import get_album_songs from .podcasts import get_show_id from .podcasts import get_show_episodes from .user import get_all_saved_tracks from .user import get_recommendations_for_genre from .artists import get_artist_id from .artists import get_artist_albums from .artists import get_related_artists from .artists import get_artist_popular_songs from .playlists import get_playlist_id from .playlists import make_new_playlist from .playlists import get_playlist_tracks # Main body logger = logging.getLogger() class DatabaseNotLoaded(Exception): pass @dataclass class TrackCollection: """Class representing a collection of tracks. Can be chained together through a variety of defined methods.""" read_items_from_db = lambda id_, db: db.build_collection_from_collection_id(id_=id_) sp = login( scope="playlist-modify-private playlist-modify-public user-read-playback-position user-library-read" ) id_: str = "" info: SpotifyDataStructure = None _items: List[Any] = field(default_factory=list) _audio_features_enriched: bool = False def copy(self): return copy.copy(self) @property def _api_track_gen(self): yield from self._items @property def _db_track_gen(self): db = CollectionDatabase() return db.load_playlist(playlist_id=self.id_) @property def exist_in_db(self): db = CollectionDatabase() return db.playlist_exists(self.id_) if db.is_loaded() else False @property def items(self): if self._items: yield from self._items else: if self.id_: yield from self.item_gen() else: yield from iter(()) def item_gen(self): db = CollectionDatabase() if self.exist_in_db: yield from self._db_track_gen else: logger.info(f"Retrieving items via API") for track_dict in self._api_track_gen: track = TrackItem.from_dict(track_dict) if db.is_loaded(): db.add_track(track_item=track) yield track @classmethod def from_id(cls, id_: str): return cls(id_=id_) @classmethod def from_item(cls, id_: str, item: SpotifyDataStructure): return cls(id_=id_, info=item) @classmethod def from_db(cls, id_: str, db_path: str): db = database.SpotifyDatabase(db_path, op_table="table") items = cls.read_items_from_db(id_=id_, db=db) return TrackCollection(id_=id_, _items=items) @classmethod def from_name(cls, name: str): name = name.replace("_", " ") id_ = cls.func_get_id(name=name) return cls(id_=id_) def __str__(self) -> str: return "\n".join([str(item) for item in self.items]) def __add__(self, other: "TrackCollection") -> "TrackCollection": """Defines the addition of two collections. Items get concatenated. Returns: TrackCollection: Collection object with combined items """ def new_items(): yield from self.items yield from other.items enriched = (self._audio_features_enriched) and (other._audio_features_enriched) return TrackCollection( id_="", _items=new_items(), _audio_features_enriched=enriched ) def __radd__(self, other: "TrackCollection") -> "TrackCollection": """Used when building track collections from list of other track collections Returns: TrackCollection: Sum of two collections """ if other == 0: return self else: return self + other def __sub__(self, other: "TrackCollection") -> "TrackCollection": """Defines the substraction of two collections. Items from other get removed from items from self. Returns: TrackCollection: Collection object with modified items. """ other_items = list(other.items) def new_items(): for item in self.items: if item not in other_items: yield item enriched = self._audio_features_enriched return TrackCollection( id_="", _items=new_items(), _audio_features_enriched=enriched ) def __truediv__(self, other: "TrackCollection") -> "TrackCollection": """Defines the division of two collections. Returns: TrackCollection: Items are intersection of self and other """ other_items = list(other.items) def new_items(): for item in self.items: if item in other_items: yield item enriched = self._audio_features_enriched return TrackCollection( id_="", _items=new_items(), _audio_features_enriched=enriched ) def __mod__(self, other: "TrackCollection") -> "TrackCollection": """Defines the modulo of two collections Returns: TrackCollection: Items are alternates of self and other. """ def new_items(): for i, j in zip(self.items, other.items): yield i yield j enriched = (self._audio_features_enriched) and (other._audio_features_enriched) return TrackCollection(_items=new_items(), _audio_features_enriched=enriched) def to_dataframes(self) -> Tuple[pd.DataFrame]: """Transforms items into dataframes, used for storage in database. Returns: Tuple[pd.DataFrame]: Representation of items as dataframes """ # Enrich with audio features tracks = copy.copy(list(self.add_audio_features().items)) # Extract data album_artist = [ {"album_id": track.album.id, "artist_id": artist.id} for track in tracks for artist in track.album.artists ] all_tracks = [asdict(track) for track in tracks] all_audio_features = [ {"track_id": track["id"], **track["audio_features"]} for track in all_tracks ] all_albums = [asdict(track.album) for track in tracks] all_artists = [artist for album in all_albums for artist in album["artists"]] # Build dataframes df_all_artists = pd.DataFrame(all_artists) df_all_albums = pd.DataFrame(all_albums).drop(columns="artists") df_audio_features = pd.DataFrame(all_audio_features) df_all_tracks =
pd.DataFrame(all_tracks)
pandas.DataFrame
''' This script is to help with basic data preparation with the nuMoM2b dataset ''' import pandas as pd import numpy as np # location of the data in this repository (not saved to Github!) data_loc = './data/nuMoM2b_Dataset_NICHD Data Challenge.csv' # This does dummy variables for multiple columns # Here used for drug codes, but could be used for ICD codes # In health claims data (order does not matter) def encode_mult(df, cols, encode=None, base="V", cum=False, missing_drop=True): res_counts = [] if not encode: tot_encode = pd.unique(df[cols].values.ravel()) if missing_drop: check = pd.isnull(tot_encode) tot_encode = tot_encode[~check] else: tot_encode = encode var_names = [] for i,v in enumerate(tot_encode): var_name = base + str(i) res_count = (df[cols] == v).sum(axis=1) res_counts.append( res_count ) var_names.append(var_name) res_count_df = pd.concat(res_counts, axis=1) res_count_df.columns = var_names if cum: return res_count_df, list(tot_encode) else: return 1*(res_count_df > 0), list(tot_encode) # This function takes the recode dict and columns def recode_vars(codes, columns, data): data[columns] = data[columns].replace(codes) ####################################################### # These are the different variable sets ''' A09A03a - pre-term birth [784 yes] A09A03b - maternal hypertensive disorder [1464 yes] CBAC01 - neonatal morbidities (general) [1872 yes] 1 = yes 2 = no others = missing data pOUTCOME 1 Live birth 2 Stillbirth 3 Fetal demise < 20 weeks 4 Elective termination 5 Indicated termination D Don't know R Refused CMAJ01d1 - readmission infection 14 days CMAJ01d2 - readmission preclampsia CMAJ01d3 - readmission bleeding CMAJ01d4 - readmission depression CMAE04a1c - postpartum depression CBAB01 - Documented infection A09A03b3 - maternal hypertensive disorder - Preeclampsia/HELLP/eclampsia ''' outcomes = ['A09A03a','A09A03b','CBAC01','pOUTCOME', 'CMAJ01d1','CMAJ01d2','CMAJ01d3','CMAJ01d4', 'CMAE04a1c','CBAB01','A09A03b3'] ''' CMAE04 - mental health condition CMAE04a1a - depression prior CMAE04a2a - anxiety prior CMAE04a3a - bipolar prior CMAE04a4a - PTSD prior CMAE04a5a - Schizophrenia prior CMAE04a6a - treated for other mental health 0/1 (checked/not checked) ''' mental_health = ['CMAE04','CMAE04a1a','CMAE04a2a','CMAE04a3a', 'CMAE04a4a','CMAE04a5a','CMAE04a6a'] ''' CMAE03 - diabetes ever diagnosed (1 yes before, 2 yes during preg, 3 no) CMDA01 - hypertension prior 20 weeks CMDA02 - proteinuria (protein urine) prior 20 weeks [Yes = 1, No = 2] V1AD06 (V1A) Have you had any 'flu-like illnesses,' 'really bad colds,' fever, a rash, or any muscle or joint aches since you became pregnant? V1AD12a (V1A) Previous surgeries - Cervical surgery - Cone V1AD12b (V1A) Previous surgeries - Cervical surgery - LEEP V1AD12c (V1A) Previous surgeries - Cervical surgery - Cryotherapy V1AD12d (V1A) Previous surgeries - Myomectomy V1AD12e (V1A) Previous surgeries - Abdominal surgery excluding uterine surgery V1AD13 (V1A) Have you ever had a blood transfusion? [Yes = 1, No = 2] ''' health_cond = ['CMAE03','CMDA01','CMDA02','V1AD06','V1AD12a','V1AD12b', 'V1AD12c','V1AD12d','V1AD12e','V1AD13'] ''' V1AD14 (V1A) Do you use a continuous positive airway pressure (CPAP) or other breathing machine when you sleep? V1AD15 (V1A) Do you have asthma? V1AD15a (V1A) Are you currently using oral steroid tablets or liquids (such as prednisone, deltasone, orasone, prednisolone, prelone, medrol, or solumedrol) for treatment of asthma? V1AD15a1 (V1A) Asthma treatment - Did your doctor ask you to take this every day? V1AD15a2 (V1A) Asthma treatment - Did you start taking the steroid tablets or liquid more than 14 days ago? V1AD16 (V1A) Do you receive oxygen therapy, either during the day or at night, for any medical condition(s)? [Yes = 1, No = 2] ''' asthma = ['V1AD14','V1AD15','V1AD15a','V1AD15a1','V1AD15a2','V1AD16'] ''' V1AD02a (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - Taking vitamins with folic acid before pregnancy V1AD02b (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - Being a healthy weight before pregnancy V1AD02c (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - Getting your vaccines updated before pregnancy V1AD02d (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - Visiting a dentist or dental hygienist before pregnancy V1AD02e (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - Getting counseling for any genetic diseases that run in your family V1AD02f (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - Controlling any medical conditions, such as diabetes or high blood pressure V1AD02g (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - Getting counseling or treatment for depression or anxiety V1AD02h (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - The safety of using prescription or over-the-counter medicines during pregnancy V1AD02i (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - How smoking during pregnancy can affect a baby V1AD02j (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - How drinking alcohol during pregnancy can affect a baby V1AD02k (V1A) Before you got pregnant, did a doctor, nurse, or other health care worker talk to you about the following regarding how to prepare for a healthy pregnancy and baby? - How using illegal drugs during pregnancy can affect a baby V1AD03 (V1A) Was this pregnancy planned? V1AD05 (V1A) Is this pregnancy desired? [Yes = 1, No = 2] ''' health_discussion = ['V1AD02a','V1AD02b','V1AD02c','V1AD02d','V1AD02e', 'V1AD02f','V1AD02g','V1AD02h','V1AD02i','V1AD02j', 'V1AD02k','V1AD03','V1AD05'] ''' urgalertyn C1. Did review result in urgent alerts? (No/Yes) alertahi50 C1b1. Apnea-hypopnea index (AHI) > 50 (No/Yes) alerthypoyn B2. Severe hypoxemia (No/Yes) alerthyporest B2a. Baseline O2 sat < 88% (checkbox) alerthyposleep B2b. O2 sat during sleep <90% for >10% of sleep time (checkbox) alertecgyn B3. Specific heart rate and/or ECG finding (No/Yes) alertecghr40 B3a. HR for >2 continuous minutes is <40 bpm (checkbox) alertecghr150 B3b. HR for >2 continuous minutes is >150 bpm (checkbox) 0 = No, 1 = Yes ''' sleep_alert = ['urgalertyn','alertahi50','alerthypoyn','alerthyporest', 'alerthyposleep','alertecgyn','alertecghr40','alertecghr150'] ''' V2AE06a (V2A) Have any of your biological mother, sisters, half-sisters, or female first cousins ever had pregnancy complications - Delivery of a child more than 3 weeks before the expected due date V2AE06b (V2A) Have any of your biological mother, sisters, half-sisters, or female first cousins ever had pregnancy complications - Delivery of a child weighing less than 5 lb 8 oz (or 2500 grams) V2AE06c (V2A) Have any of your biological mother, sisters, half-sisters, or female first cousins ever had pregnancy complications - Spontaneous preterm delivery (<37 weeks) V2AE06d (V2A) Have any of your biological mother, sisters, half-sisters, or female first cousins ever had pregnancy complications - Early or preterm rupture of the membranes V2AE06e (V2A) Have any of your biological mother, sisters, half-sisters, or female first cousins ever had pregnancy complications - Preeclampsia, eclampsia, toxemia or pregnancy induced hypertension V2AE06f (V2A) Have any of your biological mother, sisters, half-sisters, or female first cousins ever had pregnancy complications - Induction of labor due to low amniotic fluid or poor fetal growth V2AE06g (V2A) Have any of your biological mother, sisters, half-sisters, or female first cousins ever had pregnancy complications - Stillbirth V2AE06h (V2A) Have any of your biological mother, sisters, half-sisters, or female first cousins ever had pregnancy complications - Delivery of an infant with a birth defect V2AE06i (V2A) Have any of your biological mother, sisters, half-sisters, or female first cousins ever had pregnancy complications - Other pregnancy complication 1 = Yes, 2 = No ''' fam_complications = ['V2AE06a','V2AE06b','V2AE06c','V2AE06d','V2AE06e', 'V2AE06f','V2AE06g','V2AE06h','V2AE06i'] ''' Social Support V1GA01 (V1G) Social Support - There is a special person who is around when I am in need V1GA02 (V1G) Social Support - There is a special person with whom I can share my joys and sorrows V1GA03 (V1G) Social Support - My family really tries to help me V1GA04 (V1G) Social Support - I get the emotional help and support I need from my family V1GA05 (V1G) Social Support - I have a special person who is a real source of comfort to me V1GA06 (V1G) Social Support - My friends really try to help me V1GA07 (V1G) Social Support - I can count on my friends when things go wrong V1GA08 (V1G) Social Support - I can talk about my problems with my family V1GA09 (V1G) Social Support - I have friends with whom I can share my joys and sorrows V1GA10 (V1G) Social Support - There is a special person in my life who cares about my feelings V1GA11 (V1G) Social Support - My family is willing to help me make decisions V1GA12 (V1G) Social Support - I can talk about my problems with my friends 1 Very strongly disagree 2 Strongly disagree 3 Mildly disagree 4 Neutral 5 Mildly agree 6 Strongly agree 7 Very strongly agree ''' social_support = ['V1GA01','V1GA02','V1GA03','V1GA04','V1GA05','V1GA06', 'V1GA07','V1GA08','V1GA09','V1GA10','V1GA11','V1GA12'] ''' SmokeCat1 Ever used tobacco (V1AG04) SmokeCat2 Smoked tobacco in the 3 months prior to pregnancy (V1AG05) SmokeCat3 Among those who smoked in the prior 3 months, how many cigarettes per day (V1AG05a) ''' smoking = ['SmokeCat1','SmokeCat2','SmokeCat3'] ''' Alcohol/Drugs V1AG12a (V1A) Every used any of these drugs - Marijuana (THC) V1AG12b (V1A) Every used any of these drugs - Cocaine V1AG12c (V1A) Every used any of these drugs - Prescription narcotics that were not prescribed for you V1AG12d (V1A) Every used any of these drugs - Heroin V1AG12e (V1A) Every used any of these drugs - Methadone V1AG12f (V1A) Every used any of these drugs - Amphetamines (speed) not prescribed for you V1AG12g (V1A) Every used any of these drugs - Inhalants not prescribed for you V1AG12h (V1A) Every used any of these drugs - Hallucinogens V1AG12i (V1A) Every used any of these drugs - Other V1AG14 (V1A) Have you ever considered yourself to be addicted to these drugs? [1 = Yes, 2 = No] ''' substances = ['V1AG12a','V1AG12b','V1AG12c', 'V1AG12d','V1AG12e','V1AG12f','V1AG12g','V1AG12h','V1AG12i', 'V1AG14'] ''' AgeCat_V1 Age category (years) at visit 1 calculated from DOB (V1AB01) and the form completion date 1 13-17 2 18-34 3 35-39 4 >= 40 CRace Race/ethnicity combined categories derived from V1AF05 and V1AF07a-g 1 Non-Hispanic White 2 Non-Hispanic Black 3 Hispanic 4 Asian 5 Other BMI_Cat BMI category (kg/m^2) at visit 1 calculated from height and weight (form V1B) 1 < 18.5 (underweight) 2 18.5 - < 25 (normal weight) 3 25 - < 30 (overweight) 4 30 - < 35 (obese) 5 >= 35 (morbidly obese) Education Education status attained (V1AF02) 1 Less than HS grad 2 HS grad or GED 3 Some college 4 Assoc/Tech degree 5 Completed college 6 Degree work beyond college poverty Poverty category based on income (V1AF14) and household size (V1AF13) relative to 2013 federal poverty guidelines 1 > 200% of fed poverty level 2 100-200% of fed poverty level 3 < 100% of fed poverty level ''' demo = ['AgeCat_V1','CRace','BMI_Cat','Education','poverty'] ''' Ins_Govt Health care paid for by govt insurance (V1AF15a) Ins_Mil Health care paid for by military insurance (V1AF15b) Ins_Comm Health care paid for by commercial health insurance (V1AF15c) Ins_Pers Health care paid for by personal income (V1AF15d) Ins_Othr Health care paid for by other (V1AF15e) 1 = Yes, 2 = No ''' insurance = ['Ins_Govt','Ins_Mil','Ins_Comm','Ins_Pers','Ins_Othr'] ''' V1AF03 (V1A) Do you currently have a partner or 'significant other'? V1AF03a1 (V1A) What support do you expect your partner to give you during this pregnancy? - Emotional support V1AF03a2 (V1A) What support do you expect your partner to give you during this pregnancy? - Financial support V1AF03a3 (V1A) What support do you expect your partner to give you during this pregnancy? - To be present for my prenatal visits V1AF03a4 (V1A) What support do you expect your partner to give you during this pregnancy? - To be present for the delivery V1AF03b (V1A) Are you currently living with your partner? V1AF03c (V1A) Is your current partner the biological father of the baby? 1 Yes 2 No 3 Not done/none recorded D Don't know M Missing N Not applicable R Refused ''' partner = ['V1AF03','V1AF03a1','V1AF03a2','V1AF03a3','V1AF03a4','V1AF03b','V1AF03c'] """ Ultrasound abnormalities [Normal/Abnormal/Not Reported] 'CUAB01a', (CUA) Brain region - Calvarium 'CUAB01b', (CUA) Brain region - Falx 'CUAB01c', (CUA) Brain region - Cavum septi pellucidi 'CUAB01d', (CUA) Brain region - Lateral ventricles 'CUAB01e', (CUA) Brain region - Choroid plexus 'CUAB01f', (CUA) Brain region - Thalami 'CUAB01g', (CUA) Brain region - Cerebellum 'CUAB01h', (CUA) Brain region - Posterior fossa 'CUAB01i', (CUA) Brain region - Cisterna magna ' ', 'CUAC01a', (CUA) Head/neck region - Lenses 'CUAC01b', (CUA) Head/neck region - Orbits 'CUAC01c', (CUA) Head/neck region - Profile 'CUAC01d', (CUA) Head/neck region - Nasal bone 'CUAC01e', (CUA) Head/neck region - Upper lip ' ', 'CUAD01a', (CUA) Chest region - Cardiac axis 'CUAD01b', (CUA) Chest region - Four chamber view 'CUAD01c', (CUA) Chest region - RVOT 'CUAD01d', (CUA) Chest region - LVOT 'CUAD01e', (CUA) Chest region - Three vessel view 'CUAD01f', (CUA) Chest region - Lungs 'CUAD01g', (CUA) Chest region - Diaphragm ' ', 'CUAE01a', (CUA) Abdomen region - Situs 'CUAE01b', (CUA) Abdomen region - Ventral wall / cord 'CUAE01c', (CUA) Abdomen region - Stomach 'CUAE01d', (CUA) Abdomen region - Kidneys 'CUAE01e', (CUA) Abdomen region - Gallbladder 'CUAE01f', (CUA) Abdomen region - Bladder 'CUAE01g', (CUA) Abdomen region - Umbilical arteries 'CUAE01h', (CUA) Abdomen region - Bowel 'CUAE01i', (CUA) Abdomen region - Genitalia ' ', 'CUAF01a', (CUA) Extremities region - Upper extremities 'CUAF01b', (CUA) Extremities region - Lower extremities ' ', 'CUAG01a', (CUA) Spine region - Cervical 'CUAG01b', (CUA) Spine region - Thoracic 'CUAG01c', (CUA) Spine region - Lumbar 'CUAG01d', (CUA) Spine region - Sacral CUBB01 (CUB) Were any structural abnormalities detected? [Yes/no] 1 Normal 2 Abnormal 3 Not reported/Unknown """ ultrasound_abnormal = ['CUBB01', 'CUAB01a', 'CUAB01b', 'CUAB01c', 'CUAB01d', 'CUAB01e', 'CUAB01f', 'CUAB01g', 'CUAB01h', 'CUAB01i', 'CUAC01a', 'CUAC01b', 'CUAC01c', 'CUAC01d', 'CUAC01e', 'CUAD01a', 'CUAD01b', 'CUAD01c', 'CUAD01d', 'CUAD01e', 'CUAD01f', 'CUAD01g', 'CUAE01a', 'CUAE01b', 'CUAE01c', 'CUAE01d', 'CUAE01e', 'CUAE01f', 'CUAE01g', 'CUAE01h', 'CUAE01i', 'CUAF01a', 'CUAF01b', 'CUAG01a', 'CUAG01b', 'CUAG01c', 'CUAG01d'] ''' CMEA01B1A_INT - UTI [negative before delivery] CMEA02A1A_INT - Sepsis blood culture CMEA02B1A_INT - Sepsis gram strain CMEA02C1A_INT - Sepsis spinal fluid CMEA03A1_INT - Pneumonia CMEA04A2_INT - other maternal infections INT is days, so negative values are before birth ''' #Too few of these to worry about, only a handful infections = ['CMEA01B1A_INT','CMEA02A1A_INT','CMEA02B1A_INT', 'CMEA02C1A_INT','CMEA03A1_INT','CMEA04A2_INT'] """ CMDA03a_Check - done/not done CMDA03a1 - serum creatinine [For adult women, 0.59 to 1.04 mg/dL (52.2 to 91.9 micromoles/L), https://www.mayoclinic.org/tests-procedures/creatinine-test/about/pac-20384646] CMDA03b_Check CMDA03b1 - AST Liver check [Females: 9 to 32 units/L, https://www.webmd.com/a-to-z-guides/aspartate_aminotransferse-test] CMDA03c_Check CMDA03c1 - uric acid [For females, it’s over 6 mg/dL is high, https://www.webmd.com/arthritis/uric-acid-blood-test] CMDA09g_Check CMDA09g1 - lowest serum platelet count [A normal platelet count ranges from 150,000 to 450,000 platelets per microliter of blood, https://www.hopkinsmedicine.org/health/conditions-and-diseases/what-are-platelets-and-why-are-they-important] CMDA09i_Check CMDA09i1 - highest serum lactate dehydrogenase [usually range between 140 units per liter (U/L) to 280 U/L for adults, https://www.webmd.com/a-to-z-guides/lactic-acid-dehydrogenase-test] CMDA09j_Check CMDA09j1 - highest serum total bilirubin [Normal results for a total bilirubin test are 1.2 milligrams per deciliter (mg/dL) for adults, low are ok, high is bad, https://www.mayoclinic.org/tests-procedures/bilirubin/about/pac-20393041] """ check_vars = ['CMDA03a_Check','CMDA03b_Check','CMDA03c_Check','CMDA09g_Check', 'CMDA09i_Check','CMDA09j_Check'] lab_vars = [i.split("_")[0]+"1" for i in check_vars] low_high = {'CMDA03a1':(0.59,1.04), 'CMDA03b1':(9,32), 'CMDA03c1':(0,6), 'CMDA09g1':(150,450), 'CMDA09i1':(140,280), 'CMDA09j1':(0,1.2)} # Need to make these into dummy variables # If before/during ''' Drug_Timing 1 > 2 Months before pregnancy Drug_Timing 2 During 2 months before pregnancy Drug_Timing 3 During Pregnancy, before first visit Drug_Timing 4 Before second visit Drug_Timing 5 Before third visit Drug_Timing 6 Before delivery Drug_Timing D Don't know Drug Codes 101 Narcotic  102 NSAID  103 Triptans  109 Other analgesics  111 Nitrofurantoin  112 Penicillins  113 Metronidazole  114 Macrolides  115 Sulfa drugs  116 Aminoglycosides  117 Clindamycin  118 Cephalosporins  119 Other antibiotic  121 Systemic antifungals  122 Vaginal antifungals  131 Antivirals - flu  132 Antivirals - herpes  139 Antivirals - other  141 Warfarin  142 Unfractionated heparin  143 LMWH  149 Other anticoagulant  150 Antipsychotics  161 MAOI  162 TCA  163 SSRI  164 SNRI  165 NDRI  166 Augmenter drug  169 Other antidepressant  171 GABA analogs  172 Benzodiazepines  173 Caboxamides (carbamazepine)  174 Fructose derivative (topiramate)  175 Hydantoins  176 Triazines (lamotrigine)  177 Valproate  179 Other anticonvulsant  181 Nifedipine/Procardia  182 Indomethacin/Indocin  183 Magnesium Sulfate  184 Terbutaline/Brethine  189 Other tocolytic  191 Methyldopa (Aldomet)  192 Labetolol  193 Ca-Channel Blocker  194 Beta-Blocker  195 ACE-Inhibitor  199 Other antihypertensives  200 Diuretics  211 Motility agents  212 Anti-nausea  213 SHT3 antagonist  214 Other NVP agents  215 PPIs  216 H2 receptor agonists  219 Other GI agents  220 Chemotherapeutics  230 Steroids (systemic)  240 Hormonal contraceptives  250 Progesterone (for purpose other than contraception)  261 Antithyroids (overactive)  262 Thyroid replacement (under-active)  271 Bronchodilator  272 Inhaled steroid  273 Immune modulator  280 Decongestants  290 Antihistamines  300 Combined antihistamines / decongestant  310 Combined antihistamines / decongestant / analgesic  320 Anti-anxiety medications  330 Mood stabilizers (lithium)  341 Insulin  342 Metformin  343 Glyburide  349 Other anti-diabetic medication  499 Other medication  510 Prenatal Multivitamin  520 Other Multivitamin  530 Additional Iron  540 Additional Folate  599 Other Vitamin  610 Influenza (seasonal/novel)  620 Hepatitis B  630 Rubella (German measles)  640 MMR  650 Varicella-zoster immune globulin (VZIG chicken pox)  660 Pertussis  699 Other vaccine  -8 Don't know ''' drug_codes = ['DrugCode'] + ['DrugCode_' + str(i+1) for i in range(27)] drugtime_codes = ['VXXC01g'] + ['VXXC01g_' + str(i+1) for i in range(27)] # These are the sets all put together all_vars = outcomes + mental_health + health_cond all_vars += check_vars + lab_vars + insurance all_vars += ultrasound_abnormal + demo + partner all_vars += substances + social_support + fam_complications all_vars += drug_codes + drugtime_codes + sleep_alert all_vars += health_discussion + asthma + smoking # Loads the full data frame of these variables full_dat = pd.read_csv(data_loc, usecols=all_vars, dtype=str) ############# # Drug Prep, 2 months before pregnancy not2m = full_dat[drugtime_codes] != '2' drug_dat = full_dat[drug_codes].copy() drug_dat.iloc[not2m] = np.NaN drug_dummy, drug_encode = encode_mult(full_dat, drug_codes, base="Drug", cum=False) drug_dummyvars = ["Drug_" + i for i in drug_encode] drug_dummy.columns = drug_dummyvars full_dat[drug_dummyvars] = drug_dummy all_vars += drug_dummyvars ############# ############# # Infections at least 60 days before birth # Too few to worry about #full_dat[infections].describe() ############# ############# # Insurance type ins_var = pd.Series('Ins_No',full_dat.index) for i in insurance: check = full_dat[i] == '1' ins_var[check] = i full_dat['ins_type'] = ins_var ins_type = ['ins_type'] #all_vars += ins_type demo += ins_type # just add it into demo variables ############# ############# # Outlier lab results -1 too low, 1 is too high lab_outlier = [] lab_ovars = [] for lv in lab_vars: num = pd.to_numeric(full_dat[lv],errors='coerce') low = (num < low_high[lv][0]) high = (num > low_high[lv][1]) res = pd.Series(0,full_dat.index) res[low] = -1 res[high] = 1 lab_outlier.append(res) lab_ovars.append('Out_' + lv) lab_odf = pd.concat(lab_outlier, axis=1) lab_odf.columns = lab_ovars full_dat[lab_ovars] = lab_odf all_vars += lab_ovars ############# # Function to return data without missing for given # outcome variable def prep_dat(out,rhs): # If variables in rhs are not in current full_dat, reread base # and include if out is None: outl = [] else: outl = [out] ro = set(rhs + outl) fd = set(list(full_dat)) diff = list(ro - fd) new_dat = full_dat.copy() if len(diff) > 0: upd =
pd.read_csv(data_loc, usecols=diff, dtype=str)
pandas.read_csv
import platform if platform.system() != "Windows": #Note pysam doesn't support Windows import numpy as np import anndata as ad import pandas as pd import pysam from scipy.sparse import lil_matrix from tqdm import tqdm def bld_mtx_fly(tsv_file, annotation, csv_file=None, genome=None, save=False): """ Building count matrix on the fly. Expected running time for 10k cells X 100k features on a personal computer ~65min Does not count pcr duplicate. A tbi file with the same filename as the provided tsv_file must be present in the same directory as the tsv file Note that this function is not available on the Windows operating system. Parameters ---------- tsv_file : name of the file containing the multiplexed reads (.tsv or .tsv.gz) annotation : loaded set of features to create the feature matrix from csv_file : default is None - genome : default is None - specify if you want to extract a specific genome assembly save : default is False - supply a file path as str to save generated AnnData object Output ------ AnnData object (also saved as h5ad if save argument is specified) """ print('loading barcodes') barcodes = sorted(
pd.read_csv(tsv_file, sep='\t', header=None)
pandas.read_csv
import pandas as pd import matplotlib.pyplot as plt import numpy as np #-------------read csv--------------------- df_2010_2011 = pd.read_csv("/mnt/nadavrap-students/STS/data/data_Shapira_20200911_2010_2011.csv") df_2012_2013 = pd.read_csv("/mnt/nadavrap-students/STS/data/data_Shapira_20200911_2012_2013.csv") df_2014_2015 =
pd.read_csv("/mnt/nadavrap-students/STS/data/data_Shapira_20200911_2014_2015.csv")
pandas.read_csv
#! /usr/bin/env python3 ## pooling_pipeline.py - ## index: A list of operations and functions included in this function ''' 0. import libraries and initialize global variables [Tommer] 1. parses input file [Tommer] 1a. create expression matrix for set of runs [Tommer] 2. single project PCA and elimination [Dan] 3. pool samples [Tommer] 3a. pool metadata [Tommer] 4. multiproject PCA/CCA [Dan] 4a. if (args.case): pool data and metadata again [Tommer] 5. elimination of run based on centroid distance [Tommer] 6. pass to DESeq2 for DGE analysis [Tommer] ''' ## 0. import libraries and initialize global variables, parse arguments import sys import sklearn import pandas as pd import gcsfs import seaborn as sns import numpy as np import matplotlib.pyplot as plt import math import random import subprocess from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.pipeline import Pipeline import argparse gene_counts_path = 'gs://ncbi_sra_rnaseq/genecounts/' print('parsing input file') parser = argparse.ArgumentParser() parser.add_argument('--case', action='store_true', help='for case control studies, perform PCA separately on cases and controls') parser.add_argument('--input',type=str, help='metadata csv',default=None) parser.add_argument('--name', type=str, help='name for whole analysis') args = parser.parse_args() joint_project = args.name input_file_path = args.input outdir = joint_project+'_output/' subprocess.call('mkdir '+outdir, shell = True) ## 1. parses input file total_df = pd.read_csv(input_file_path, sep = ',', index_col = 0) projects = list(set(total_df['project'])) for project in projects: df = total_df[total_df['project'] == project] df = df.drop_duplicates(subset = 'Run') df.to_csv(outdir+project+'.tsv', sep = '\t') ## 1a. create expression matrix for a project (set of runs) for project in projects: df = pd.read_csv(outdir+project+'.tsv', sep = '\t', index_col = 0) run_file1 = open(outdir+project+'_runs.txt', 'w') for run in list(df['Run']): run_file1.write(run+'\n') run_file1.close() genecount_df = pd.DataFrame() meta_df = pd.DataFrame() run_file = outdir+project+'_runs.txt' for run in open(run_file, 'r'): try: run = run.strip() df = pd.read_csv('gs://ncbi_sra_rnaseq/genecounts/'+run+'.genecounts', sep = '\t', index_col = 1, names = ['sample', 'gene', run]) df = df[run] df.columns = [run] genecount_df = pd.concat([genecount_df, df], axis = 1) except FileNotFoundError: print(run) continue genecount_df = genecount_df.drop(['__alignment_not_unique', '__ambiguous', '__no_feature', '__not_aligned', '__too_low_aQual'], axis = 0) genecount_df.to_csv(outdir+project+'_genecounts.txt', sep = '\t') ## 2. perform single project PCA print('looking for outliers in individual projects') if (args.case): print('separating cases from controls') new_projects = [] for project in projects: meta_df = pd.read_csv(outdir+project+'.tsv', sep = '\t', index_col = 0) genecount_df = pd.read_csv(outdir+project+'_genecounts.txt', sep = '\t', index_col = 0) total_runs = list(set(list(meta_df['Run'])) & set(list(genecount_df))) meta_df = meta_df.loc[meta_df['Run'].isin(total_runs)] genecount_df = genecount_df[total_runs] case_meta_df = meta_df[meta_df['condition'] == 'case'] control_meta_df = meta_df[meta_df['condition'] == 'control'] case_genecounts_df = genecount_df[meta_df[meta_df['condition'] == 'case']['Run']] control_genecounts_df = genecount_df[meta_df[meta_df['condition'] == 'control']['Run']] print('project ID is: '+project) if (len(list(case_genecounts_df)) > 0): new_projects.append(project+'_case') case_meta_df.to_csv(outdir+project+'_case.tsv', sep = '\t') case_genecounts_df.to_csv(outdir+project+'_case_genecounts.txt', sep = '\t') if (len(list(control_genecounts_df)) > 0): new_projects.append(project+'_control') control_meta_df.to_csv(outdir+project+'_control.tsv', sep = '\t') control_genecounts_df.to_csv(outdir+project+'_control_genecounts.txt', sep = '\t') projects = new_projects for project in projects: print(project) subprocess.call('python3 counts_pca-2.py --projname '+outdir+project+' --df '+outdir+project+'_genecounts.txt --md '+outdir+project+'.tsv --review', shell = True) ## 3. pool data for runs that successfully pass through single sample pca print('pooling data from separate projects') total_df = pd.DataFrame() project_list = [] for project in projects: df = pd.read_csv(outdir+project+'_genecounts.txt', sep = '\t', index_col = 0) total_df = pd.concat([total_df, df], axis = 1) for i in range(0,len(list(df))): project_list.append(project) total_df.to_csv(outdir+joint_project+'_genecounts.txt', sep = '\t') ## 3a. pool metadata print('pooling metadata from separate projects') joint_df = pd.read_csv(outdir+joint_project+'_genecounts.txt', sep = '\t') print(len(list(joint_df))) meta_df =
pd.DataFrame()
pandas.DataFrame
# -*- coding:utf-8 -*- import math import phate import anndata import shutil import warnings import pickle import numpy as np import pandas as pd import seaborn as sns from scipy.spatial.distance import cdist from scipy.stats import wilcoxon, pearsonr from scipy.spatial import distance_matrix from sklearn.decomposition import PCA # from python_codes.train.train import train from python_codes.train.clustering import clustering from python_codes.train.pseudotime import pseudotime from python_codes.util.util import load_breast_cancer_data, preprocessing_data, save_features from python_codes.util.exchangeable_loom import write_exchangeable_loom warnings.filterwarnings("ignore") from python_codes.util.util import * from matplotlib import rcParams rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Arial','Roboto'] rcParams['savefig.dpi'] = 300 import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable, inset_locator title_sz = 16 #################################### #----------Get Annotations---------# #################################### def get_adata_from_embeddings(args, sample_name, dataset="breast_cancer"): args.spatial = True output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' feature_fp = os.path.join(output_dir, "features.tsv") adata = sc.read_csv(feature_fp, delimiter="\t", first_column_names=None) return adata def get_clusters(args, sample_name, method="leiden", dataset="breast_cancer"): original_spatial = args.spatial args.spatial = True output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' pred_clusters = pd.read_csv(f"{output_dir}/{method}.tsv", header=None).values.flatten().astype(str) args.spatial = original_spatial cluster_color_dict = get_cluster_colors(args, sample_name) unique_cluster_dict = {cluster:cluster_color_dict[cluster]["abbr"] for cluster in cluster_color_dict.keys()} uniq_pred = np.unique(pred_clusters) for cid, cluster in enumerate(uniq_pred): pred_clusters[pred_clusters == cluster] = unique_cluster_dict[int(cluster)] return pred_clusters def get_cluster_colors_and_labels_original(): ann_dict = { 0: "Cancer 1", 1: "Immune:B/plasma", 2: "Adipose", 3: "Immune:APC/B/T cells", 4: "Cancer:Immune rich", 5: "Cancer 2", 6: "Cancer Connective" } color_dict = { 0: "#771122", 1: "#AA4488", 2: "#05C1BA", 3: "#F7E54A", 4: "#D55802", 5: "#137777", 6: "#124477" } return ann_dict, color_dict def get_cluster_colors(args, sample_name): fp = f'{args.dataset_dir}/Visium/Breast_Cancer/putative_cell_type_colors/{sample_name}.csv' df = pd.read_csv(fp) clusters = df["Cluster ID"].values.astype(int) annotations = df["Annotations"].values.astype(str) colors = df["Color"].values.astype(str) abbrs = df["Abbr"].values.astype(str) cur_dict = {} for cid, cluster in enumerate(clusters): cur_dict[cluster] = { "annotation" : annotations[cid], "color" : colors[cid], "abbr" : abbrs[cid] } return cur_dict def get_top_n_cluster_specific_genes(args, sample_name, method, dataset="breast_cancer", top_n=3): args.spatial = True output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' cluster_marker_genes_fp = f'{output_dir}/marker_genes_pval_gby_{method}.tsv' df = pd.read_csv(cluster_marker_genes_fp, sep="\t") df = df.loc[:top_n-1, df.columns.str.endswith("_n")] cluster_specific_genes_dict = {} for cluster_abbr in df.columns: cluster_specific_genes_dict[cluster_abbr.strip("_n")] = df[cluster_abbr].values.astype(str) return cluster_specific_genes_dict def save_cluster_specific_genes(args, adata, sample_name, method, dataset="breast_cancer", qval=0.05): args.spatial = True output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' fp = f'{args.dataset_dir}/Visium/Breast_Cancer/putative_cell_type_colors/{sample_name}.csv' df = pd.read_csv(fp) abbrs = np.array(np.unique(df["Abbr"].values.astype(str))) cluster_marker_genes_fp = f'{output_dir}/marker_genes_pval_gby_{method}.tsv' df = pd.read_csv(cluster_marker_genes_fp, sep="\t", header=0) for cid, cluster_name in enumerate(abbrs): sub_df = df.loc[df.loc[:, f"{cluster_name}_p"] <= qval, f"{cluster_name}_n"] genes = np.array(np.unique(sub_df.values.flatten().astype(str))) output_fp = f'{output_dir}/cluster_specific_marker_genes/{cluster_name}.tsv' mkdir(os.path.dirname(output_fp)) np.savetxt(output_fp, genes[:], delimiter="\n", fmt="%s") print(f"Saved at {output_fp}") all_genes = np.array(list(adata.var_names)) output_fp = f'{output_dir}/cluster_specific_marker_genes/background_genes.tsv' mkdir(os.path.dirname(output_fp)) np.savetxt(output_fp, all_genes[:], delimiter="\n", fmt="%s") print(f"Saved at {output_fp}") def get_GO_term_dict(args): base_dir = f"{args.dataset_dir}/Visium/Breast_Cancer/analysis" genes_with_go_ids_fp = f'{base_dir}/genes_with_go_ids.csv' go_id_to_genes_dict_pkl_fp = f"{base_dir}/go_id_to_genes_dict.pkl" if os.path.exists(go_id_to_genes_dict_pkl_fp): with open(go_id_to_genes_dict_pkl_fp, 'rb') as f: go_terms_dict = pickle.load(f) return go_terms_dict else: df = pd.read_csv(genes_with_go_ids_fp).values.astype(str) go_terms = np.array(np.unique(df[:, 1])) go_terms_dict = {go_id : df[df[:, 1] == go_id, 0] for go_id in go_terms} with open(go_id_to_genes_dict_pkl_fp, 'wb') as f: pickle.dump(go_terms_dict, f, -1) print(f"Saved at {go_id_to_genes_dict_pkl_fp}") return go_terms_dict def get_GO_terms_with_spatial_coherent_expr(args, adata, sample_name, go_term_dict, dataset="breast_cancer"): coords = adata.obsm["spatial"] index = np.arange(coords.shape[0]) genes = np.array(adata.var_names) GO_high_expressed = {} GO_high_expressed_pvals = {} n_go_terms = len(go_term_dict) for gid, (go_id, go_genes) in enumerate(go_term_dict.items()): if (gid + 1) % 500 == 0: print(f"Processed {gid + 1}/{n_go_terms}: {100. * (gid + 1)/n_go_terms}% GO terms") expr = adata.X[:, np.isin(genes, go_genes)].mean(axis=1) avg_expr = expr.mean() std_expr = expr.std() outlier_val = avg_expr + std_expr ind = np.array(np.where(expr > outlier_val)).flatten() if ind.size > 5: sub_coords = coords[ind, :] sub_dists = distance.cdist(sub_coords, sub_coords, 'euclidean') rand_index = np.random.choice(index, size=ind.size) random_coord = coords[rand_index, :] rand_dists = distance.cdist(random_coord, random_coord, 'euclidean') pval = wilcoxon(sub_dists.flatten(), rand_dists.flatten(), alternative='greater') if pval.pvalue < .05: GO_high_expressed[go_id] = ind GO_high_expressed_pvals[go_id] = pval.pvalue else: pass print(f"Found {len(GO_high_expressed)} highly expressed GO terms") args.spatial = True go_terms_w_pv = np.array([[go_id, str(GO_high_expressed_pvals[go_id])] for go_id in sorted(GO_high_expressed_pvals.keys(), key= lambda key:GO_high_expressed_pvals[key], reverse=True)]).astype(str) df = pd.DataFrame(go_terms_w_pv, columns=["GO_ID", "P-Val"]) output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' high_expr_GO_out_fp = f"{output_dir}/highly_expr_go.tsv" df.to_csv(high_expr_GO_out_fp, sep="\t", index=False) print(f"Saved at {high_expr_GO_out_fp}") high_expr_GO_out_pkl_fp = f"{output_dir}/highly_expr_go_w_spots_indices.pkl" with open(high_expr_GO_out_pkl_fp, 'wb') as handle: pickle.dump(GO_high_expressed, handle, -1) print(f"Saved at {high_expr_GO_out_pkl_fp}") def get_ovlp_GO_definitions(args, sample_name, dataset="breast_cancer"): args.spatial = True output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' high_expr_GO_out_fp = f"{output_dir}/highly_expr_go.tsv" df = pd.read_csv(high_expr_GO_out_fp, sep="\t", header= 0) fp = f'{args.dataset_dir}/Visium/Breast_Cancer/analysis/genes_with_go_ids_and_def.csv' go_id_def = pd.read_csv(fp).values.astype(str) go_dict = {go_id: go_id_def[gid, 1] for gid, go_id in enumerate(go_id_def[:, 0])} go_terms = df.loc[:, "GO_ID"].values.astype(str) go_def = np.array([go_dict[go_id] for go_id in go_terms]).astype(str) df["GO_DEF"] = go_def df = df.sort_values(by="P-Val", ascending=True) high_expr_GO_out_def_fp = f"{output_dir}/highly_expr_go_w_def.tsv" df.to_csv(high_expr_GO_out_def_fp, sep="\t", index=False) print(f"Saved at {high_expr_GO_out_def_fp}") def get_clusters_annnotations(sample_name): if sample_name[0] == "G": clusters = ['APC,B,T-1', 'APC,B,T-2', 'Inva-Conn', 'Invasive-2', 'Invasive-1', 'Imm-Reg-1', 'Imm-Reg-2' , 'Tu.Imm.Itfc-1', 'Tu.Imm.Itfc-1', 'Tu.Imm.Itfc-1'] return clusters else: return [] def find_ovlpd_go_terms_with_cluster_specific_go_pathways(args, sample_name, dataset="breast_cancer"): args.spatial = True output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' high_expr_GO_out_fp = f"{output_dir}/highly_expr_go.tsv" high_expr_go_df = pd.read_csv(high_expr_GO_out_fp, sep="\t", header=0) high_expr_go_terms = high_expr_go_df["GO_ID"].values.astype(str) cluster_dir = f'{output_dir}/cluster_specific_marker_genes' clusters = get_clusters_annnotations(sample_name) for cid, cluster in enumerate(clusters): cluster_go_term_fp = f"{cluster_dir}/{cluster}_topGO_terms.tsv" df = pd.read_csv(cluster_go_term_fp, sep="\t", header=0) go_ids = df["GO.ID"].values.astype(str) ovlp_go_ids, x_ind, y_ind = np.intersect1d(high_expr_go_terms, go_ids, return_indices=True) cluster_ovlp_go_terms_fp = f"{cluster_dir}/{cluster}_topGO_terms_w_high_expr_patterns.tsv" sub_df = df.iloc[y_ind, :] sub_df.to_csv(cluster_ovlp_go_terms_fp, sep="\t", index=False) print(f"Saved at {cluster_ovlp_go_terms_fp}") def cell_cell_communication_preprocessing_data(args, adata): sc.pp.filter_genes(adata, min_counts=1) # only consider genes with more than 1 count sc.pp.normalize_per_cell(adata, key_n_counts='n_counts_all', min_counts=0) # normalize with total UMI count per cell sc.pp.log1p(adata) # log transform: adata.X = log(adata.X + 1) genes = np.array(adata.var_names) cells = np.array(adata.obs_names) return adata, genes, cells def save_adata_to_preprocessing_dir(args, adata_pp, sample, cells): pp_dir = f'{args.dataset_dir}/Visium/Breast_Cancer/preprocessed/{sample}' mkdir(pp_dir) cluster_annotations = get_clusters(args, sample) concat_annotations = np.transpose(np.vstack([cells, cluster_annotations])) annotation_fp = f'{pp_dir}/cluster_anno.tsv' df = pd.DataFrame(data=concat_annotations, columns=["Cell", "Annotation"]) df.to_csv(annotation_fp, sep="\t", index=False) print(f"{sample} annotation saved at {annotation_fp}") adata_fp = f'{pp_dir}/anndata_pp.h5ad' mkdir(os.path.dirname(adata_fp)) adata_pp.write(adata_fp) print(f"{sample} adata saved at {adata_fp}") #################################### #-------------Plotting-------------# #################################### def plt_setting(): SMALL_SIZE = 10 MEDIUM_SIZE = 12 BIGGER_SIZE = 30 plt.rc('font', size=MEDIUM_SIZE, weight="bold") # controls default text sizes plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title def figure(nrow, ncol, rsz=3., csz=3., wspace=.4, hspace=.5): fig, axs = plt.subplots(nrow, ncol, figsize=(ncol * csz, nrow * rsz)) plt_setting() plt.subplots_adjust(wspace=wspace, hspace=hspace) return fig, axs def plot_hne_and_annotation(args, adata, sample_name, nrow = 1, scale = 0.045, ncol=4, rsz=2.5, csz=2.8, wspace=.4, hspace=.5, annotation=True): fig, axs = figure(nrow, ncol, rsz=rsz, csz=csz, wspace=wspace, hspace=hspace) if nrow == 1: for ax in axs: ax.axis('off') ax = axs[0] if annotation: fp = f'{args.dataset_dir}/Visium/Breast_Cancer/ST-pat/img/{sample_name[0]}1_annotated.png' else: fp = f'{args.dataset_dir}/Visium/Breast_Cancer/ST-imgs/{sample_name[0]}/{sample_name}/HE.jpg' img = plt.imread(fp) ax.imshow(img) # ax.set_title("H & E", fontsize=title_sz) x, y = adata.obsm["spatial"][:, 0]*scale, adata.obsm["spatial"][:, 1]*scale if not annotation: xlim = [np.min(x), np.max(x) * 1.05] ylim = [np.min(y) * .75, np.max(y) * 1.1] ax.set_xlim(xlim) ax.set_ylim(ylim) else: xlim, ylim = None, None ax.invert_yaxis() return fig, axs, x, y, img, xlim, ylim def plot_clustering(args, adata, sample_name, method="leiden", dataset="breast_cancer", cm = plt.get_cmap("Paired"), scale = .62, scatter_sz=1.3, nrow = 1, annotation=True): original_spatial = args.spatial fig, axs, x, y, img, xlim, ylim = plot_hne_and_annotation(args, adata, sample_name, scale=scale, nrow=nrow, ncol=3, rsz=2.6, csz=3.2, wspace=.3, hspace=.4, annotation=annotation) spatials = [False, True] for sid, spatial in enumerate(spatials): ax = axs[sid + 1] args.spatial = spatial output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' pred_clusters = pd.read_csv(f"{output_dir}/{method}.tsv", header=None).values.flatten().astype(int) uniq_pred = np.unique(pred_clusters) n_cluster = len(uniq_pred) if not annotation: ax.imshow(img) for cid, cluster in enumerate(uniq_pred): color = cm((cid * (n_cluster / (n_cluster - 1.0))) / n_cluster) ind = pred_clusters == cluster ax.scatter(x[ind], y[ind], s=scatter_sz, color=color, label=cluster) title = args.arch if not spatial else "%s + SP" % args.arch ax.set_title(title, fontsize=title_sz, pad=-30) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.invert_yaxis() box = ax.get_position() height_ratio = 1.0 ax.set_position([box.x0, box.y0, box.width * 0.8, box.height * height_ratio]) lgnd = ax.legend(loc='center left', fontsize=8, bbox_to_anchor=(1, 0.5), scatterpoints=1, handletextpad=0.1, borderaxespad=.1) for handle in lgnd.legendHandles: handle._sizes = [8] fig_fp = f"{output_dir}/{method}.pdf" plt.savefig(fig_fp, dpi=300) plt.close('all') args.spatial = original_spatial def plot_pseudotime(args, adata, sample_name, dataset="breast_cancer", cm = plt.get_cmap("gist_rainbow"), scale = 0.62, scatter_sz=1.3, nrow = 1): original_spatial = args.spatial fig, axs, x, y, img, _, _ = plot_hne_and_annotation(args, adata, sample_name, scale=scale, nrow=nrow, ncol=3) spatials = [False, True] for sid, spatial in enumerate(spatials): ax = axs[sid + 1] ax.imshow(img) args.spatial = spatial output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' fp = f"{output_dir}/pseudotime.tsv" pseudotimes = pd.read_csv(fp, header=None).values.flatten().astype(float) st = ax.scatter(x, y, s=1, c=pseudotimes, cmap=cm) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) clb = fig.colorbar(st, cax=cax) clb.ax.set_ylabel("pseudotime", labelpad=10, rotation=270, fontsize=10, weight='bold') title = args.arch if not spatial else "%s + SP" % args.arch ax.set_title(title, fontsize=title_sz) fig_fp = f"{output_dir}/psudotime.pdf" plt.savefig(fig_fp, dpi=300) plt.close('all') args.spatial = original_spatial def plot_clustering_and_pseudotime(args, adata, sample_name, method="leiden", dataset="breast_cancer", scale = 1., scatter_sz=1.3, nrow = 1, annotation=False, alpha=.5): original_spatial = args.spatial args.spatial = True fig, axs, x, y, img, xlim, ylim = plot_hne_and_annotation(args, adata, sample_name, scale=scale, nrow=nrow, ncol=5, rsz=2.6, csz=3.9, wspace=1, hspace=.4, annotation=annotation) ax = axs[1] ax.imshow(img, alpha=alpha) # fp = f'{args.dataset_dir}/Visium/Breast_Cancer/ST-pat/img/{sample_name[0]}1_annotated.png' # img2 = plt.imread(fp) # ax.imshow(img2) fp = f'{args.dataset_dir}/Visium/Breast_Cancer/ST-cluster/lbl/{sample_name}-cluster-annotation.tsv' df = pd.read_csv(fp, sep="\t") coords = df[["pixel_x", "pixel_y"]].values.astype(float) pred_clusters = df["label"].values.astype(int) cluster_dict, color_dict = get_cluster_colors_and_labels_original() uniq_pred = np.unique(pred_clusters) uniq_pred = sorted(uniq_pred, key=lambda cluster: cluster_dict[cluster]) for cid, cluster in enumerate(uniq_pred): ind = pred_clusters == cluster ax.scatter(coords[ind, 0], coords[ind, 1], s=scatter_sz, color=color_dict[cluster], label=cluster_dict[cluster]) ax.set_title("Annotation", fontsize=title_sz) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.invert_yaxis() ax.legend(fontsize=8, loc='center left', bbox_to_anchor=(1.0, 0.5)) ax = axs[2] ax.imshow(img, alpha=alpha) output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' pred_clusters = pd.read_csv(f"{output_dir}/{method}.tsv", header=None).values.flatten().astype(str) uniq_pred = np.unique(pred_clusters) cluster_color_dict = get_cluster_colors(args, sample_name) unique_cluster_dict = {cluster: cluster_color_dict[cluster]["abbr"] for cluster in cluster_color_dict.keys()} color_dict_for_cluster = {} for cid, cluster in enumerate(uniq_pred): label = unique_cluster_dict[int(cluster)] color_dict_for_cluster[label] = f"#{cluster_color_dict[int(cluster)]['color']}" pred_clusters[pred_clusters == cluster] = label uniq_pred = sorted(np.unique(pred_clusters)) for cid, cluster in enumerate(uniq_pred): ind = pred_clusters == cluster ax.scatter(x[ind], y[ind], s=scatter_sz, color=color_dict_for_cluster[cluster], label=cluster) ax.set_title("SpaceFlow\n(Segmentation)", fontsize=title_sz) ax.legend(fontsize=8, loc='center left', bbox_to_anchor=(1.0, 0.5)) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.invert_yaxis() ax = axs[3] ax.imshow(img, alpha=alpha) pseudotimes = pd.read_csv(f"{output_dir}/pseudotime.tsv", header=None).values.flatten().astype(float) pseudo_time_cm = plt.get_cmap("gist_rainbow") st = ax.scatter(x, y, s=scatter_sz, c=pseudotimes, cmap=pseudo_time_cm) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%") clb = fig.colorbar(st, cax=cax) clb.ax.set_ylabel("pSM value", labelpad=10, rotation=270, fontsize=8, weight='bold') ax.set_title("SpaceFlow\n(pSM)", fontsize=title_sz) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.invert_yaxis() ax = axs[4] ax.imshow(img, alpha=alpha) method = "stLearn" #"monocole" pseudotimes = pd.read_csv(f"{args.output_dir}/{dataset}/{sample_name}/{method}/pseudotime.tsv", header=None).values.flatten().astype(float) pseudo_time_cm = plt.get_cmap("gist_rainbow") st = ax.scatter(x, y, s=scatter_sz, c=pseudotimes, cmap=pseudo_time_cm) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%") clb = fig.colorbar(st, cax=cax) clb.ax.set_ylabel("pseudotime", labelpad=10, rotation=270, fontsize=8, weight='bold') ax.set_title(f"{method}\n(pseudotime)", fontsize=title_sz) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.invert_yaxis() fig_fp = f"{output_dir}/cluster+pseudotime.pdf" plt.savefig(fig_fp, dpi=300) plt.close('all') args.spatial = original_spatial def plot_clustering_and_pseudotime_SI(args, adata, sample_name, method="leiden", dataset="breast_cancer", scale = 1., scatter_sz=1.3, nrow = 1, annotation=False, cluster_cm = plt.get_cmap("tab10"),pseudotime_cm = plt.get_cmap("gist_rainbow"), alpha=.5): original_spatial = args.spatial args.spatial = True fig, axs, x, y, img, xlim, ylim = plot_hne_and_annotation(args, adata, sample_name, scale=scale, nrow=nrow, ncol=4, rsz=2.6, csz=2.8, wspace=.3, hspace=.2, annotation=annotation) ax = axs[1] ax.imshow(img, alpha=alpha) fp = f'{args.dataset_dir}/Visium/Breast_Cancer/ST-cluster/lbl/{sample_name}-cluster-annotation.tsv' df = pd.read_csv(fp, sep="\t") coords = df[["pixel_x", "pixel_y"]].values.astype(float) pred_clusters = df["label"].values.astype(int) uniq_pred = np.unique(pred_clusters) n_cluster = len(uniq_pred) for cid, cluster in enumerate(uniq_pred): ind = pred_clusters == cluster color = cluster_cm((cid * (n_cluster / (n_cluster - 1.0))) / n_cluster) ax.scatter(coords[ind, 0], coords[ind, 1], s=scatter_sz, color=color, label=str(cluster)) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.invert_yaxis() ax = axs[2] ax.imshow(img, alpha=alpha) output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' pred_clusters = pd.read_csv(f"{output_dir}/{method}.tsv", header=None).values.flatten().astype(str) uniq_pred = np.unique(pred_clusters) n_cluster = len(uniq_pred) for cid, cluster in enumerate(uniq_pred): ind = pred_clusters == cluster color = cluster_cm((cid * (n_cluster / (n_cluster - 1.0))) / n_cluster) ax.scatter(x[ind], y[ind], s=scatter_sz, color=color, label=cluster) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.invert_yaxis() ax = axs[3] ax.imshow(img, alpha=alpha) pseudotimes = pd.read_csv(f"{output_dir}/pseudotime.tsv", header=None).values.flatten().astype(float) st = ax.scatter(x, y, s=scatter_sz, c=pseudotimes, cmap=pseudotime_cm) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%") clb = fig.colorbar(st, cax=cax) clb.ax.set_ylabel("pSM value", labelpad=10, rotation=270, fontsize=8, weight='bold') ax.set_xlim(xlim) ax.set_ylim(ylim) ax.invert_yaxis() fig_fp = f"{output_dir}/segmentation_pseudotime.pdf" plt.savefig(fig_fp, dpi=300) plt.close('all') args.spatial = original_spatial def get_correlation_matrix_btw_clusters(args, sample_name, adata, method="cluster", dataset="breast_cancer"): pred_clusters = get_clusters(args, sample_name) uniq_clusters = np.array(np.unique(pred_clusters)) mean_exprs = [] for cid, uniq_cluster in enumerate(uniq_clusters): ind = pred_clusters == uniq_cluster mean_expr = adata.X[ind, :].mean(axis=0) mean_exprs.append(mean_expr) mean_exprs = np.array(mean_exprs).astype(float) df = pd.DataFrame(data=mean_exprs.transpose(), columns=uniq_clusters, index=np.array(adata.var_names).astype(str)) corr_matrix = df.corr(method="pearson") def plot_rank_marker_genes_group(args, sample_name, adata_filtered, method="cluster", dataset="breast_cancer", top_n_genes=3): original_spatial = args.spatial args.spatial = True pred_clusters = get_clusters(args, sample_name) output_dir = f'{args.output_dir}/{get_target_fp(args, dataset, sample_name)}' adata_filtered.obs[method] =
pd.Categorical(pred_clusters)
pandas.Categorical
# creating my first module: # libraries import pandas as pd import numpy as np import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from pandas import read_csv as csv def Explore(file, column_names=None, title_line_number=100, head_line_number=20): #df = pd.read_csv(file, header=None, names=column_names) df = pd.read_csv(file);print(title_line_number*'*') print('The dataset has been loaded from | {} | Successfully'.format(file)) print(title_line_number*'*'+'\n') print(df.head());print(title_line_number*'*'+'\n');print('\n'+title_line_number*'=') print('The data set has {} number of records, and {} number of columns'.format(df.shape[0],df.shape[1])) print(title_line_number*'*'+'\n');print('\n'+title_line_number*'=') print('The Datatypes are:');print(head_line_number*'-'); print(df.dtypes);print(title_line_number*'*'+'\n');print('\n'+title_line_number*'=') print('Other info:');print(head_line_number*'-'); print(df.info());print(title_line_number*'*'+'\n');print('\n'+title_line_number*'=') print('Statistical Summary:');print(head_line_number*'-'); print(df.describe());print(title_line_number*'*'+'\n');print('\n'+title_line_number*'=') return df def title(string, icon='-'): print(string.center(100,icon)) def setJupyterNotebook(max_rows=500,max_cols=500): pd.set_option('display.max_rows',max_rows) pd.set_option('display.max_columns',max_cols) np.set_printoptions(precision=3) pd.set_option('display.float_format', lambda x: '%.3f' % x) np.random.seed(8) import warnings warnings.filterwarnings('ignore') def Split(df,target='target',test_size=0.3,random_state=8): ''' input: pandas dataframe, target='target', test_size=0.3,random_state=8 output: tuple of X_train, X_test, y_train, y_test ''' X,y = df.drop([target], axis=1),df[target] from sklearn.model_selection import train_test_split return train_test_split(X, y, test_size=test_size, random_state=random_state) def OHE(data,non_features,cat_features=None): # Use later OneHotEncoder of sklearn and fit_transform(X_train) and transform (X_test) X_train, X_test, y_train, y_test = data if cat_features is None: cat_features = [col for col in X_train.select_dtypes('object').columns if col not in non_features] X_train_cat, X_test_cat = tuple([pd.concat([pd.get_dummies(X_cat[col],drop_first=False,prefix=col,prefix_sep='_',)\ for col in cat_features],axis=1) for X_cat in data[:2]]) X_train = pd.concat([X_train,X_train_cat],axis=1).drop(cat_features,axis=1) X_test = pd.concat([X_test,X_test_cat],axis=1).drop(cat_features,axis=1) OHE_features = list(X_train_cat.columns) return (X_train, X_test, y_train, y_test), OHE_features def Balance(data): ''' input: data = tuple of X_train, X_test, y_train, y_test target='target' # column name of the target variable output: data = the balanced version of data => FUNCTION DOES BALANCING ONLY ON TRAIN DATASET ''' X_train, X_test, y_train, y_test = data target=y_train.name #if else 'target' print('Checking Imbalance');print(y_train.value_counts(normalize=True)) Input = input('Do You Want to Treat Data?\nPress "y" or "n" \n') if Input.strip() == "y": print('Treating Imbalance on Train Data') from imblearn.over_sampling import SMOTE from imblearn.under_sampling import NearMiss SM = SMOTE(random_state=8, ratio=1.0) X_train_SM, y_train_SM = SM.fit_sample(X_train, y_train) X_train_SM = pd.DataFrame(X_train_SM, columns=X_train.columns) y_train_SM = pd.Series(y_train_SM,name=target); print('After Balancing') print(y_train_SM.value_counts(normalize=True)); print('*',"*");plt.figure(figsize=(8,3)); plt.subplot(1,2,1);sns.countplot(y_train);plt.title('before Imbalance'); plt.subplot(1,2,2);sns.countplot(y_train_SM);plt.title('after Imbalance Treatment');plt.show() data = X_train_SM,X_test, y_train_SM, y_test elif Input.strip()=='n': sns.countplot(y_train);plt.print('BEFORE'); data = data return data def SetIndex(data, index = 'ID'): ''' setting index before puting to ML algorithms and manual label encoding of y_train and y_test ''' X_train, X_test, y_train, y_test = data y_train = y_train.map({'Yes':1,'No':0}); y_test = y_test.map({'Yes':1,'No':0}) try:X_train = X_train.set_index(index) except:X_train=X_train y_train.index=X_train.index try:X_test = X_test.set_index(index) except:X_test=X_test y_test.index=X_test.index data = X_train, X_test, y_train, y_test return data def FeatureScale(data,OHE_features,scaler='MinMaxScaler'): ''' Feature Scaling only numerical_feaures. and not on OHE features input data = X_train, X_test, y_train, y_test OHE_features = list of One Encoded categorical feature columns scaler = either 'StandardScaler' or 'MinMaxScaler' output data = X_train, X_test, y_train, y_test ''' X_train, X_test, y_train, y_test = data X_train_num = X_train[[col for col in X_train.columns if col not in OHE_features]] X_train_cat = X_train[[col for col in X_train.columns if col in OHE_features]] X_test_num = X_test[[col for col in X_test.columns if col not in OHE_features]] X_test_cat = X_test[[col for col in X_test.columns if col in OHE_features]] from sklearn.preprocessing import StandardScaler, MinMaxScaler scalers = {'StandardScaler':StandardScaler(),'MinMaxScaler':MinMaxScaler()} sc = scalers[scaler] print('Applying',scaler) sc_X_train= pd.DataFrame(sc.fit_transform(X_train_num),columns=X_train_num.columns,index=X_train_num.index) sc_X_test = pd.DataFrame(sc.transform(X_test_num),columns=X_test_num.columns,index=X_test_num.index) X_train_scale =
pd.concat([sc_X_train,X_train_cat],axis=1)
pandas.concat
from clean_helpers import * import pandas as pd # Specify here what cleaning functions you want to use cleaning_actions = ['clean_new_line', 'clean_tags', 'clean_punctuation', \ 'remove_numbers'] clean = { "clean_new_line": clean_new_line, "lowercase": lowercase, "lemmatize": lemmatize, "remove_stopwords": remove_stopwords, "translate": perform_translation, "clean_punctuation": clean_punctuation, "clean_tags" : clean_tags, "remove_numbers": remove_numbers, } input_file_pos_full = 'Data/train_pos_full.txt' input_file_neg_full = 'Data/train_neg_full.txt' input_file_pos = 'Data/train_pos.txt' input_file_neg = 'Data/train_neg.txt' input_file_test = 'Data/test_data.txt' # Create a dataframe containing all the sentences in train_pos.txt and train_neg.txt labeled pos_sentences = [] with open(input_file_pos, 'r') as f: for sentence in f: pos_sentences.append(sentence) neg_sentences = [] with open(input_file_neg, 'r') as f: for sentence in f: neg_sentences.append(sentence) pos_data = pd.DataFrame(pos_sentences, columns=['sentence']) pos_data['label'] = 1 neg_data = pd.DataFrame(neg_sentences, columns=['sentence']) neg_data['label'] = 0 data = pd.concat([pos_data, neg_data]) # Create a dataframe containing all the sentences in train_pos_full.txt and train_neg_full.txt labeled pos_sentences_full = [] with open(input_file_pos_full, 'r') as f: for sentence in f: pos_sentences_full.append(sentence) neg_sentences_full = [] with open(input_file_neg_full, 'r') as f: for sentence in f: neg_sentences_full.append(sentence) pos_data_full = pd.DataFrame(pos_sentences_full, columns=['sentence']) pos_data_full['label'] = 1 neg_data_full = pd.DataFrame(neg_sentences_full, columns=['sentence']) neg_data_full['label'] = 0 full_data =
pd.concat([pos_data_full, neg_data_full])
pandas.concat
#!/usr/bin/env python """Tests for `pubchem_api` package.""" import os import numpy as np import pandas as pd import scipy from scipy.spatial import distance import unittest # from click.testing import CliRunner # from structure_prediction import cli class TestDataPreprocessing(unittest.TestCase): """Tests for `data pre-processing` package.""" def setUp(self): """Set up test fixtures, if any.""" def tearDown(self): """Tear down test fixtures, if any.""" def test_001_adjacency_matrix_ok(self): """ Tests to ensure that adjacency matrix prepared correctly To show that distance.pdist function calculates correctly on a simple test array """ print("Test One... To show that distance.pdist function calculates correctly on a simple test array") test_array_1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) a = np.sqrt(((1-1)**2) + ((2-2)**2) + ((3-3)**2)) b = np.sqrt(((1-4)**2) + ((2-5)**2) + ((3-6)**2)) c = np.sqrt(((1-7)**2) + ((2-8)**2) + ((3-9)**2)) d = np.sqrt(((1-10)**2) + ((2-11)**2) + ((3-12)**2)) e = np.sqrt(((4-1)**2) + ((5-2)**2) + ((6-3)**2)) f = np.sqrt(((4-4)**2) + ((5-5)**2) + ((6-6)**2)) g = np.sqrt(((4-7)**2) + ((5-8)**2) + ((6-9)**2)) h = np.sqrt(((4-10)**2) + ((5-11)**2) + ((6-12)**2)) i = np.sqrt(((7-1)**2) + ((8-2)**2) + ((9-3)**2)) j = np.sqrt(((7-4)**2) + ((8-5)**2) + ((9-6)**2)) k = np.sqrt(((7-7)**2) + ((8-8)**2) + ((9-9)**2)) l = np.sqrt(((7-10)**2) + ((8-11)**2) + ((9-12)**2)) m = np.sqrt(((10-1)**2) + ((11-2)**2) + ((12-3)**2)) n = np.sqrt(((10-4)**2) + ((11-5)**2) + ((12-6)**2)) o = np.sqrt(((10-7)**2) + ((11-8)**2) + ((12-9)**2)) p = np.sqrt(((10-10)**2) + ((11-11)**2) + ((12-12)**2)) result_array = np.array([[a, b, c, d], [e, f, g, h], [i, j, k, l], [m, n, o, p]]) print(result_array) calculate_distances = distance.pdist(test_array_1, 'euclidean') make_square = distance.squareform(calculate_distances) print(make_square) assert np.array_equal(result_array, make_square) def test_002_adjacency_matrix_ok(self): """ Tests to ensure that adjacency matrix prepared correctly To show that distance.pdist function calculates correctly on a simple test array """ print(("Test Two... To show that distance.pdist function calculates correctly on a simple test array")) test_array_1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) a = np.sqrt(((1-1)**2) + ((2-2)**2) + ((3-3)**2)) b = np.sqrt(((1-4)**2) + ((2-5)**2) + ((3-6)**2)) c = np.sqrt(((1-7)**2) + ((2-8)**2) + ((3-9)**2)) d = np.sqrt(((1-10)**2) + ((2-11)**2) + ((3-12)**2)) e = np.sqrt(((4-1)**2) + ((5-2)**2) + ((6-3)**2)) f = np.sqrt(((4-4)**2) + ((5-5)**2) + ((6-6)**2)) g = np.sqrt(((4-7)**2) + ((5-8)**2) + ((6-9)**2)) h = np.sqrt(((4-10)**2) + ((5-11)**2) + ((6-12)**2)) i = np.sqrt(((7-1)**2) + ((8-2)**2) + ((9-3)**2)) j = np.sqrt(((7-4)**2) + ((8-5)**2) + ((9-6)**2)) k = np.sqrt(((7-7)**2) + ((8-8)**2) + ((9-9)**2)) l = np.sqrt(((7-10)**2) + ((8-11)**2) + ((9-12)**2)) m = np.sqrt(((10-1)**2) + ((11-2)**2) + ((12-3)**2)) n = np.sqrt(((10-4)**2) + ((11-5)**2) + ((12-6)**2)) o = np.sqrt(((10-7)**2) + ((11-8)**2) + ((12-9)**2)) p = np.sqrt(((10-10)**2) + ((11-11)**2) + ((12-12)**2)) result_array = np.array([[a, b, c, d], [e, f, g, h], [i, j, k, l], [m, n, o, p]]) calculate_distances = distance.pdist(test_array_1, 'euclidean') make_square = distance.squareform(calculate_distances) for i in range(0,result_array.shape[1]): # print(result_array[i,i]) self.assertEqual(result_array[i,i], 0) for i in range(0,make_square.shape[1]): # print(make_square[i,i]) self.assertEqual(make_square[i,i], 0) def test_003_adjacency_matrix_ok(self): """ Tests to ensure that adjacency matrix prepared correctly To show that distance.pdist function calculates correctly on a pdb.cif file """ print("Test Three... To show that distance.pdist function calculates correctly on a pdb.cif file") with open('./extracted_test_data/1j5a.cif') as infile: target_list = infile.read().split('\n') df_1 = pd.DataFrame(data=target_list, columns=["header"]) # Put list in a dataframe m X 1 column df_1 = df_1[:-1] # Removes additional row that is included cif_to_df_2 = df_1.header.str.split(expand=True) # Put dataframe to m x 20 columns critical_info_to_df_3 = cif_to_df_2.drop(columns=[0, 1, 2, 3, 4, 6, 7, 8, 9, 13, 14, 15, 16, 17, 18, 19, 20], axis=1) # df containing aa & coordinate positions print(critical_info_to_df_3.head()) convert_to_array = critical_info_to_df_3.drop(columns=[5], axis=1).to_numpy() # Removes aa flag & contains only coordinate info calculate_distances = distance.pdist(convert_to_array, 'euclidean') make_square = distance.squareform(calculate_distances) print(make_square) assert df_1.shape[0] == cif_to_df_2.shape[0] assert cif_to_df_2.shape[0] == critical_info_to_df_3.shape[0] def test_004_adjacency_matrix_ok(self): """ Tests to ensure that adjacency matrix prepared correctly To show that distance.pdist function calculates correctly on a pdb.cif file """ print("Test Four... To show that distance.pdist function calculates correctly on a pdb.cif file") with open('./extracted_test_data/1j5a.cif') as infile: target_list = infile.read().split('\n') df_1 = pd.DataFrame(data=target_list, columns=["header"]) # Put list in a dataframe m X 1 column df_1 = df_1[:-1] # Removes additional row that is included cif_to_df_2 = df_1.header.str.split(expand=True) # Put dataframe to m x 20 columns critical_info_to_df_3 = cif_to_df_2.drop(columns=[0, 1, 2, 3, 4, 6, 7, 8, 9, 13, 14, 15, 16, 17, 18, 19, 20], axis=1) # df containing aa & coordinate positions convert_to_array = critical_info_to_df_3.drop(columns=[5], axis=1).to_numpy() # Removes aa flag & contains only coordinate info calculate_distances = distance.pdist(convert_to_array, 'euclidean') make_square = distance.squareform(calculate_distances) for i in range(0,make_square.shape[1]): print(make_square[i,i]) self.assertEqual(make_square[i,i], 0) def test_005_adjacency_matrix_ok(self): """ Tests to ensure that adjacency matrix prepared correctly To show that adjacency matrix maintains its form when converted back into a dataframe """ print("Test Five...") with open('./extracted_test_data/1j5a.cif') as infile: target_list = infile.read().split('\n') df_1 = pd.DataFrame(data=target_list, columns=["header"]) # Put list in a dataframe m X 1 column df_1 = df_1[:-1] # Removes additional row that is included cif_to_df_2 = df_1.header.str.split(expand=True) # Put dataframe to m x 20 columns critical_info_to_df_3 = cif_to_df_2.drop(columns=[0, 1, 2, 3, 4, 6, 7, 8, 9, 13, 14, 15, 16, 17, 18, 19, 20], axis=1) # df containing aa & coordinate positions convert_to_array = critical_info_to_df_3.drop(columns=[5], axis=1).to_numpy() # Removes aa flag & contains only coordinate info calculate_distances = distance.pdist(convert_to_array, 'euclidean') make_square = distance.squareform(calculate_distances) adjacency_matrix_df_4 = pd.DataFrame(make_square) df_join =
pd.concat([critical_info_to_df_3, adjacency_matrix_df_4], axis=1, join='inner')
pandas.concat
'''script to calculate adjusted ppl and acc python -u scripts/adjust_ppl_acc.py -bs 256 --cuda cuda:5 -model_dir model/nodp/20210418/181252/data-wikitext-2-add10b_model-LSTM_ebd-200_hid-200_bi-False_lay-1_tie-False_tok-50258_bs-16_bptt-35_lr-20.0_dp-False_partial-False_0hidden-False.pt_ppl-69.7064935_acc-0.38333_epoch-50_ep-0.000_dl-0_ap-0.00 python -u scripts/adjust_ppl_acc.py -bs 256 --cuda cuda:3 --data data/simdial --data_type dial -model_dir model/nodp/20210501/192118/data-simdial_model-LSTM_ebd-200_hid-200_bi-False_lay-1_tie-False_tok-50260_bs-16_bptt-35_lr-20.0_dp-False_partial-False_0hidden-False.pt_ppl-3.0253297_acc-0.75599_epoch-36_ep-0.000_dl-0_ap-0.00 ''' import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import utils from torch.utils.data import DataLoader, Dataset import data import argparse import math import pandas as pd from tqdm import tqdm import torch from datetime import datetime import socket from pathlib import Path def load_model(model_path): with open(model_path, 'rb') as f: model = torch.load(f, map_location=device) model.eval() return model def calculate_for_dataloader(data_loader, model, device, PAD_TOKEN_ID, tokenizer, private_func, data_type='doc', is_transformer_model=False): (total_loss, total_correct, total_count), (total_loss_nonprivate, total_correct_nonprivate, total_count_nonprivate), (total_loss_private, total_correct_private, total_count_private) = (0, 0, 0), (0, 0, 0), (0, 0, 0) model.eval() with torch.no_grad(): for batch in tqdm(data_loader): (cur_loss, cur_correct, cur_count), (cur_loss_nonprivate, cur_correct_nonprivate, cur_count_nonprivate), (cur_loss_private, cur_correct_private, cur_count_private) = utils.calculate_adjusted_ppl_acc(batch, model, device, PAD_TOKEN_ID, tokenizer, private_func, data_type, is_transformer_model) # overall total_loss += cur_loss total_correct += cur_correct total_count += cur_count # nonprivate total_loss_nonprivate += cur_loss_nonprivate total_correct_nonprivate += cur_correct_nonprivate total_count_nonprivate += cur_count_nonprivate # private total_loss_private += cur_loss_private total_correct_private += cur_correct_private total_count_private += cur_count_private overall_ppl = math.exp(total_loss/total_count) overall_acc = total_correct/total_count nonprivate_ppl = math.exp(total_loss_nonprivate/total_count_nonprivate) nonprivate_acc = total_correct_nonprivate/total_count_nonprivate private_ppl = math.exp(total_loss_private/total_count_private) private_acc = total_correct_private/total_count_private return (overall_ppl, overall_acc), (nonprivate_ppl, nonprivate_acc), (private_ppl, private_acc) parser = argparse.ArgumentParser(description='PyTorch Wikitext-2 RNN/LSTM/GRU/Transformer Language Model') parser.add_argument('--data', type=str, default='./data/wikitext-2-add10b', help='location of the data corpus') parser.add_argument('--model', type=str, default='LSTM', help='type of recurrent net (RNN_TANH, RNN_RELU, LSTM, GRU, Transformer)') parser.add_argument('--tokenizer', type=str, default='gpt2', help='type of tokenizers') parser.add_argument('--emsize', type=int, default=200, help='size of word embeddings') parser.add_argument('--nhid', type=int, default=200, help='number of hidden units per layer') parser.add_argument('--num_layers', type=int, default=1, help='number of layers') parser.add_argument('--lr', type=float, default=2, help='initial learning rate') parser.add_argument('--clip', type=float, default=0.25, help='gradient clipping') parser.add_argument('--epochs', type=int, default=50, help='upper epoch limit') parser.add_argument('--batch_size', '-bs', type=int, default=16, metavar='N', help='batch size') parser.add_argument('--bptt', type=int, default=35, help='sequence length') parser.add_argument('--dropout', type=float, default=0.2, help='dropout applied to layers (0 = no dropout)') parser.add_argument('--tied', action='store_true', #default=True, #TODO cannot use tied with DPLSTM help='tie the word embedding and softmax weights') parser.add_argument('--bidirectional', action='store_true', default=False, help='bidirectional LSTM') parser.add_argument('--seed', type=int, default=1111, help='random seed') parser.add_argument('--cuda', type=str, default="cuda:0", help='CUDA number') parser.add_argument('--log-interval', type=int, default=200, metavar='N', help='report interval') parser.add_argument('--save', type=str, default='model/', help='path to save the final model') parser.add_argument('--onnx-export', type=str, default='', help='path to export the final model in onnx format') parser.add_argument('--nhead', type=int, default=2, help='the number of heads in the encoder/decoder of the transformer model') parser.add_argument('--dry-run', action='store_true', help='verify the code and the model') parser.add_argument('-dp', action='store_true', help='differential privacy') parser.add_argument('-partial', action='store_true', help='partial differential privacy') parser.add_argument('--warmup_steps', type=int, default=5_000, help='warm up steps') parser.add_argument('--sigma', type=float, default=0.5, help='sigma') parser.add_argument('--max_per_sample_grad_norm', '-norm', type=float, default=0.1, help='max_per_sample_grad_norm') parser.add_argument('--with_scheduler', action='store_true', help='use lr scheduler') parser.add_argument('--virtual_step', type=int, default=1, help='virtual step, virtual_step * batch_size = actual_size') parser.add_argument('--data_type', type=str.lower, default='doc', choices=['doc', 'dial'], help='data type, doc for documents in lm, dial for dialogues') parser.add_argument('-partial_hidden_zero', action='store_true', help='partial differential privacy use zero hidden states') parser.add_argument('-dont_save_model', action='store_true', help='do not save the model when testing') parser.add_argument('-resume', action='store_true', help='resume from previous ckpt') parser.add_argument('-resume_from', type=str, help='ckpt to resume from') parser.add_argument('-resume_from_epoch_num', type=int, default=0, help='epoch number to resume from') parser.add_argument('-use_test_as_train', action='store_true', help='use test set as training set for faster development') parser.add_argument('-missing_digits', action='store_true', help='the experiments for missing the inserted digits') parser.add_argument('-model_dir', type=str, help='the dir to models') parser.add_argument('-outputf', type=str, default='data/adjusted_metrics', help='the output file') parser.add_argument('-digits_unk_as_private', action='store_true', help='both digits and unk will be private for missing the inserted digits') args = parser.parse_args() ############################################################################### # Load tokenizer ############################################################################### is_dial = args.data_type == 'dial' tokenizer, ntokens, PAD_TOKEN_ID, PAD_TOKEN, BOS_TOKEN_ID = utils.load_tokenizer(is_dialog=is_dial) if is_dial: private_func = utils.private_token_classifier else: if args.digits_unk_as_private: private_func = utils.is_digit_unk else: private_func = utils.is_digit device = args.cuda if args.data_type == 'doc': # corpus = data.Corpus(os.path.join(args.data), tokenizer=tokenizer) # eval_batch_size = 10 # train_data = batchify(corpus.train, args.batch_size) # val_data = batchify(corpus.valid, eval_batch_size) # test_data = batchify(corpus.test, eval_batch_size) print(f"training data: {args.data}") # if args.partial and args.dp: # train_corpus = data.CorpusPartialDPDataset(os.path.join(args.data, 'train'), tokenizer, args.batch_size, args.bptt, utils.is_digit, missing_digits=args.missing_digits) # else: # train_corpus = data.CorpusDataset(os.path.join(args.data, 'train'), tokenizer, args.batch_size, args.bptt) valid_corpus = data.CorpusDataset(os.path.join(args.data, 'valid'), tokenizer, args.batch_size, args.bptt) test_corpus = data.CorpusDataset(os.path.join(args.data, 'test'), tokenizer, args.batch_size, args.bptt) else: # if args.partial and args.dp: # if args.use_test_as_train: # train_corpus = data.CustomerPartialDPDataset(os.path.join(args.data, 'test'), tokenizer, utils.private_token_classifier) # else: # train_corpus = data.CustomerPartialDPDataset(os.path.join(args.data, 'train'), tokenizer, utils.private_token_classifier) # else: # train_corpus = data.CustomerDataset(os.path.join(args.data, 'train'), tokenizer) valid_corpus = data.CustomerDataset(os.path.join(args.data, 'valid'), tokenizer=tokenizer) test_corpus = data.CustomerDataset(os.path.join(args.data, 'test'), tokenizer=tokenizer) # train_dataloader = DataLoader(dataset=train_corpus, # shuffle=True, # batch_size=args.batch_size, # collate_fn=train_corpus.collate) val_dataloader = DataLoader(dataset=valid_corpus, shuffle=False, batch_size=args.batch_size, collate_fn=valid_corpus.collate) test_dataloader = DataLoader(dataset=test_corpus, shuffle=False, batch_size=args.batch_size, collate_fn=valid_corpus.collate) if not os.path.exists(args.outputf): os.makedirs(args.outputf) # print(f'output will be saved to {args.outputf}') timenow = datetime.now() valid_csv_dir = os.path.join(args.outputf, f'valid_{str(timenow)}_{args.cuda}_on_{socket.gethostname()}.csv') test_csv_dir = os.path.join(args.outputf, f'test_{str(timenow)}_{args.cuda}_on_{socket.gethostname()}.csv') assert not os.path.isfile(valid_csv_dir) assert not os.path.isfile(test_csv_dir) print(f'output will be saved to {valid_csv_dir}') print(f'output will be saved to {test_csv_dir}') records = [] test_records = [] if os.path.isdir(args.model_dir): paths = sorted(Path(args.model_dir).iterdir(), key=os.path.getmtime) else: paths = [args.model_dir] for model_path in tqdm(paths): model_path = str(model_path) try: model = load_model(model_path) is_transformer_model = hasattr(model, 'model_type') and model.model_type == 'Transformer' (overall_ppl, overall_acc), (nonprivate_ppl, nonprivate_acc), (private_ppl, private_acc) = calculate_for_dataloader(val_dataloader, model, device, PAD_TOKEN_ID, tokenizer, private_func, data_type=args.data_type, is_transformer_model=is_transformer_model) records.append([model_path, overall_ppl, overall_acc, nonprivate_ppl, nonprivate_acc, private_ppl, private_acc]) except: pass column_names=['model_path', 'overall_ppl', 'overall_acc', 'nonprivate_ppl', 'nonprivate_acc', 'private_ppl', 'private_acc'] records =
pd.DataFrame(records, columns=column_names)
pandas.DataFrame
from datetime import timedelta from functools import partial import itertools from parameterized import parameterized import numpy as np from numpy.testing import assert_array_equal, assert_almost_equal import pandas as pd from toolz import merge from zipline.pipeline import SimplePipelineEngine, Pipeline, CustomFactor from zipline.pipeline.common import ( EVENT_DATE_FIELD_NAME, FISCAL_QUARTER_FIELD_NAME, FISCAL_YEAR_FIELD_NAME, SID_FIELD_NAME, TS_FIELD_NAME, ) from zipline.pipeline.data import DataSet from zipline.pipeline.data import Column from zipline.pipeline.domain import EquitySessionDomain from zipline.pipeline.loaders.earnings_estimates import ( NextEarningsEstimatesLoader, NextSplitAdjustedEarningsEstimatesLoader, normalize_quarters, PreviousEarningsEstimatesLoader, PreviousSplitAdjustedEarningsEstimatesLoader, split_normalized_quarters, ) from zipline.testing.fixtures import ( WithAdjustmentReader, WithTradingSessions, ZiplineTestCase, ) from zipline.testing.predicates import assert_equal from zipline.testing.predicates import assert_frame_equal from zipline.utils.numpy_utils import datetime64ns_dtype from zipline.utils.numpy_utils import float64_dtype import pytest class Estimates(DataSet): event_date = Column(dtype=datetime64ns_dtype) fiscal_quarter = Column(dtype=float64_dtype) fiscal_year = Column(dtype=float64_dtype) estimate = Column(dtype=float64_dtype) class MultipleColumnsEstimates(DataSet): event_date = Column(dtype=datetime64ns_dtype) fiscal_quarter = Column(dtype=float64_dtype) fiscal_year = Column(dtype=float64_dtype) estimate1 = Column(dtype=float64_dtype) estimate2 = Column(dtype=float64_dtype) def QuartersEstimates(announcements_out): class QtrEstimates(Estimates): num_announcements = announcements_out name = Estimates return QtrEstimates def MultipleColumnsQuartersEstimates(announcements_out): class QtrEstimates(MultipleColumnsEstimates): num_announcements = announcements_out name = Estimates return QtrEstimates def QuartersEstimatesNoNumQuartersAttr(num_qtr): class QtrEstimates(Estimates): name = Estimates return QtrEstimates def create_expected_df_for_factor_compute(start_date, sids, tuples, end_date): """ Given a list of tuples of new data we get for each sid on each critical date (when information changes), create a DataFrame that fills that data through a date range ending at `end_date`. """ df = pd.DataFrame(tuples, columns=[SID_FIELD_NAME, "estimate", "knowledge_date"]) df = df.pivot_table( columns=SID_FIELD_NAME, values="estimate", index="knowledge_date", dropna=False ) df = df.reindex(pd.date_range(start_date, end_date)) # Index name is lost during reindex. df.index = df.index.rename("knowledge_date") df["at_date"] = end_date.tz_localize("utc") df = df.set_index(["at_date", df.index.tz_localize("utc")]).ffill() new_sids = set(sids) - set(df.columns) df = df.reindex(columns=df.columns.union(new_sids)) return df class WithEstimates(WithTradingSessions, WithAdjustmentReader): """ ZiplineTestCase mixin providing cls.loader and cls.events as class level fixtures. Methods ------- make_loader(events, columns) -> PipelineLoader Method which returns the loader to be used throughout tests. events : pd.DataFrame The raw events to be used as input to the pipeline loader. columns : dict[str -> str] The dictionary mapping the names of BoundColumns to the associated column name in the events DataFrame. make_columns() -> dict[BoundColumn -> str] Method which returns a dictionary of BoundColumns mapped to the associated column names in the raw data. """ # Short window defined in order for test to run faster. START_DATE = pd.Timestamp("2014-12-28", tz="utc") END_DATE = pd.Timestamp("2015-02-04", tz="utc") @classmethod def make_loader(cls, events, columns): raise NotImplementedError("make_loader") @classmethod def make_events(cls): raise NotImplementedError("make_events") @classmethod def get_sids(cls): return cls.events[SID_FIELD_NAME].unique() @classmethod def make_columns(cls): return { Estimates.event_date: "event_date", Estimates.fiscal_quarter: "fiscal_quarter", Estimates.fiscal_year: "fiscal_year", Estimates.estimate: "estimate", } def make_engine(self, loader=None): if loader is None: loader = self.loader return SimplePipelineEngine( lambda x: loader, self.asset_finder, default_domain=EquitySessionDomain( self.trading_days, self.ASSET_FINDER_COUNTRY_CODE, ), ) @classmethod def init_class_fixtures(cls): cls.events = cls.make_events() cls.ASSET_FINDER_EQUITY_SIDS = cls.get_sids() cls.ASSET_FINDER_EQUITY_SYMBOLS = [ "s" + str(n) for n in cls.ASSET_FINDER_EQUITY_SIDS ] # We need to instantiate certain constants needed by supers of # `WithEstimates` before we call their `init_class_fixtures`. super(WithEstimates, cls).init_class_fixtures() cls.columns = cls.make_columns() # Some tests require `WithAdjustmentReader` to be set up by the time we # make the loader. cls.loader = cls.make_loader( cls.events, {column.name: val for column, val in cls.columns.items()} ) class WithOneDayPipeline(WithEstimates): """ ZiplineTestCase mixin providing cls.events as a class level fixture and defining a test for all inheritors to use. Attributes ---------- events : pd.DataFrame A simple DataFrame with columns needed for estimates and a single sid and no other data. Tests ------ test_wrong_num_announcements_passed() Tests that loading with an incorrect quarter number raises an error. test_no_num_announcements_attr() Tests that the loader throws an AssertionError if the dataset being loaded has no `num_announcements` attribute. """ @classmethod def make_columns(cls): return { MultipleColumnsEstimates.event_date: "event_date", MultipleColumnsEstimates.fiscal_quarter: "fiscal_quarter", MultipleColumnsEstimates.fiscal_year: "fiscal_year", MultipleColumnsEstimates.estimate1: "estimate1", MultipleColumnsEstimates.estimate2: "estimate2", } @classmethod def make_events(cls): return pd.DataFrame( { SID_FIELD_NAME: [0] * 2, TS_FIELD_NAME: [pd.Timestamp("2015-01-01"), pd.Timestamp("2015-01-06")], EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-10"), pd.Timestamp("2015-01-20"), ], "estimate1": [1.0, 2.0], "estimate2": [3.0, 4.0], FISCAL_QUARTER_FIELD_NAME: [1, 2], FISCAL_YEAR_FIELD_NAME: [2015, 2015], } ) @classmethod def make_expected_out(cls): raise NotImplementedError("make_expected_out") @classmethod def init_class_fixtures(cls): super(WithOneDayPipeline, cls).init_class_fixtures() cls.sid0 = cls.asset_finder.retrieve_asset(0) cls.expected_out = cls.make_expected_out() def test_load_one_day(self): # We want to test multiple columns dataset = MultipleColumnsQuartersEstimates(1) engine = self.make_engine() results = engine.run_pipeline( Pipeline({c.name: c.latest for c in dataset.columns}), start_date=pd.Timestamp("2015-01-15", tz="utc"), end_date=pd.Timestamp("2015-01-15", tz="utc"), ) assert_frame_equal(results.sort_index(1), self.expected_out.sort_index(1)) class PreviousWithOneDayPipeline(WithOneDayPipeline, ZiplineTestCase): """ Tests that previous quarter loader correctly breaks if an incorrect number of quarters is passed. """ @classmethod def make_loader(cls, events, columns): return PreviousEarningsEstimatesLoader(events, columns) @classmethod def make_expected_out(cls): return pd.DataFrame( { EVENT_DATE_FIELD_NAME: pd.Timestamp("2015-01-10"), "estimate1": 1.0, "estimate2": 3.0, FISCAL_QUARTER_FIELD_NAME: 1.0, FISCAL_YEAR_FIELD_NAME: 2015.0, }, index=pd.MultiIndex.from_tuples( ((pd.Timestamp("2015-01-15", tz="utc"), cls.sid0),) ), ) class NextWithOneDayPipeline(WithOneDayPipeline, ZiplineTestCase): """ Tests that next quarter loader correctly breaks if an incorrect number of quarters is passed. """ @classmethod def make_loader(cls, events, columns): return NextEarningsEstimatesLoader(events, columns) @classmethod def make_expected_out(cls): return pd.DataFrame( { EVENT_DATE_FIELD_NAME: pd.Timestamp("2015-01-20"), "estimate1": 2.0, "estimate2": 4.0, FISCAL_QUARTER_FIELD_NAME: 2.0, FISCAL_YEAR_FIELD_NAME: 2015.0, }, index=pd.MultiIndex.from_tuples( ((pd.Timestamp("2015-01-15", tz="utc"), cls.sid0),) ), ) dummy_df = pd.DataFrame( {SID_FIELD_NAME: 0}, columns=[ SID_FIELD_NAME, TS_FIELD_NAME, EVENT_DATE_FIELD_NAME, FISCAL_QUARTER_FIELD_NAME, FISCAL_YEAR_FIELD_NAME, "estimate", ], index=[0], ) class WithWrongLoaderDefinition(WithEstimates): """ ZiplineTestCase mixin providing cls.events as a class level fixture and defining a test for all inheritors to use. Attributes ---------- events : pd.DataFrame A simple DataFrame with columns needed for estimates and a single sid and no other data. Tests ------ test_wrong_num_announcements_passed() Tests that loading with an incorrect quarter number raises an error. test_no_num_announcements_attr() Tests that the loader throws an AssertionError if the dataset being loaded has no `num_announcements` attribute. """ @classmethod def make_events(cls): return dummy_df def test_wrong_num_announcements_passed(self): bad_dataset1 = QuartersEstimates(-1) bad_dataset2 = QuartersEstimates(-2) good_dataset = QuartersEstimates(1) engine = self.make_engine() columns = { c.name + str(dataset.num_announcements): c.latest for dataset in (bad_dataset1, bad_dataset2, good_dataset) for c in dataset.columns } p = Pipeline(columns) err_msg = ( r"Passed invalid number of quarters -[0-9],-[0-9]; " r"must pass a number of quarters >= 0" ) with pytest.raises(ValueError, match=err_msg): engine.run_pipeline( p, start_date=self.trading_days[0], end_date=self.trading_days[-1], ) def test_no_num_announcements_attr(self): dataset = QuartersEstimatesNoNumQuartersAttr(1) engine = self.make_engine() p = Pipeline({c.name: c.latest for c in dataset.columns}) with pytest.raises(AttributeError): engine.run_pipeline( p, start_date=self.trading_days[0], end_date=self.trading_days[-1], ) class PreviousWithWrongNumQuarters(WithWrongLoaderDefinition, ZiplineTestCase): """ Tests that previous quarter loader correctly breaks if an incorrect number of quarters is passed. """ @classmethod def make_loader(cls, events, columns): return PreviousEarningsEstimatesLoader(events, columns) class NextWithWrongNumQuarters(WithWrongLoaderDefinition, ZiplineTestCase): """ Tests that next quarter loader correctly breaks if an incorrect number of quarters is passed. """ @classmethod def make_loader(cls, events, columns): return NextEarningsEstimatesLoader(events, columns) options = [ "split_adjustments_loader", "split_adjusted_column_names", "split_adjusted_asof", ] class WrongSplitsLoaderDefinition(WithEstimates, ZiplineTestCase): """ Test class that tests that loaders break correctly when incorrectly instantiated. Tests ----- test_extra_splits_columns_passed(SplitAdjustedEstimatesLoader) A test that checks that the loader correctly breaks when an unexpected column is passed in the list of split-adjusted columns. """ @classmethod def init_class_fixtures(cls): super(WithEstimates, cls).init_class_fixtures() @parameterized.expand( itertools.product( ( NextSplitAdjustedEarningsEstimatesLoader, PreviousSplitAdjustedEarningsEstimatesLoader, ), ) ) def test_extra_splits_columns_passed(self, loader): columns = { Estimates.event_date: "event_date", Estimates.fiscal_quarter: "fiscal_quarter", Estimates.fiscal_year: "fiscal_year", Estimates.estimate: "estimate", } with pytest.raises(ValueError): loader( dummy_df, {column.name: val for column, val in columns.items()}, split_adjustments_loader=self.adjustment_reader, split_adjusted_column_names=["estimate", "extra_col"], split_adjusted_asof=pd.Timestamp("2015-01-01"), ) class WithEstimatesTimeZero(WithEstimates): """ ZiplineTestCase mixin providing cls.events as a class level fixture and defining a test for all inheritors to use. Attributes ---------- cls.events : pd.DataFrame Generated dynamically in order to test inter-leavings of estimates and event dates for multiple quarters to make sure that we select the right immediate 'next' or 'previous' quarter relative to each date - i.e., the right 'time zero' on the timeline. We care about selecting the right 'time zero' because we use that to calculate which quarter's data needs to be returned for each day. Methods ------- get_expected_estimate(q1_knowledge, q2_knowledge, comparable_date) -> pd.DataFrame Retrieves the expected estimate given the latest knowledge about each quarter and the date on which the estimate is being requested. If there is no expected estimate, returns an empty DataFrame. Tests ------ test_estimates() Tests that we get the right 'time zero' value on each day for each sid and for each column. """ # Shorter date range for performance END_DATE = pd.Timestamp("2015-01-28", tz="utc") q1_knowledge_dates = [ pd.Timestamp("2015-01-01"), pd.Timestamp("2015-01-04"), pd.Timestamp("2015-01-07"), pd.Timestamp("2015-01-11"), ] q2_knowledge_dates = [ pd.Timestamp("2015-01-14"), pd.Timestamp("2015-01-17"), pd.Timestamp("2015-01-20"), pd.Timestamp("2015-01-23"), ] # We want to model the possibility of an estimate predicting a release date # that doesn't match the actual release. This could be done by dynamically # generating more combinations with different release dates, but that # significantly increases the amount of time it takes to run the tests. # These hard-coded cases are sufficient to know that we can update our # beliefs when we get new information. q1_release_dates = [ pd.Timestamp("2015-01-13"), pd.Timestamp("2015-01-14"), ] # One day late q2_release_dates = [ pd.Timestamp("2015-01-25"), # One day early pd.Timestamp("2015-01-26"), ] @classmethod def make_events(cls): """ In order to determine which estimate we care about for a particular sid, we need to look at all estimates that we have for that sid and their associated event dates. We define q1 < q2, and thus event1 < event2 since event1 occurs during q1 and event2 occurs during q2 and we assume that there can only be 1 event per quarter. We assume that there can be multiple estimates per quarter leading up to the event. We assume that estimates will not surpass the relevant event date. We will look at 2 estimates for an event before the event occurs, since that is the simplest scenario that covers the interesting edge cases: - estimate values changing - a release date changing - estimates for different quarters interleaving Thus, we generate all possible inter-leavings of 2 estimates per quarter-event where estimate1 < estimate2 and all estimates are < the relevant event and assign each of these inter-leavings to a different sid. """ sid_estimates = [] sid_releases = [] # We want all permutations of 2 knowledge dates per quarter. it = enumerate( itertools.permutations(cls.q1_knowledge_dates + cls.q2_knowledge_dates, 4) ) for sid, (q1e1, q1e2, q2e1, q2e2) in it: # We're assuming that estimates must come before the relevant # release. if ( q1e1 < q1e2 and q2e1 < q2e2 # All estimates are < Q2's event, so just constrain Q1 # estimates. and q1e1 < cls.q1_release_dates[0] and q1e2 < cls.q1_release_dates[0] ): sid_estimates.append( cls.create_estimates_df(q1e1, q1e2, q2e1, q2e2, sid) ) sid_releases.append(cls.create_releases_df(sid)) return pd.concat(sid_estimates + sid_releases).reset_index(drop=True) @classmethod def get_sids(cls): sids = cls.events[SID_FIELD_NAME].unique() # Tack on an extra sid to make sure that sids with no data are # included but have all-null columns. return list(sids) + [max(sids) + 1] @classmethod def create_releases_df(cls, sid): # Final release dates never change. The quarters have very tight date # ranges in order to reduce the number of dates we need to iterate # through when testing. return pd.DataFrame( { TS_FIELD_NAME: [pd.Timestamp("2015-01-13"), pd.Timestamp("2015-01-26")], EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-13"), pd.Timestamp("2015-01-26"), ], "estimate": [0.5, 0.8], FISCAL_QUARTER_FIELD_NAME: [1.0, 2.0], FISCAL_YEAR_FIELD_NAME: [2015.0, 2015.0], SID_FIELD_NAME: sid, } ) @classmethod def create_estimates_df(cls, q1e1, q1e2, q2e1, q2e2, sid): return pd.DataFrame( { EVENT_DATE_FIELD_NAME: cls.q1_release_dates + cls.q2_release_dates, "estimate": [0.1, 0.2, 0.3, 0.4], FISCAL_QUARTER_FIELD_NAME: [1.0, 1.0, 2.0, 2.0], FISCAL_YEAR_FIELD_NAME: [2015.0, 2015.0, 2015.0, 2015.0], TS_FIELD_NAME: [q1e1, q1e2, q2e1, q2e2], SID_FIELD_NAME: sid, } ) def get_expected_estimate(self, q1_knowledge, q2_knowledge, comparable_date): return pd.DataFrame() def test_estimates(self): dataset = QuartersEstimates(1) engine = self.make_engine() results = engine.run_pipeline( Pipeline({c.name: c.latest for c in dataset.columns}), start_date=self.trading_days[1], end_date=self.trading_days[-2], ) for sid in self.ASSET_FINDER_EQUITY_SIDS: sid_estimates = results.xs(sid, level=1) # Separate assertion for all-null DataFrame to avoid setting # column dtypes on `all_expected`. if sid == max(self.ASSET_FINDER_EQUITY_SIDS): assert sid_estimates.isnull().all().all() else: ts_sorted_estimates = self.events[ self.events[SID_FIELD_NAME] == sid ].sort_values(TS_FIELD_NAME) q1_knowledge = ts_sorted_estimates[ ts_sorted_estimates[FISCAL_QUARTER_FIELD_NAME] == 1 ] q2_knowledge = ts_sorted_estimates[ ts_sorted_estimates[FISCAL_QUARTER_FIELD_NAME] == 2 ] all_expected = pd.concat( [ self.get_expected_estimate( q1_knowledge[ q1_knowledge[TS_FIELD_NAME] <= date.tz_localize(None) ], q2_knowledge[ q2_knowledge[TS_FIELD_NAME] <= date.tz_localize(None) ], date.tz_localize(None), ).set_index([[date]]) for date in sid_estimates.index ], axis=0, ) sid_estimates.index = all_expected.index.copy() assert_equal(all_expected[sid_estimates.columns], sid_estimates) class NextEstimate(WithEstimatesTimeZero, ZiplineTestCase): @classmethod def make_loader(cls, events, columns): return NextEarningsEstimatesLoader(events, columns) def get_expected_estimate(self, q1_knowledge, q2_knowledge, comparable_date): # If our latest knowledge of q1 is that the release is # happening on this simulation date or later, then that's # the estimate we want to use. if ( not q1_knowledge.empty and q1_knowledge[EVENT_DATE_FIELD_NAME].iloc[-1] >= comparable_date ): return q1_knowledge.iloc[-1:] # If q1 has already happened or we don't know about it # yet and our latest knowledge indicates that q2 hasn't # happened yet, then that's the estimate we want to use. elif ( not q2_knowledge.empty and q2_knowledge[EVENT_DATE_FIELD_NAME].iloc[-1] >= comparable_date ): return q2_knowledge.iloc[-1:] return pd.DataFrame(columns=q1_knowledge.columns, index=[comparable_date]) class PreviousEstimate(WithEstimatesTimeZero, ZiplineTestCase): @classmethod def make_loader(cls, events, columns): return PreviousEarningsEstimatesLoader(events, columns) def get_expected_estimate(self, q1_knowledge, q2_knowledge, comparable_date): # The expected estimate will be for q2 if the last thing # we've seen is that the release date already happened. # Otherwise, it'll be for q1, as long as the release date # for q1 has already happened. if ( not q2_knowledge.empty and q2_knowledge[EVENT_DATE_FIELD_NAME].iloc[-1] <= comparable_date ): return q2_knowledge.iloc[-1:] elif ( not q1_knowledge.empty and q1_knowledge[EVENT_DATE_FIELD_NAME].iloc[-1] <= comparable_date ): return q1_knowledge.iloc[-1:] return pd.DataFrame(columns=q1_knowledge.columns, index=[comparable_date]) class WithEstimateMultipleQuarters(WithEstimates): """ ZiplineTestCase mixin providing cls.events, cls.make_expected_out as class-level fixtures and self.test_multiple_qtrs_requested as a test. Attributes ---------- events : pd.DataFrame Simple DataFrame with estimates for 2 quarters for a single sid. Methods ------- make_expected_out() --> pd.DataFrame Returns the DataFrame that is expected as a result of running a Pipeline where estimates are requested for multiple quarters out. fill_expected_out(expected) Fills the expected DataFrame with data. Tests ------ test_multiple_qtrs_requested() Runs a Pipeline that calculate which estimates for multiple quarters out and checks that the returned columns contain data for the correct number of quarters out. """ @classmethod def make_events(cls): return pd.DataFrame( { SID_FIELD_NAME: [0] * 2, TS_FIELD_NAME: [pd.Timestamp("2015-01-01"), pd.Timestamp("2015-01-06")], EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-10"), pd.Timestamp("2015-01-20"), ], "estimate": [1.0, 2.0], FISCAL_QUARTER_FIELD_NAME: [1, 2], FISCAL_YEAR_FIELD_NAME: [2015, 2015], } ) @classmethod def init_class_fixtures(cls): super(WithEstimateMultipleQuarters, cls).init_class_fixtures() cls.expected_out = cls.make_expected_out() @classmethod def make_expected_out(cls): expected = pd.DataFrame( columns=[cls.columns[col] + "1" for col in cls.columns] + [cls.columns[col] + "2" for col in cls.columns], index=cls.trading_days, ) for (col, raw_name), suffix in itertools.product( cls.columns.items(), ("1", "2") ): expected_name = raw_name + suffix if col.dtype == datetime64ns_dtype: expected[expected_name] = pd.to_datetime(expected[expected_name]) else: expected[expected_name] = expected[expected_name].astype(col.dtype) cls.fill_expected_out(expected) return expected.reindex(cls.trading_days) def test_multiple_qtrs_requested(self): dataset1 = QuartersEstimates(1) dataset2 = QuartersEstimates(2) engine = self.make_engine() results = engine.run_pipeline( Pipeline( merge( [ {c.name + "1": c.latest for c in dataset1.columns}, {c.name + "2": c.latest for c in dataset2.columns}, ] ) ), start_date=self.trading_days[0], end_date=self.trading_days[-1], ) q1_columns = [col.name + "1" for col in self.columns] q2_columns = [col.name + "2" for col in self.columns] # We now expect a column for 1 quarter out and a column for 2 # quarters out for each of the dataset columns. assert_equal( sorted(np.array(q1_columns + q2_columns)), sorted(results.columns.values) ) assert_equal( self.expected_out.sort_index(axis=1), results.xs(0, level=1).sort_index(axis=1), ) class NextEstimateMultipleQuarters(WithEstimateMultipleQuarters, ZiplineTestCase): @classmethod def make_loader(cls, events, columns): return NextEarningsEstimatesLoader(events, columns) @classmethod def fill_expected_out(cls, expected): # Fill columns for 1 Q out for raw_name in cls.columns.values(): expected.loc[ pd.Timestamp("2015-01-01", tz="UTC") : pd.Timestamp( "2015-01-11", tz="UTC" ), raw_name + "1", ] = cls.events[raw_name].iloc[0] expected.loc[ pd.Timestamp("2015-01-11", tz="UTC") : pd.Timestamp( "2015-01-20", tz="UTC" ), raw_name + "1", ] = cls.events[raw_name].iloc[1] # Fill columns for 2 Q out # We only have an estimate and event date for 2 quarters out before # Q1's event happens; after Q1's event, we know 1 Q out but not 2 Qs # out. for col_name in ["estimate", "event_date"]: expected.loc[ pd.Timestamp("2015-01-06", tz="UTC") : pd.Timestamp( "2015-01-10", tz="UTC" ), col_name + "2", ] = cls.events[col_name].iloc[1] # But we know what FQ and FY we'd need in both Q1 and Q2 # because we know which FQ is next and can calculate from there expected.loc[ pd.Timestamp("2015-01-01", tz="UTC") : pd.Timestamp("2015-01-09", tz="UTC"), FISCAL_QUARTER_FIELD_NAME + "2", ] = 2 expected.loc[ pd.Timestamp("2015-01-12", tz="UTC") : pd.Timestamp("2015-01-20", tz="UTC"), FISCAL_QUARTER_FIELD_NAME + "2", ] = 3 expected.loc[ pd.Timestamp("2015-01-01", tz="UTC") : pd.Timestamp("2015-01-20", tz="UTC"), FISCAL_YEAR_FIELD_NAME + "2", ] = 2015 return expected class PreviousEstimateMultipleQuarters(WithEstimateMultipleQuarters, ZiplineTestCase): @classmethod def make_loader(cls, events, columns): return PreviousEarningsEstimatesLoader(events, columns) @classmethod def fill_expected_out(cls, expected): # Fill columns for 1 Q out for raw_name in cls.columns.values(): expected[raw_name + "1"].loc[ pd.Timestamp("2015-01-12", tz="UTC") : pd.Timestamp( "2015-01-19", tz="UTC" ) ] = cls.events[raw_name].iloc[0] expected[raw_name + "1"].loc[ pd.Timestamp("2015-01-20", tz="UTC") : ] = cls.events[raw_name].iloc[1] # Fill columns for 2 Q out for col_name in ["estimate", "event_date"]: expected[col_name + "2"].loc[ pd.Timestamp("2015-01-20", tz="UTC") : ] = cls.events[col_name].iloc[0] expected[FISCAL_QUARTER_FIELD_NAME + "2"].loc[ pd.Timestamp("2015-01-12", tz="UTC") : pd.Timestamp("2015-01-20", tz="UTC") ] = 4 expected[FISCAL_YEAR_FIELD_NAME + "2"].loc[ pd.Timestamp("2015-01-12", tz="UTC") : pd.Timestamp("2015-01-20", tz="UTC") ] = 2014 expected[FISCAL_QUARTER_FIELD_NAME + "2"].loc[ pd.Timestamp("2015-01-20", tz="UTC") : ] = 1 expected[FISCAL_YEAR_FIELD_NAME + "2"].loc[ pd.Timestamp("2015-01-20", tz="UTC") : ] = 2015 return expected class WithVaryingNumEstimates(WithEstimates): """ ZiplineTestCase mixin providing fixtures and a test to ensure that we have the correct overwrites when the event date changes. We want to make sure that if we have a quarter with an event date that gets pushed back, we don't start overwriting for the next quarter early. Likewise, if we have a quarter with an event date that gets pushed forward, we want to make sure that we start applying adjustments at the appropriate, earlier date, rather than the later date. Methods ------- assert_compute() Defines how to determine that results computed for the `SomeFactor` factor are correct. Tests ----- test_windows_with_varying_num_estimates() Tests that we create the correct overwrites from 2015-01-13 to 2015-01-14 regardless of how event dates were updated for each quarter for each sid. """ @classmethod def make_events(cls): return pd.DataFrame( { SID_FIELD_NAME: [0] * 3 + [1] * 3, TS_FIELD_NAME: [ pd.Timestamp("2015-01-09"), pd.Timestamp("2015-01-12"), pd.Timestamp("2015-01-13"), ] * 2, EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-12"), pd.Timestamp("2015-01-13"), pd.Timestamp("2015-01-20"), pd.Timestamp("2015-01-13"), pd.Timestamp("2015-01-12"), pd.Timestamp("2015-01-20"), ], "estimate": [11.0, 12.0, 21.0] * 2, FISCAL_QUARTER_FIELD_NAME: [1, 1, 2] * 2, FISCAL_YEAR_FIELD_NAME: [2015] * 6, } ) @classmethod def assert_compute(cls, estimate, today): raise NotImplementedError("assert_compute") def test_windows_with_varying_num_estimates(self): dataset = QuartersEstimates(1) assert_compute = self.assert_compute class SomeFactor(CustomFactor): inputs = [dataset.estimate] window_length = 3 def compute(self, today, assets, out, estimate): assert_compute(estimate, today) engine = self.make_engine() engine.run_pipeline( Pipeline({"est": SomeFactor()}), start_date=pd.Timestamp("2015-01-13", tz="utc"), # last event date we have end_date=pd.Timestamp("2015-01-14", tz="utc"), ) class PreviousVaryingNumEstimates(WithVaryingNumEstimates, ZiplineTestCase): def assert_compute(self, estimate, today): if today == pd.Timestamp("2015-01-13", tz="utc"): assert_array_equal(estimate[:, 0], np.array([np.NaN, np.NaN, 12])) assert_array_equal(estimate[:, 1], np.array([np.NaN, 12, 12])) else: assert_array_equal(estimate[:, 0], np.array([np.NaN, 12, 12])) assert_array_equal(estimate[:, 1], np.array([12, 12, 12])) @classmethod def make_loader(cls, events, columns): return PreviousEarningsEstimatesLoader(events, columns) class NextVaryingNumEstimates(WithVaryingNumEstimates, ZiplineTestCase): def assert_compute(self, estimate, today): if today == pd.Timestamp("2015-01-13", tz="utc"): assert_array_equal(estimate[:, 0], np.array([11, 12, 12])) assert_array_equal(estimate[:, 1], np.array([np.NaN, np.NaN, 21])) else: assert_array_equal(estimate[:, 0], np.array([np.NaN, 21, 21])) assert_array_equal(estimate[:, 1], np.array([np.NaN, 21, 21])) @classmethod def make_loader(cls, events, columns): return NextEarningsEstimatesLoader(events, columns) class WithEstimateWindows(WithEstimates): """ ZiplineTestCase mixin providing fixures and a test to test running a Pipeline with an estimates loader over differently-sized windows. Attributes ---------- events : pd.DataFrame DataFrame with estimates for 2 quarters for 2 sids. window_test_start_date : pd.Timestamp The date from which the window should start. timelines : dict[int -> pd.DataFrame] A dictionary mapping to the number of quarters out to snapshots of how the data should look on each date in the date range. Methods ------- make_expected_timelines() -> dict[int -> pd.DataFrame] Creates a dictionary of expected data. See `timelines`, above. Tests ----- test_estimate_windows_at_quarter_boundaries() Tests that we overwrite values with the correct quarter's estimate at the correct dates when we have a factor that asks for a window of data. """ END_DATE = pd.Timestamp("2015-02-10", tz="utc") window_test_start_date = pd.Timestamp("2015-01-05") critical_dates = [ pd.Timestamp("2015-01-09", tz="utc"), pd.Timestamp("2015-01-15", tz="utc"), pd.Timestamp("2015-01-20", tz="utc"), pd.Timestamp("2015-01-26", tz="utc"), pd.Timestamp("2015-02-05", tz="utc"), pd.Timestamp("2015-02-10", tz="utc"), ] # Starting date, number of announcements out. window_test_cases = list(itertools.product(critical_dates, (1, 2))) @classmethod def make_events(cls): # Typical case: 2 consecutive quarters. sid_0_timeline = pd.DataFrame( { TS_FIELD_NAME: [ cls.window_test_start_date, pd.Timestamp("2015-01-20"), pd.Timestamp("2015-01-12"), pd.Timestamp("2015-02-10"), # We want a case where we get info for a later # quarter before the current quarter is over but # after the split_asof_date to make sure that # we choose the correct date to overwrite until. pd.Timestamp("2015-01-18"), ], EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-20"), pd.Timestamp("2015-01-20"), pd.Timestamp("2015-02-10"), pd.Timestamp("2015-02-10"), pd.Timestamp("2015-04-01"), ], "estimate": [100.0, 101.0] + [200.0, 201.0] + [400], FISCAL_QUARTER_FIELD_NAME: [1] * 2 + [2] * 2 + [4], FISCAL_YEAR_FIELD_NAME: 2015, SID_FIELD_NAME: 0, } ) # We want a case where we skip a quarter. We never find out about Q2. sid_10_timeline = pd.DataFrame( { TS_FIELD_NAME: [ pd.Timestamp("2015-01-09"), pd.Timestamp("2015-01-12"), pd.Timestamp("2015-01-09"), pd.Timestamp("2015-01-15"), ], EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-22"), pd.Timestamp("2015-01-22"), pd.Timestamp("2015-02-05"), pd.Timestamp("2015-02-05"), ], "estimate": [110.0, 111.0] + [310.0, 311.0], FISCAL_QUARTER_FIELD_NAME: [1] * 2 + [3] * 2, FISCAL_YEAR_FIELD_NAME: 2015, SID_FIELD_NAME: 10, } ) # We want to make sure we have correct overwrites when sid quarter # boundaries collide. This sid's quarter boundaries collide with sid 0. sid_20_timeline = pd.DataFrame( { TS_FIELD_NAME: [ cls.window_test_start_date, pd.Timestamp("2015-01-07"), cls.window_test_start_date, pd.Timestamp("2015-01-17"), ], EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-20"), pd.Timestamp("2015-01-20"), pd.Timestamp("2015-02-10"), pd.Timestamp("2015-02-10"), ], "estimate": [120.0, 121.0] + [220.0, 221.0], FISCAL_QUARTER_FIELD_NAME: [1] * 2 + [2] * 2, FISCAL_YEAR_FIELD_NAME: 2015, SID_FIELD_NAME: 20, } ) concatted = pd.concat( [sid_0_timeline, sid_10_timeline, sid_20_timeline] ).reset_index() np.random.seed(0) return concatted.reindex(np.random.permutation(concatted.index)) @classmethod def get_sids(cls): sids = sorted(cls.events[SID_FIELD_NAME].unique()) # Add extra sids between sids in our data. We want to test that we # apply adjustments to the correct sids. return [ sid for i in range(len(sids) - 1) for sid in range(sids[i], sids[i + 1]) ] + [sids[-1]] @classmethod def make_expected_timelines(cls): return {} @classmethod def init_class_fixtures(cls): super(WithEstimateWindows, cls).init_class_fixtures() cls.create_expected_df_for_factor_compute = partial( create_expected_df_for_factor_compute, cls.window_test_start_date, cls.get_sids(), ) cls.timelines = cls.make_expected_timelines() @parameterized.expand(window_test_cases) def test_estimate_windows_at_quarter_boundaries( self, start_date, num_announcements_out ): dataset = QuartersEstimates(num_announcements_out) trading_days = self.trading_days timelines = self.timelines # The window length should be from the starting index back to the first # date on which we got data. The goal is to ensure that as we # progress through the timeline, all data we got, starting from that # first date, is correctly overwritten. window_len = ( self.trading_days.get_loc(start_date) - self.trading_days.get_loc(self.window_test_start_date) + 1 ) class SomeFactor(CustomFactor): inputs = [dataset.estimate] window_length = window_len def compute(self, today, assets, out, estimate): today_idx = trading_days.get_loc(today) today_timeline = ( timelines[num_announcements_out] .loc[today] .reindex(trading_days[: today_idx + 1]) .values ) timeline_start_idx = len(today_timeline) - window_len assert_almost_equal(estimate, today_timeline[timeline_start_idx:]) engine = self.make_engine() engine.run_pipeline( Pipeline({"est": SomeFactor()}), start_date=start_date, # last event date we have end_date=pd.Timestamp("2015-02-10", tz="utc"), ) class PreviousEstimateWindows(WithEstimateWindows, ZiplineTestCase): @classmethod def make_loader(cls, events, columns): return PreviousEarningsEstimatesLoader(events, columns) @classmethod def make_expected_timelines(cls): oneq_previous = pd.concat( [ pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, np.NaN, cls.window_test_start_date), ], end_date, ) for end_date in pd.date_range("2015-01-09", "2015-01-19") ] ), cls.create_expected_df_for_factor_compute( [ (0, 101, pd.Timestamp("2015-01-20")), (10, np.NaN, cls.window_test_start_date), (20, 121, pd.Timestamp("2015-01-20")), ], pd.Timestamp("2015-01-20"), ), cls.create_expected_df_for_factor_compute( [ (0, 101, pd.Timestamp("2015-01-20")), (10, np.NaN, cls.window_test_start_date), (20, 121, pd.Timestamp("2015-01-20")), ], pd.Timestamp("2015-01-21"), ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 101, pd.Timestamp("2015-01-20")), (10, 111, pd.Timestamp("2015-01-22")), (20, 121, pd.Timestamp("2015-01-20")), ], end_date, ) for end_date in pd.date_range("2015-01-22", "2015-02-04") ] ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 101, pd.Timestamp("2015-01-20")), (10, 311, pd.Timestamp("2015-02-05")), (20, 121, pd.Timestamp("2015-01-20")), ], end_date, ) for end_date in pd.date_range("2015-02-05", "2015-02-09") ] ), cls.create_expected_df_for_factor_compute( [ (0, 201, pd.Timestamp("2015-02-10")), (10, 311, pd.Timestamp("2015-02-05")), (20, 221, pd.Timestamp("2015-02-10")), ], pd.Timestamp("2015-02-10"), ), ] ) twoq_previous = pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, np.NaN, cls.window_test_start_date), ], end_date, ) for end_date in pd.date_range("2015-01-09", "2015-02-09") ] # We never get estimates for S1 for 2Q ago because once Q3 # becomes our previous quarter, 2Q ago would be Q2, and we have # no data on it. + [ cls.create_expected_df_for_factor_compute( [ (0, 101, pd.Timestamp("2015-02-10")), (10, np.NaN, pd.Timestamp("2015-02-05")), (20, 121, pd.Timestamp("2015-02-10")), ], pd.Timestamp("2015-02-10"), ) ] ) return {1: oneq_previous, 2: twoq_previous} class NextEstimateWindows(WithEstimateWindows, ZiplineTestCase): @classmethod def make_loader(cls, events, columns): return NextEarningsEstimatesLoader(events, columns) @classmethod def make_expected_timelines(cls): oneq_next = pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 100, cls.window_test_start_date), (10, 110, pd.Timestamp("2015-01-09")), (20, 120, cls.window_test_start_date), (20, 121, pd.Timestamp("2015-01-07")), ], pd.Timestamp("2015-01-09"), ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 100, cls.window_test_start_date), (10, 110, pd.Timestamp("2015-01-09")), (10, 111, pd.Timestamp("2015-01-12")), (20, 120, cls.window_test_start_date), (20, 121, pd.Timestamp("2015-01-07")), ], end_date, ) for end_date in pd.date_range("2015-01-12", "2015-01-19") ] ), cls.create_expected_df_for_factor_compute( [ (0, 100, cls.window_test_start_date), (0, 101, pd.Timestamp("2015-01-20")), (10, 110, pd.Timestamp("2015-01-09")), (10, 111, pd.Timestamp("2015-01-12")), (20, 120, cls.window_test_start_date), (20, 121, pd.Timestamp("2015-01-07")), ], pd.Timestamp("2015-01-20"), ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 200, pd.Timestamp("2015-01-12")), (10, 110, pd.Timestamp("2015-01-09")), (10, 111, pd.Timestamp("2015-01-12")), (20, 220, cls.window_test_start_date), (20, 221, pd.Timestamp("2015-01-17")), ], end_date, ) for end_date in pd.date_range("2015-01-21", "2015-01-22") ] ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 200, pd.Timestamp("2015-01-12")), (10, 310, pd.Timestamp("2015-01-09")), (10, 311, pd.Timestamp("2015-01-15")), (20, 220, cls.window_test_start_date), (20, 221, pd.Timestamp("2015-01-17")), ], end_date, ) for end_date in pd.date_range("2015-01-23", "2015-02-05") ] ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 200, pd.Timestamp("2015-01-12")), (10, np.NaN, cls.window_test_start_date), (20, 220, cls.window_test_start_date), (20, 221, pd.Timestamp("2015-01-17")), ], end_date, ) for end_date in pd.date_range("2015-02-06", "2015-02-09") ] ), cls.create_expected_df_for_factor_compute( [ (0, 200, pd.Timestamp("2015-01-12")), (0, 201, pd.Timestamp("2015-02-10")), (10, np.NaN, cls.window_test_start_date), (20, 220, cls.window_test_start_date), (20, 221, pd.Timestamp("2015-01-17")), ], pd.Timestamp("2015-02-10"), ), ] ) twoq_next = pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, 220, cls.window_test_start_date), ], end_date, ) for end_date in pd.date_range("2015-01-09", "2015-01-11") ] + [ cls.create_expected_df_for_factor_compute( [ (0, 200, pd.Timestamp("2015-01-12")), (10, np.NaN, cls.window_test_start_date), (20, 220, cls.window_test_start_date), ], end_date, ) for end_date in pd.date_range("2015-01-12", "2015-01-16") ] + [ cls.create_expected_df_for_factor_compute( [ (0, 200, pd.Timestamp("2015-01-12")), (10, np.NaN, cls.window_test_start_date), (20, 220, cls.window_test_start_date), (20, 221, pd.Timestamp("2015-01-17")), ], pd.Timestamp("2015-01-20"), ) ] + [ cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, np.NaN, cls.window_test_start_date), ], end_date, ) for end_date in pd.date_range("2015-01-21", "2015-02-10") ] ) return {1: oneq_next, 2: twoq_next} class WithSplitAdjustedWindows(WithEstimateWindows): """ ZiplineTestCase mixin providing fixures and a test to test running a Pipeline with an estimates loader over differently-sized windows and with split adjustments. """ split_adjusted_asof_date = pd.Timestamp("2015-01-14") @classmethod def make_events(cls): # Add an extra sid that has a release before the split-asof-date in # order to test that we're reversing splits correctly in the previous # case (without an overwrite) and in the next case (with an overwrite). sid_30 = pd.DataFrame( { TS_FIELD_NAME: [ cls.window_test_start_date, pd.Timestamp("2015-01-09"), # For Q2, we want it to start early enough # that we can have several adjustments before # the end of the first quarter so that we # can test un-adjusting & readjusting with an # overwrite. cls.window_test_start_date, # We want the Q2 event date to be enough past # the split-asof-date that we can have # several splits and can make sure that they # are applied correctly. pd.Timestamp("2015-01-20"), ], EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-09"), pd.Timestamp("2015-01-09"), pd.Timestamp("2015-01-20"), pd.Timestamp("2015-01-20"), ], "estimate": [130.0, 131.0, 230.0, 231.0], FISCAL_QUARTER_FIELD_NAME: [1] * 2 + [2] * 2, FISCAL_YEAR_FIELD_NAME: 2015, SID_FIELD_NAME: 30, } ) # An extra sid to test no splits before the split-adjusted-asof-date. # We want an event before and after the split-adjusted-asof-date & # timestamps for data points also before and after # split-adjsuted-asof-date (but also before the split dates, so that # we can test that splits actually get applied at the correct times). sid_40 = pd.DataFrame( { TS_FIELD_NAME: [pd.Timestamp("2015-01-09"), pd.Timestamp("2015-01-15")], EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-09"), pd.Timestamp("2015-02-10"), ], "estimate": [140.0, 240.0], FISCAL_QUARTER_FIELD_NAME: [1, 2], FISCAL_YEAR_FIELD_NAME: 2015, SID_FIELD_NAME: 40, } ) # An extra sid to test all splits before the # split-adjusted-asof-date. All timestamps should be before that date # so that we have cases where we un-apply and re-apply splits. sid_50 = pd.DataFrame( { TS_FIELD_NAME: [pd.Timestamp("2015-01-09"), pd.Timestamp("2015-01-12")], EVENT_DATE_FIELD_NAME: [ pd.Timestamp("2015-01-09"), pd.Timestamp("2015-02-10"), ], "estimate": [150.0, 250.0], FISCAL_QUARTER_FIELD_NAME: [1, 2], FISCAL_YEAR_FIELD_NAME: 2015, SID_FIELD_NAME: 50, } ) return pd.concat( [ # Slightly hacky, but want to make sure we're using the same # events as WithEstimateWindows. cls.__base__.make_events(), sid_30, sid_40, sid_50, ] ) @classmethod def make_splits_data(cls): # For sid 0, we want to apply a series of splits before and after the # split-adjusted-asof-date we well as between quarters (for the # previous case, where we won't see any values until after the event # happens). sid_0_splits = pd.DataFrame( { SID_FIELD_NAME: 0, "ratio": (-1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 100), "effective_date": ( pd.Timestamp("2014-01-01"), # Filter out # Split before Q1 event & after first estimate pd.Timestamp("2015-01-07"), # Split before Q1 event pd.Timestamp("2015-01-09"), # Split before Q1 event pd.Timestamp("2015-01-13"), # Split before Q1 event pd.Timestamp("2015-01-15"), # Split before Q1 event pd.Timestamp("2015-01-18"), # Split after Q1 event and before Q2 event pd.Timestamp("2015-01-30"), # Filter out - this is after our date index pd.Timestamp("2016-01-01"), ), } ) sid_10_splits = pd.DataFrame( { SID_FIELD_NAME: 10, "ratio": (0.2, 0.3), "effective_date": ( # We want a split before the first estimate and before the # split-adjusted-asof-date but within our calendar index so # that we can test that the split is NEVER applied. pd.Timestamp("2015-01-07"), # Apply a single split before Q1 event. pd.Timestamp("2015-01-20"), ), } ) # We want a sid with split dates that collide with another sid (0) to # make sure splits are correctly applied for both sids. sid_20_splits = pd.DataFrame( { SID_FIELD_NAME: 20, "ratio": ( 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, ), "effective_date": ( pd.Timestamp("2015-01-07"), pd.Timestamp("2015-01-09"), pd.Timestamp("2015-01-13"), pd.Timestamp("2015-01-15"), pd.Timestamp("2015-01-18"), pd.Timestamp("2015-01-30"), ), } ) # This sid has event dates that are shifted back so that we can test # cases where an event occurs before the split-asof-date. sid_30_splits = pd.DataFrame( { SID_FIELD_NAME: 30, "ratio": (8, 9, 10, 11, 12), "effective_date": ( # Split before the event and before the # split-asof-date. pd.Timestamp("2015-01-07"), # Split on date of event but before the # split-asof-date. pd.Timestamp("2015-01-09"), # Split after the event, but before the # split-asof-date. pd.Timestamp("2015-01-13"), pd.Timestamp("2015-01-15"), pd.Timestamp("2015-01-18"), ), } ) # No splits for a sid before the split-adjusted-asof-date. sid_40_splits = pd.DataFrame( { SID_FIELD_NAME: 40, "ratio": (13, 14), "effective_date": ( pd.Timestamp("2015-01-20"), pd.Timestamp("2015-01-22"), ), } ) # No splits for a sid after the split-adjusted-asof-date. sid_50_splits = pd.DataFrame( { SID_FIELD_NAME: 50, "ratio": (15, 16), "effective_date": ( pd.Timestamp("2015-01-13"), pd.Timestamp("2015-01-14"), ), } ) return pd.concat( [ sid_0_splits, sid_10_splits, sid_20_splits, sid_30_splits, sid_40_splits, sid_50_splits, ] ) class PreviousWithSplitAdjustedWindows(WithSplitAdjustedWindows, ZiplineTestCase): @classmethod def make_loader(cls, events, columns): return PreviousSplitAdjustedEarningsEstimatesLoader( events, columns, split_adjustments_loader=cls.adjustment_reader, split_adjusted_column_names=["estimate"], split_adjusted_asof=cls.split_adjusted_asof_date, ) @classmethod def make_expected_timelines(cls): oneq_previous = pd.concat( [ pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, np.NaN, cls.window_test_start_date), # Undo all adjustments that haven't happened yet. (30, 131 * 1 / 10, pd.Timestamp("2015-01-09")), (40, 140.0, pd.Timestamp("2015-01-09")), (50, 150 * 1 / 15 * 1 / 16, pd.Timestamp("2015-01-09")), ], end_date, ) for end_date in pd.date_range("2015-01-09", "2015-01-12") ] ), cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, np.NaN, cls.window_test_start_date), (30, 131, pd.Timestamp("2015-01-09")), (40, 140.0, pd.Timestamp("2015-01-09")), (50, 150.0 * 1 / 16, pd.Timestamp("2015-01-09")), ], pd.Timestamp("2015-01-13"), ), cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, np.NaN, cls.window_test_start_date), (30, 131, pd.Timestamp("2015-01-09")), (40, 140.0, pd.Timestamp("2015-01-09")), (50, 150.0, pd.Timestamp("2015-01-09")), ], pd.Timestamp("2015-01-14"), ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, np.NaN, cls.window_test_start_date), (30, 131 * 11, pd.Timestamp("2015-01-09")), (40, 140.0, pd.Timestamp("2015-01-09")), (50, 150.0, pd.Timestamp("2015-01-09")), ], end_date, ) for end_date in pd.date_range("2015-01-15", "2015-01-16") ] ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 101, pd.Timestamp("2015-01-20")), (10, np.NaN, cls.window_test_start_date), (20, 121 * 0.7 * 0.8, pd.Timestamp("2015-01-20")), (30, 231, pd.Timestamp("2015-01-20")), (40, 140.0 * 13, pd.Timestamp("2015-01-09")), (50, 150.0, pd.Timestamp("2015-01-09")), ], end_date, ) for end_date in pd.date_range("2015-01-20", "2015-01-21") ] ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 101, pd.Timestamp("2015-01-20")), (10, 111 * 0.3, pd.Timestamp("2015-01-22")), (20, 121 * 0.7 * 0.8, pd.Timestamp("2015-01-20")), (30, 231, pd.Timestamp("2015-01-20")), (40, 140.0 * 13 * 14, pd.Timestamp("2015-01-09")), (50, 150.0, pd.Timestamp("2015-01-09")), ], end_date, ) for end_date in pd.date_range("2015-01-22", "2015-01-29") ] ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 101 * 7, pd.Timestamp("2015-01-20")), (10, 111 * 0.3, pd.Timestamp("2015-01-22")), (20, 121 * 0.7 * 0.8 * 0.9, pd.Timestamp("2015-01-20")), (30, 231, pd.Timestamp("2015-01-20")), (40, 140.0 * 13 * 14, pd.Timestamp("2015-01-09")), (50, 150.0, pd.Timestamp("2015-01-09")), ], end_date, ) for end_date in pd.date_range("2015-01-30", "2015-02-04") ] ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 101 * 7, pd.Timestamp("2015-01-20")), (10, 311 * 0.3, pd.Timestamp("2015-02-05")), (20, 121 * 0.7 * 0.8 * 0.9, pd.Timestamp("2015-01-20")), (30, 231, pd.Timestamp("2015-01-20")), (40, 140.0 * 13 * 14, pd.Timestamp("2015-01-09")), (50, 150.0, pd.Timestamp("2015-01-09")), ], end_date, ) for end_date in pd.date_range("2015-02-05", "2015-02-09") ] ), cls.create_expected_df_for_factor_compute( [ (0, 201, pd.Timestamp("2015-02-10")), (10, 311 * 0.3, pd.Timestamp("2015-02-05")), (20, 221 * 0.8 * 0.9, pd.Timestamp("2015-02-10")), (30, 231, pd.Timestamp("2015-01-20")), (40, 240.0 * 13 * 14, pd.Timestamp("2015-02-10")), (50, 250.0, pd.Timestamp("2015-02-10")), ], pd.Timestamp("2015-02-10"), ), ] ) twoq_previous = pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, np.NaN, cls.window_test_start_date), (30, np.NaN, cls.window_test_start_date), ], end_date, ) for end_date in pd.date_range("2015-01-09", "2015-01-19") ] + [ cls.create_expected_df_for_factor_compute( [ (0, np.NaN, cls.window_test_start_date), (10, np.NaN, cls.window_test_start_date), (20, np.NaN, cls.window_test_start_date), (30, 131 * 11 * 12, pd.Timestamp("2015-01-20")), ], end_date, ) for end_date in pd.date_range("2015-01-20", "2015-02-09") ] # We never get estimates for S1 for 2Q ago because once Q3 # becomes our previous quarter, 2Q ago would be Q2, and we have # no data on it. + [ cls.create_expected_df_for_factor_compute( [ (0, 101 * 7, pd.Timestamp("2015-02-10")), (10, np.NaN, pd.Timestamp("2015-02-05")), (20, 121 * 0.7 * 0.8 * 0.9, pd.Timestamp("2015-02-10")), (30, 131 * 11 * 12, pd.Timestamp("2015-01-20")), (40, 140.0 * 13 * 14, pd.Timestamp("2015-02-10")), (50, 150.0, pd.Timestamp("2015-02-10")), ], pd.Timestamp("2015-02-10"), ) ] ) return {1: oneq_previous, 2: twoq_previous} class NextWithSplitAdjustedWindows(WithSplitAdjustedWindows, ZiplineTestCase): @classmethod def make_loader(cls, events, columns): return NextSplitAdjustedEarningsEstimatesLoader( events, columns, split_adjustments_loader=cls.adjustment_reader, split_adjusted_column_names=["estimate"], split_adjusted_asof=cls.split_adjusted_asof_date, ) @classmethod def make_expected_timelines(cls): oneq_next = pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 100 * 1 / 4, cls.window_test_start_date), (10, 110, pd.Timestamp("2015-01-09")), (20, 120 * 5 / 3, cls.window_test_start_date), (20, 121 * 5 / 3, pd.Timestamp("2015-01-07")), (30, 130 * 1 / 10, cls.window_test_start_date), (30, 131 * 1 / 10, pd.Timestamp("2015-01-09")), (40, 140, pd.Timestamp("2015-01-09")), (50, 150.0 * 1 / 15 * 1 / 16, pd.Timestamp("2015-01-09")), ], pd.Timestamp("2015-01-09"), ), cls.create_expected_df_for_factor_compute( [ (0, 100 * 1 / 4, cls.window_test_start_date), (10, 110, pd.Timestamp("2015-01-09")), (10, 111, pd.Timestamp("2015-01-12")), (20, 120 * 5 / 3, cls.window_test_start_date), (20, 121 * 5 / 3, pd.Timestamp("2015-01-07")), (30, 230 * 1 / 10, cls.window_test_start_date), (40, np.NaN, pd.Timestamp("2015-01-10")), (50, 250.0 * 1 / 15 * 1 / 16, pd.Timestamp("2015-01-12")), ], pd.Timestamp("2015-01-12"), ), cls.create_expected_df_for_factor_compute( [ (0, 100, cls.window_test_start_date), (10, 110, pd.Timestamp("2015-01-09")), (10, 111, pd.Timestamp("2015-01-12")), (20, 120, cls.window_test_start_date), (20, 121, pd.Timestamp("2015-01-07")), (30, 230, cls.window_test_start_date), (40, np.NaN, pd.Timestamp("2015-01-10")), (50, 250.0 * 1 / 16, pd.Timestamp("2015-01-12")), ], pd.Timestamp("2015-01-13"), ), cls.create_expected_df_for_factor_compute( [ (0, 100, cls.window_test_start_date), (10, 110, pd.Timestamp("2015-01-09")), (10, 111, pd.Timestamp("2015-01-12")), (20, 120, cls.window_test_start_date), (20, 121, pd.Timestamp("2015-01-07")), (30, 230, cls.window_test_start_date), (40, np.NaN, pd.Timestamp("2015-01-10")), (50, 250.0, pd.Timestamp("2015-01-12")), ], pd.Timestamp("2015-01-14"), ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 100 * 5, cls.window_test_start_date), (10, 110, pd.Timestamp("2015-01-09")), (10, 111, pd.Timestamp("2015-01-12")), (20, 120 * 0.7, cls.window_test_start_date), (20, 121 * 0.7, pd.Timestamp("2015-01-07")), (30, 230 * 11, cls.window_test_start_date), (40, 240, pd.Timestamp("2015-01-15")), (50, 250.0, pd.Timestamp("2015-01-12")), ], end_date, ) for end_date in pd.date_range("2015-01-15", "2015-01-16") ] ), cls.create_expected_df_for_factor_compute( [ (0, 100 * 5 * 6, cls.window_test_start_date), (0, 101, pd.Timestamp("2015-01-20")), (10, 110 * 0.3, pd.Timestamp("2015-01-09")), (10, 111 * 0.3, pd.Timestamp("2015-01-12")), (20, 120 * 0.7 * 0.8, cls.window_test_start_date), (20, 121 * 0.7 * 0.8, pd.Timestamp("2015-01-07")), (30, 230 * 11 * 12, cls.window_test_start_date), (30, 231, pd.Timestamp("2015-01-20")), (40, 240 * 13, pd.Timestamp("2015-01-15")), (50, 250.0, pd.Timestamp("2015-01-12")), ], pd.Timestamp("2015-01-20"), ), cls.create_expected_df_for_factor_compute( [ (0, 200 * 5 * 6, pd.Timestamp("2015-01-12")), (10, 110 * 0.3, pd.Timestamp("2015-01-09")), (10, 111 * 0.3, pd.Timestamp("2015-01-12")), (20, 220 * 0.7 * 0.8, cls.window_test_start_date), (20, 221 * 0.8, pd.Timestamp("2015-01-17")), (40, 240 * 13, pd.Timestamp("2015-01-15")), (50, 250.0, pd.Timestamp("2015-01-12")), ], pd.Timestamp("2015-01-21"), ), cls.create_expected_df_for_factor_compute( [ (0, 200 * 5 * 6, pd.Timestamp("2015-01-12")), (10, 110 * 0.3, pd.Timestamp("2015-01-09")), (10, 111 * 0.3, pd.Timestamp("2015-01-12")), (20, 220 * 0.7 * 0.8, cls.window_test_start_date), (20, 221 * 0.8, pd.Timestamp("2015-01-17")), (40, 240 * 13 * 14, pd.Timestamp("2015-01-15")), (50, 250.0, pd.Timestamp("2015-01-12")), ], pd.Timestamp("2015-01-22"), ), pd.concat( [ cls.create_expected_df_for_factor_compute( [ (0, 200 * 5 * 6, pd.Timestamp("2015-01-12")), (10, 310 * 0.3, pd.Timestamp("2015-01-09")), (10, 311 * 0.3, pd.Timestamp("2015-01-15")), (20, 220 * 0.7 * 0.8, cls.window_test_start_date), (20, 221 * 0.8, pd.Timestamp("2015-01-17")), (40, 240 * 13 * 14,
pd.Timestamp("2015-01-15")
pandas.Timestamp
'''This module implements the word2vec model service that is responsible for training the model as well as a backend interface for the API. ''' from datetime import datetime import json import logging import pandas as pd from gensim.models.ldamulticore import LdaMulticore import numpy as np from wb_nlp.interfaces.milvus import ( get_milvus_client, get_embedding_dsl ) from wb_nlp.interfaces import mongodb, elasticsearch from wb_nlp.types.models import LDAModelConfig, ModelTypes from wb_nlp.models.base import BaseModel class LDAModel(BaseModel): def __init__( self, model_config_id, cleaning_config_id, model_class=LdaMulticore, model_config_type=LDAModelConfig, expected_model_name=ModelTypes.lda.value, model_run_info_description="", model_run_info_id=None, raise_empty_doc_status=True, log_level=logging.INFO, ): super().__init__( model_config_id=model_config_id, cleaning_config_id=cleaning_config_id, model_class=model_class, model_config_type=model_config_type, expected_model_name=expected_model_name, model_run_info_description=model_run_info_description, model_run_info_id=model_run_info_id, raise_empty_doc_status=raise_empty_doc_status, log_level=log_level, ) self.topic_composition_ranges = None try: self.logger.info("Initializing topic composition") self.get_topic_composition_ranges() self.logger.info("Finished initializing topic composition") except ValueError: self.logger.info("Skipping initialization of topic composition") def set_model_specific_attributes(self): self.num_topics = self.dim def transform_doc(self, document, normalize=True, tolist=False): # This function is the primary method of converting a document # into its vector representation based on the model. # This should be implemented in the respective models. # The expected output is a dictionary with keys: # - doc_vec # numpy array of shape (1, self.dim) # - success # Whether the transformation went successfully self.check_model() success = True document = document.lower() try: doc_topics = self.infer_topics(document) doc_vec = np.array([dt["score"] for dt in sorted( doc_topics, key=lambda x: x["topic"])]).reshape(1, -1) if normalize: doc_vec /= np.linalg.norm(doc_vec, ord=2) except Exception as e: success = False if self.raise_empty_doc_status: raise(e) else: doc_vec = np.zeros(self.dim).reshape(1, -1) if tolist: doc_vec = doc_vec.ravel().tolist() return dict(doc_vec=doc_vec, success=success) def infer_topics(self, text, topn_topics=None, total_topic_score=None, serialize=False): if isinstance(text, str): text = text.split() if len(text) == 1: doc_topics = self.model.get_term_topics( self.g_dict.token2id[text[0]]) else: doc = self.g_dict.doc2bow(text) doc_topics = self.model[doc] found_topics = {i for i, v in doc_topics} # print(found_topics) for i in range(self.model.num_topics): if i not in found_topics: doc_topics.append((i, 0)) doc_topics = pd.DataFrame(doc_topics, columns=['topic', 'score']) doc_topics = doc_topics.sort_values('score', ascending=False) if total_topic_score is not None: tdoc_topics = doc_topics[doc_topics.score.cumsum( ) <= total_topic_score] if tdoc_topics.empty: doc_topics = doc_topics.head(1) else: doc_topics = tdoc_topics if topn_topics is not None and doc_topics.shape[0] > topn_topics: doc_topics = doc_topics.head(topn_topics) # doc_topics['topic'] = doc_topics['topic'].astype(int) doc_topics = doc_topics.to_dict('records') if serialize: doc_topics = json.dumps(doc_topics) return doc_topics def get_model_topic_words(self, topn_words=5, total_word_score=None, serialize=False): payload = [] for topic_id in range(self.model.num_topics): topic_words = self.get_topic_words( topic_id, topn_words=topn_words, total_word_score=total_word_score ) payload.append({'topic_id': topic_id, 'topic_words': topic_words}) if serialize: payload = json.dumps(payload) return payload def get_topic_words(self, topic_id, topn_words=10, total_word_score=None, serialize=False): topic_id = int(topic_id) topic_words = pd.DataFrame(self.model.show_topic( topic_id, topn=topn_words), columns=['word', 'score']) topic_words = topic_words.sort_values('score', ascending=False) if total_word_score is not None: ttopic_words = topic_words[topic_words.score.cumsum( ) <= total_word_score] if ttopic_words.empty: topic_words = topic_words.head(1) else: topic_words = ttopic_words if topn_words is not None and topic_words.shape[0] > topn_words: topic_words = topic_words.head(topn_words) topic_words = topic_words.to_dict('records') if serialize: topic_words = json.dumps(topic_words) return topic_words def get_doc_topic_words(self, text, topn_topics=10, topn_words=10, total_topic_score=1, total_word_score=1, serialize=False): doc_topics = self.infer_topics( text, topn_topics=topn_topics, total_topic_score=total_topic_score) doc_topic_words = [] for dt in doc_topics: topic = dt['topic'] topic_score = dt['score'] topic_words = self.get_topic_words( topic, topn_words=topn_words, total_word_score=total_word_score) topic_data = {'topic': topic, 'score': topic_score} topic_data['words'] = topic_words doc_topic_words.append(topic_data) doc_topic_words = pd.DataFrame(doc_topic_words).to_dict('records') if serialize: doc_topic_words = json.dumps(doc_topic_words) return doc_topic_words # def get_doc_topic_words_by_id(self, doc_id, topn_topics=10, topn_words=10, total_topic_score=1, total_word_score=1, serialize=False): # doc_topics = self.get_doc_topic_by_id( # doc_id, topn=topn_topics, serialize=False) # doc_topic_words = [] # for dt in doc_topics: # topic = dt['topic'] # topic_score = dt['score'] # topic_words = self.get_topic_words( # topic, topn_words=topn_words, total_word_score=total_word_score) # topic_data = {'topic': topic, 'score': topic_score} # topic_data['words'] = topic_words # doc_topic_words.append(topic_data) # doc_topic_words = pd.DataFrame(doc_topic_words).to_dict('records') # if serialize: # doc_topic_words = json.dumps(doc_topic_words) # return doc_topic_words def get_combined_doc_topic_words(self, text, topn_topics=None, topn_words=None, total_topic_score=0.8, total_word_score=0.2, serialize=False): doc_topics = self.infer_topics( text, topn_topics=topn_topics, total_topic_score=total_topic_score) doc_topic_words = [] for dt in doc_topics: topic = dt['topic'] topic_score = dt['score'] topic_words = self.get_topic_words( topic, topn_words=topn_words, total_word_score=total_word_score) for tw in topic_words: word = tw['word'] word_score = tw['score'] doc_topic_words.append({ 'topic': topic, 'word': word, 'topic_score': topic_score, 'word_score': word_score, 'score': topic_score * word_score }) doc_topic_words = pd.DataFrame(doc_topic_words).sort_values( 'score', ascending=False).to_dict('records') if serialize: doc_topic_words = json.dumps(doc_topic_words) return doc_topic_words # def get_doc_topic_by_id(self, doc_id, topn=None, serialize=False): # doc = self.documents_topics.loc[doc_id] # if doc.empty: # return [] # # Just call is score for consistency # doc.name = 'score' # doc.index.name = 'topic' # doc = doc.sort_values(ascending=False) / doc.sum() # doc.index = doc.index.astype(int) # doc = doc.reset_index() # if topn is not None: # doc = doc.head(topn) # doc = doc.to_dict('records') # if serialize: # doc = json.dumps(doc) # return doc # def get_similar_documents(self, document, topn=10, return_data='id', return_similarity=False, duplicate_threshold=0.01, show_duplicates=True, serialize=False): # doc_topics = self.infer_topics(document) # doc_topics = pd.DataFrame(doc_topics).sort_values( # 'topic').set_index('topic') # e_distance = euclidean_distances(doc_topics.score.values.reshape( # 1, -1), self.normalized_documents_topics.values).flatten() # if not show_duplicates: # e_distance[e_distance <= duplicate_threshold] = np.inf # payload = [] # for rank, top_sim_ix in enumerate(e_distance.argsort()[:topn], 1): # payload.append( # {'id': self.normalized_documents_topics.iloc[top_sim_ix].name, 'score': e_distance[top_sim_ix], 'rank': rank}) # if serialize: # payload = pd.DataFrame(payload).to_json() # return payload # def get_similar_docs_by_id(self, doc_id, topn=10, return_data='id', return_similarity=False, duplicate_threshold=0.01, show_duplicates=True, serialize=False): # doc_topics = self.normalized_documents_topics.loc[doc_id].values.reshape( # 1, -1) # e_distance = euclidean_distances( # doc_topics, self.normalized_documents_topics.values).flatten() # if not show_duplicates: # e_distance[e_distance <= duplicate_threshold] = pd.np.inf # payload = [] # for rank, top_sim_ix in enumerate(e_distance.argsort()[:topn], 1): # payload.append( # {'id': self.normalized_documents_topics.iloc[top_sim_ix].name, 'score': e_distance[top_sim_ix], 'rank': rank}) # if serialize: # payload = pd.DataFrame(payload).to_json() # return payload def _mdb_get_docs_by_topic_composition(self, topic_percentage, return_all_topics=False): self.check_wvecs() model_run_info_id = self.model_run_info["model_run_info_id"] doc_topic_collection = mongodb.get_document_topics_collection() topic_cols = [f"topic_{id}" for id in sorted(topic_percentage)] topic_filters = {f"topics.topic_{id}": {"$gte": val} for id, val in sorted(topic_percentage.items())} topic_filters = { "model_run_info_id": model_run_info_id, **topic_filters} cands = doc_topic_collection.find(topic_filters) doc_df = pd.DataFrame(cands) if doc_df.empty: return doc_df doc_df = doc_df.set_index( "id")["topics"].apply(pd.Series) if not return_all_topics: doc_df = doc_df[topic_cols] doc_df = doc_df.round(5) return doc_df def _get_docs_by_topic_composition_search(self, topic_percentage): model_run_info_id = self.model_run_info["model_run_info_id"] search = elasticsearch.DocTopic.search() topic_filters = [dict(range={f"topics.topic_{id}": {"gte": val}}) for id, val in sorted(topic_percentage.items())] search = search.query( dict( bool=dict( must=[ {"term": {"model_run_info_id": model_run_info_id}}] + topic_filters ) ) ) return search def _get_docs_by_topic_composition(self, topic_percentage, return_all_topics=False): self.check_wvecs() search = self._get_docs_by_topic_composition_search(topic_percentage) topic_cols = [f"topic_{id}" for id in sorted(topic_percentage)] search = search[0: search.count()] response = search.execute() doc_df = pd.DataFrame([h.to_dict() for h in response.hits]) if doc_df.empty: return doc_df doc_df = doc_df.set_index( "id")["topics"].apply(pd.Series) if not return_all_topics: doc_df = doc_df[topic_cols] doc_df = doc_df.round(5) return doc_df def get_docs_by_topic_composition_count(self, topic_percentage): search = self._get_docs_by_topic_composition_search(topic_percentage) return search.count() # return len(self._get_docs_by_topic_composition(topic_percentage)) def get_docs_by_topic_composition(self, topic_percentage, serialize=False, from_result=0, size=10, return_all_topics=False): ''' topic_percentage (dict): key (int) corresponds to topic id and value (float [0, 1]) corresponds to the expected topic percentage. ''' # topic_percentage = {6: 0.1, 42: 0.1} doc_df = self._get_docs_by_topic_composition( topic_percentage, return_all_topics=return_all_topics) doc_count = len(doc_df) payload = [] if doc_count > 0: doc_rank = (-1 * doc_df ).rank().mean(axis=1).rank().sort_values() doc_rank.name = "rank" doc_rank = doc_rank.reset_index().to_dict("records") doc_topic = doc_df.T.to_dict() for rank, ent in enumerate(doc_rank): if from_result > rank: continue payload.append( {'id': ent["id"], 'topic': doc_topic[ent["id"]], 'rank': rank + 1}) if len(payload) == size: break payload = sorted(payload, key=lambda x: x['rank']) if serialize: payload = pd.DataFrame(payload).to_json() return dict(total=doc_count, hits=payload) def mdb_get_topic_composition_ranges(self, serialize=False): self.check_wvecs() if self.topic_composition_ranges is None: model_run_info_id = self.model_run_info["model_run_info_id"] doc_topic_collection = mongodb.get_document_topics_collection() self.topic_composition_ranges = pd.DataFrame([ list(doc_topic_collection.aggregate([ {"$match": {"model_run_info_id": model_run_info_id}}, {"$group": { "_id": f"topic_{i}", "min": {"$min": f"$topics.topic_{i}"}, "max": {"$max": f"$topics.topic_{i}"}}}]))[0] for i in range(self.dim) ]).rename(columns={"_id": "topic"}).set_index("topic").T.to_dict() # "records") # Data structure: {topic_id: {min: <min_val>, max: <max_val>}} payload = self.topic_composition_ranges if serialize: payload = pd.DataFrame(payload).to_json() return payload def get_topic_composition_ranges(self, serialize=False): self.check_wvecs() if self.topic_composition_ranges is None: model_run_info_id = self.model_run_info["model_run_info_id"] topic_stats = [] for i in range(self.dim): search = elasticsearch.DocTopic.search() query_body = dict( aggs={f"topic_{i}": dict( stats=dict(field=f"topics.topic_{i}"))}, query=dict( term=dict(model_run_info_id=model_run_info_id)), size=0 ) search.update_from_dict(query_body) result = search.execute() topic_stats.append(result.aggregations.to_dict()) self.topic_composition_ranges = { k: v for i in topic_stats for k, v in i.items() } # Data structure: {topic_id: {min: <min_val>, max: <max_val>}} payload = self.topic_composition_ranges if serialize: payload =
pd.DataFrame(payload)
pandas.DataFrame
# Imports and cleans viral sequencing data, to throw into Angular app. # Does a bunch of things: # 1) standardizes all inputs to conform with schema # 2) creates a series of Experiment objects to store the experimental data with experiment IDs # 3) creates a series of Patient objects for patients who are not in the KGH roster. # 4) creates a series of Samples for all the experiments. import pandas as pd import os import re from datetime import datetime import helpers from .generate_viral_seq_dataset import get_viralseq_dataset from .generate_viral_seq_datadownload import get_viralseq_downloads from Bio import SeqIO # from Bio import Phylo def clean_viral_seq(output_dir, lassaS_AAfile, lassaS_Alignedfile, lassaS_Rawfile, lassa_MDfile, id_dict, exptCols_common, patientCols, sampleCols, downloadCols, dateModified, version, updatedBy, saveFiles, verbose): # [File locations] ---------------------------------------------------------------------------------------------------- # Outputs log_dir = f"{output_dir}/log" today = datetime.today().strftime('%Y-%m-%d') # Custom, extra properties specific to viral sequencing exptCols = exptCols_common.copy() exptCols.extend(['genbankID', 'inAlignment', 'cvisb_data']) # [IDs from KGH] ---------------------------------------------------------------------------------------------------- ids = pd.read_json(id_dict) ids.reset_index(inplace=True) ids.rename(columns={'index': 'ID'}, inplace=True) # Import and clean data ---------------------------------------------------------------------------------------------------- # [Lassa] ---------------------------------------------------------------------------------------------------- # Lassa data stored in 4 files: # metadata file: contains any patient information known about them. includes both S and L alignments. lasv =
pd.read_csv(lassa_MDfile)
pandas.read_csv
""" Author: <NAME> <<EMAIL>> Date: 2019-06-22 Function: Encapsulates RESTful API logic. """ import random import requests from requests.exceptions import HTTPError from urllib.parse import urlencode import numpy as np import pandas as pd from io import StringIO from .common import ( halt, print_tqdm, get_base_url, get_token, remove_angle_brackets, save_config, inline, MAX_ROWS ) class APIError(Exception): ''' Represents API related error. error.status_code will have http status code. ''' def __init__(self, error, http_error=None): super().__init__(error['message']) self._error = error self._http_error = http_error @property def code(self): return self._error['code'] @property def status_code(self): http_error = self._http_error if http_error is not None and hasattr(http_error, 'response'): return http_error.response.status_code @property def request(self): if self._http_error is not None: return self._http_error.request @property def response(self): if self._http_error is not None: return self._http_error.response class _REST(object): """ Handles RESTful requests to the Simons CMAP API. """ def __init__(self, token=None, baseURL=None, headers=None, vizEngine=None, exportDir=None, exportFormat=None, figureDir=None, ): """ :param str token: access token to make client requests. :param str baseURL: root endpoint of Simons CMAP API. :param dict headers: additional headers to add to requests. :param str vizEngine: data visualization library used to render the graphs. :param str exportDir: path to local directory where the exported data are stored. :param str exportFormat: file format of the exported files. """ self._token = remove_angle_brackets(token) or get_token() self._baseURL = baseURL or get_base_url() self._headers = headers self._token_prefix = 'Api-Key ' self._vizEngine = vizEngine self._exportDir = exportDir self._exportFormat = exportFormat self._figureDir = figureDir save_config( token=self._token, vizEngine=self._vizEngine, exportDir=self._exportDir, exportFormat=self._exportFormat, figureDir=self._figureDir ) assert len(self._token) > 0, 'API key cannot be empty.' assert self._headers is None or isinstance(self._headers, dict), \ 'Expected dict, got %r' % self._headers def _request( self, route, method='GET', payload=None, baseURL=None ): baseURL = baseURL or self._baseURL headers = {'Authorization': self._token_prefix + self._token} if method.upper().strip() == 'GET': return self._atomic_get(route, headers, payload) else: return None def _atomic_get(self, route, headers, payload): """ Submits a single GET request. Returns the body in form of pandas dataframe if 200 status. """ df = pd.DataFrame({}) try: queryString = '' if payload is not None: queryString = urlencode(payload) url = self._baseURL + route + queryString resp = requests.get(url, headers=headers) resp_text = resp.text # not a big fan, a bit slow? if len(resp_text) < 50: if resp_text.lower().strip() == 'unauthorized': halt('Unauthorized API key!') try: if len(resp_text.strip())>0: df = pd.read_csv(StringIO(resp_text)) if 'time' in df.columns: df['time'] = pd.to_datetime(df['time']) df['time'] = df['time'].dt.strftime('%Y-%m-%dT%H:%M:%S') # json_list = [orjson.loads(line) for line in resp_text.splitlines()] # df = pd.DataFrame(json_list, columns=list(json_list[0])) except Exception as e: print_tqdm('REST API Error (status code {})'.format(resp.status_code), err=True) print_tqdm(resp_text, err=True) print('********* Python Error Msg **********') print(e) except HTTPError as http_error: # look for resp.status_code raise return df @staticmethod def validate_sp_args( table, variable, dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2 ): """ :param str table: table name (each data set is stored in one or more than one table). :param str variable: variable short name which directly corresponds to a field name in the table. :param str dt1: start date or datetime. :param str dt2: end date or datetime. :param float lat1: start latitude [degree N]. :param float lat2: end latitude [degree N]. :param float lon1: start longitude [degree E]. :param float lon2: end longitude [degree E]. :param float depth1: start depth [m]. :param float depth2: end depth [m]. """ def is_number(val): return isinstance(val, float) or isinstance(val, int) or isinstance(val, np.int64) msg = '' if not isinstance(table, str): msg += 'table name should be string. \n' if not isinstance(variable, str): msg += 'variable name should be string. \n' if not isinstance(dt1, str): msg += 'dt1 (start date) should be string. \n' if not isinstance(dt2, str): msg += 'dt2 (end date) should be string. \n' if not is_number(lat1): msg += 'lat1 (start latitude) should be float or integer. \n' if not is_number(lat2): msg += 'lat2 (end latitude) should be float or integer. \n' if not is_number(lon1): msg += 'lon1 (start longitude) should be float or integer. \n' if not is_number(lon2): msg += 'lon2 (end longitude) should be float or integer. \n' if not is_number(depth1): msg += 'depth1 (start depth) should be float or integer. \n' if not is_number(depth2): msg += 'depth2 (end depth) should be float or integer. \n' if len(msg) > 0: halt(msg) return msg def query(self, query, servers=['rainier']): """Takes a custom query and returns the results in form of a dataframe.""" # route = '/dataretrieval/query?' # JSON format, deprecated route = '/api/data/query?' # CSV format payload = {'query': query, 'servername': random.choice(servers)} return self._request(route, method='GET', payload=payload) def stored_proc(self, query, args): """Executes a strored-procedure and returns the results in form of a dataframe.""" # route = '/dataretrieval/sp?' # JSON format, deprecated route = '/api/data/sp?' # CSV format payload = { 'tableName': args[0], 'fields': args[1], 'dt1': args[2], 'dt2': args[3], 'lat1': args[4], 'lat2': args[5], 'lon1': args[6], 'lon2': args[7], 'depth1': args[8], 'depth2': args[9], 'spName': query.split(' ')[1] } self.validate_sp_args(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]) df = self._request(route, method='GET', payload=payload) return df def get_catalog(self): """Returns a dataframe containing full Simons CMAP catalog of variables.""" # return self.query('EXEC uspCatalog') return self.query("""SELECT Variable, [Table_Name], [Unit], [Make], [Sensor], [Process_Level], [Study_Domain], [Temporal_Resolution], [Spatial_Resolution], [Time_Min], [Time_Max], [Lat_Min], [Lat_Max], [Lon_Min], [Lon_Max], [Depth_Min], [Depth_Max], [Variable_25th], [Variable_25th], [Variable_50th], [Variable_75th], [Variable_Count], [Variable_Mean], [Variable_Std], [Variable_Min], [Variable_Max], [Dataset_Name], [Dataset_Short_Name], [Data_Source], [Distributor], [Dataset_Description], [Acknowledgement], [Dataset_ID], [ID], [Visualize], [Keywords] FROM dbo.udfCatalog()""") def search_catalog(self, keywords): """ Returns a dataframe containing a subset of Simons CMAP catalog of variables. All variables at Simons CMAP catalog are annotated with a collection of semantically related keywords. This method takes the passed keywords and returns all of the variables annotated with similar keywords. The passed keywords should be separated by blank space. The search result is not sensitive to the order of keywords and is not case sensitive. The passed keywords can provide any 'hint' associated with the target variables. Below are a few examples: * the exact variable name (e.g. NO3), or its linguistic term (Nitrate) * methodology (model, satellite ...), instrument (CTD, seaflow), or disciplines (physics, biology ...)  * the cruise official name (e.g. KOK1606), or unofficial cruise name (Falkor) * the name of data producer (e.g <NAME>) or institution name (MIT) If you searched for a variable with semantically-related-keywords and did not get the correct results, please let us know. We can update the keywords at any point. """ return self.query("EXEC uspSearchCatalog '%s'" % keywords) def datasets(self): """Returns a dataframe containing the list of data sets hosted by Simons CMAP database.""" return self.query("EXEC uspDatasets") def datasets_with_ancillary(self): """ Returns a dataframe containing the list of data sets that have been automatically colocalized with ancillary variables (mostly environmental). A growing number of Simons CMAP datasets are automatically colocalized with a large (100+) number of ancillary parameters derived from satellite and numerical model products. """ return self.query("EXEC uspDatasetsWithAncillary") def head(self, tableName, rows=5): """Returns top records of a data set.""" return self.query("EXEC uspHead '%s', '%d'" % (tableName, rows)) def columns(self, tableName): """Returns the list of data set columns.""" return self.query("EXEC uspColumns '%s'" % tableName) def get_dataset_ID(self, tableName): """ Returns dataset ID. """ df = self.query("SELECT DISTINCT(Dataset_ID) FROM dbo.udfCatalog() WHERE LOWER(Table_Name)=LOWER('%s') " % tableName) if len(df) < 1: halt('Invalid table name: %s' % tableName) if len(df) > 1: halt('More than one table found. Please provide a more specific name: ') print(df) return df.iloc[0]['Dataset_ID'] def get_dataset(self, tableName): """ Returns the entire dataset. It is not recommended to retrieve datasets with more than 1 million rows using this method. For large datasets, please use the 'space_time' method and retrieve the data in smaller chunks. Note that this method does not return the dataset metadata. Use the 'get_dataset_metadata' method to get the dataset metadata. """ datasetID = self.get_dataset_ID(tableName) maxRow = 2000000 df = self.query("SELECT JSON_stats FROM tblDataset_Stats WHERE Dataset_ID=%d " % datasetID) df = pd.read_json(df['JSON_stats'][0]) rows = int(df.loc[['count'], 'lat']) if rows > maxRow: msg = "The requested dataset has %d records.\n" % rows msg += "It is not recommended to retrieve datasets with more than %d rows using this method.\n" % maxRow msg += "For large datasets, please use the 'space_time' method and retrieve the data in smaller chunks." halt(msg) return self.query("SELECT * FROM %s" % tableName) def get_dataset_with_ancillary(self, tableName, CIP=False): """ Returns the entire dataset joined with colocalized ancillary variables. The ancillary variable names are prefixed with `CMAP_`. It is not recommended to retrieve datasets with more than 1 million rows using this method. Note that this method does not return the dataset metadata. Use the 'get_dataset_metadata' method to get the dataset metadata. """ datasetID = self.get_dataset_ID(tableName) df = self.query("SELECT JSON_stats FROM tblDataset_Stats WHERE Dataset_ID=%d " % datasetID) df = pd.read_json(df['JSON_stats'][0]) rows = int(df.loc[['count'], 'lat']) if rows > MAX_ROWS: msg = "The requested dataset has %d records.\n" % rows msg += "It is not recommended to retrieve datasets with more than %d rows using this method.\n" % MAX_ROWS msg += "For large datasets, please use the 'space_time' method and retrieve the data in smaller chunks." halt(msg) anciDatasets = self.datasets_with_ancillary() if not tableName in list(anciDatasets["Table_Name"].values): halt(f"""The selected data set (table: {tableName}) has not been colocalized with ancillary variables. Please let us know if you think we should do so.""") anciTableName = "tblAncillary" if CIP: anciTableName = "tblAncillary_CIP" anciCols = list(self.query(f"EXEC uspColumns '{anciTableName}'")["Columns"].values) anciCols = [e for e in anciCols if e not in ('time', 'lat', 'lon', 'depth', 'link')] anciCols = ', '.join(anciCols) return self.query(f""" SELECT t1.*, {anciCols} FROM {tableName} t1 LEFT JOIN {anciTableName} t2 ON t1.[time]=t2.[time] AND ABS(t1.lat-t2.lat)<0.0001 AND ABS(t1.lon-t2.lon)<0.0001 AND ABS(t1.depth-t2.depth)<0.001 WHERE t2.link='{tableName}' """) def get_dataset_metadata(self, tableName): """Returns a dataframe containing the dataset metadata.""" return self.query("EXEC uspDatasetMetadata '%s'" % tableName) def get_var(self, tableName, varName): """ Returns a single-row dataframe from tblVariables containing info associated with varName. This method is mean to be used internally and will not be exposed at documentations. """ query = "SELECT * FROM tblVariables WHERE Table_Name='%s' AND Short_Name='%s'" % (tableName, varName) return self.query(query) def get_var_catalog(self, tableName, varName): """Returns a single-row dataframe from catalog (udfCatalog) containing all of the variable's info at catalog.""" query = "SELECT * FROM [dbo].udfCatalog() WHERE Table_Name='%s' AND Variable='%s'" % (tableName, varName) return self.query(query) def get_var_long_name(self, tableName, varName): """Returns the long name of a given variable.""" return self.query("EXEC uspVariableLongName '%s', '%s'" % (tableName, varName)).iloc[0]['Long_Name'] def get_unit(self, tableName, varName): """Returns the unit for a given variable.""" return ' [' + self.query("EXEC uspVariableUnit '%s', '%s'" % (tableName, varName)).iloc[0]['Unit'] + ']' def get_var_resolution(self, tableName, varName): """Returns a single-row dataframe from catalog (udfCatalog) containing the variable's spatial and temporal resolutions.""" return self.query("EXEC uspVariableResolution '%s', '%s'" % (tableName, varName)) def get_var_coverage(self, tableName, varName): """Returns a single-row dataframe from catalog (udfCatalog) containing the variable's spatial and temporal coverage.""" return self.query("EXEC uspVariableCoverage '%s', '%s'" % (tableName, varName)) def get_var_stat(self, tableName, varName): """Returns a single-row dataframe from catalog (udfCatalog) containing the variable's summary statistics.""" return self.query("EXEC uspVariableStat '%s', '%s'" % (tableName, varName)) def has_field(self, tableName, varName): """Returns a boolean confirming whether a field (varName) exists in a table (data set).""" query = "SELECT COL_LENGTH('%s', '%s') AS RESULT " % (tableName, varName) df = self.query(query)['RESULT'] hasField = False if len(df)>0: hasField = True return hasField def is_grid(self, tableName, varName): """Returns a boolean indicating whether the variable is a gridded product or has irregular spatial resolution.""" grid = True query = "SELECT Spatial_Res_ID, RTRIM(LTRIM(Spatial_Resolution)) AS Spatial_Resolution FROM tblVariables " query = query + "JOIN tblSpatial_Resolutions ON [tblVariables].Spatial_Res_ID=[tblSpatial_Resolutions].ID " query = query + "WHERE Table_Name='%s' AND Short_Name='%s' " % (tableName, varName) df = self.query(query) if len(df) < 1: return None if df.Spatial_Resolution[0].lower().find('irregular') != -1: grid = False return grid def is_climatology(self, tableName): """ Returns True if the table represents a climatological data set. """ return True if self.query(f"SELECT * FROM tblDatasets d JOIN tblVariables v ON d.ID=v.Dataset_ID WHERE v.Table_Name='{tableName}'").iloc[0]['Climatology'] == 1 else False def get_references(self, datasetID): """Returns a dataframe containing refrences associated with a data set.""" query = "SELECT Reference FROM dbo.udfDatasetReferences(%d)" % datasetID return self.query(query) def get_metadata_noref(self, table, variable): """ Returns a dataframe containing the associated metadata for a single variable. The returned metadata does not include the list of references and articles associated with the variable. """ query = "SELECT * FROM dbo.udfCatalog() WHERE Variable='%s' AND Table_Name='%s'" % (variable, table) return self.query(query) def get_metadata(self, table, variable): """ Returns a dataframe containing the associated metadata. The inputs can be string literals (if only one table, and variable is passed) or a list of string literals. """ if isinstance(table, str): table = [table] if isinstance(variable, str): variable = [variable] metadata = pd.DataFrame({}) for i in range(len(table)): df = self.query("EXEC uspVariableMetaData '%s', '%s'" % (table[i], variable[i])) metadata = pd.concat([metadata, df], axis=0, sort=False) return metadata def cruises(self): """ Returns a dataframe containing a list of all of the hosted cruise names. """ return self.query('EXEC uspCruises') def cruise_by_name(self, cruiseName): """ Returns a dataframe containing cruise info using cruise name. """ df = self.query("EXEC uspCruiseByName '%s' " % cruiseName) if len(df) < 1: halt('Invalid cruise name: %s' % cruiseName) if len(df) > 1: if 'Keywords' in df.columns: df.drop('Keywords', axis=1, inplace=True) print(df) halt('More than one cruise found. Please provide a more specific cruise name: ') return df def cruise_bounds(self, cruiseName): """ Returns a dataframe containing cruise boundaries in space and time. """ df = self.cruise_by_name(cruiseName) return self.query('EXEC uspCruiseBounds %d ' % df.iloc[0]['ID']) def cruise_trajectory(self, cruiseName): """ Returns a dataframe containing the cruise trajectory. """ df = self.cruise_by_name(cruiseName) return self.query('EXEC uspCruiseTrajectory %d ' % df.iloc[0]['ID']) def cruise_variables(self, cruiseName): """ Returns a dataframe containing all registered variables (at Simons CMAP) during a cruise. """ df = self.cruise_by_name(cruiseName) return self.query('SELECT * FROM dbo.udfCruiseVariables(%d) ' % df.iloc[0]['ID']) def subset(self, spName, table, variable, dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2): """Returns a subset of data according to space-time constraints.""" query = 'EXEC {} ?, ?, ?, ?, ?, ?, ?, ?, ?, ?'.format(spName) args = [table, variable, dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2] return self.stored_proc(query, args) def space_time(self, table, variable, dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2): """ Returns a subset of data according to space-time constraints. The results are ordered by time, lat, lon, and depth (if exists). """ return self.subset('uspSpaceTime', table, variable, dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2) @staticmethod def _interval_to_uspName(interval): if interval is None or interval == '': return 'uspTimeSeries' interval = interval.lower().strip() if interval in ['w', 'week', 'weekly']: usp = 'uspWeekly' elif interval in ['m', 'month', 'monthly']: usp = 'uspMonthly' elif interval in ['q', 's', 'season', 'seasonal', 'seasonality', 'quarterly']: usp = 'uspQuarterly' elif interval in ['y', 'a', 'year', 'yearly', 'annual']: usp = 'uspAnnual' else: halt('Invalid interval: %s' % interval) return usp def time_series(self, table, variable, dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2, interval=None): """ Returns a subset of data according to space-time constraints. The results are aggregated by time and ordered by time, lat, lon, and depth (if exists). The timeseries data can be binned weekyly, monthly, qurterly, or annualy, if interval variable is set (this feature is not applicable to climatological data sets). """ usp = self._interval_to_uspName(interval) if usp != 'uspTimeSeries' and self.is_climatology(table): print_tqdm( 'Custom binning (monthly, weekly, ...) is not suppoerted for climatological data sets. Table %s represents a climatological data set.' % table, err=True) return
pd.DataFrame({})
pandas.DataFrame
import numpy as np import pandas as pd from glob import glob import os fnames= glob('noaa storm/*.csv') details_fn= sorted([fn for fn in fnames if 'details' in fn]) timezone_mapper= { 'CST' : 'US/Central', 'CST-6' : 'US/Central', 'EST' : 'US/Eastern', 'EST-5' : 'US/Eastern', 'PST' : 'US/Pacific', 'PST-8' : 'US/Pacific', 'MST' : 'US/Mountain', 'MST-7' : 'US/Mountain', 'AST' : 'Etc/GMT-4', 'AST-4' : 'Etc/GMT-4', 'HST' : 'US/Hawaii', 'HST-10': 'US/Hawaii', 'GST10' : 'Etc/GMT-4', 'SST' : 'US/Samoa', 'SST-11': 'US/Samoa', 'AKST-9': 'US/Alaska' } def retrieve_floods(fn): '''''' df= pd.read_csv(fn) df= df[df['EVENT_TYPE'].str.contains(pat='Lakeshore Flood|Flood|Flash Flood|Coastal Flood')] return df # convert begin time and end time to UTC def convert_datetime_begin(x): if x.CZ_TIMEZONE in timezone_mapper.keys(): timezone= timezone_mapper[x.CZ_TIMEZONE] else: timezone= x.CZ_TIMEZONE datetime= '%06d'%(x.BEGIN_YEARMONTH)+'%02d'%(x.BEGIN_DAY)+'%04d'%(x.BEGIN_TIME) datetime= pd.to_datetime(datetime, format='%Y%m%d%H%M').tz_localize('%s'%timezone, ambiguous='NaT', nonexistent='NaT').tz_convert('UTC').tz_localize(None) # except: # # print(str(x.BEGIN_YEARMONTH)+str(x.BEGIN_DAY)+'%04d'%(x.BEGIN_TIME)) # datetime= pd.to_datetime(datetime, format='%Y%m%d%H%M') return datetime def convert_datetime_end(x): if x.CZ_TIMEZONE in timezone_mapper.keys(): timezone= timezone_mapper[x.CZ_TIMEZONE] else: timezone= x.CZ_TIMEZONE datetime= '%06d'%(x.END_YEARMONTH)+'%02d'%(x.END_DAY)+'%04d'%(x.END_TIME) datetime= pd.to_datetime(datetime, format='%Y%m%d%H%M').tz_localize('%s'%timezone, ambiguous='NaT', nonexistent='NaT').tz_convert('UTC').tz_localize(None) return datetime floods= pd.DataFrame(columns= df.columns) for i in range(len(details_fn)): _df= retrieve_floods(details_fn[i]) floods= pd.concat([floods, _df]) begin_time= floods.apply(convert_datetime_begin,axis=1) end_time= floods.apply(convert_datetime_end,axis=1) floods['datetime_begin']= begin_time floods['datetime_end']= end_time def update_fatality(df, df_fatality): df['fatality']= 0 for ID in df_fatality.EVENT_ID: if ID in list(df.EVENT_ID): df.loc[df.EVENT_ID==ID, 'fatality']+=1 return df fatalities_fn= sorted([fn for fn in fnames if 'fatalities' in fn]) df= pd.read_csv(fatalities_fn[0]) fatalities= pd.DataFrame(columns= df.columns) for i in range(len(fatalities_fn)): _df= pd.read_csv(fatalities_fn[i]) fatalities= pd.concat([fatalities, _df]) floods= update_fatality(floods, fatalities) def justify(x): if isinstance(x, str): if x[-1]=='K': if x[0]=='K': y=1 else: y= float(x[:-1])*1000 elif x[-1]=='M': if x[0]=='M': y= 1000000 else: y= float(x[:-1])*1000000 elif x[-1]=='B': if x[0]=='B': y=1e9 else: y= float(x[:-1])*10**9 elif x[-1]=='0': y= 0 else: y= 0 return y floods['damages']= floods.DAMAGE_PROPERTY.apply(justify) + floods.DAMAGE_CROPS.apply(justify) # geocode NWS report to fill nan geophysical coordinates with natural language processing import spacy from spacy import displacy from collections import Counter import en_core_web_sm nlp = en_core_web_sm.load() from geopy import Nominatim locator = Nominatim(user_agent= "myGeocoder") def insert_location(x): try: if (pd.isna(x.LON) or pd.isna(x.LAT)) and not
pd.isna(x.DESCRIPTION)
pandas.isna
# pylint: disable-msg=W0612,E1101,W0141 import nose from numpy.random import randn import numpy as np from pandas.core.index import Index, MultiIndex from pandas import Panel, DataFrame, Series, notnull, isnull from pandas.util.testing import (assert_almost_equal, assert_series_equal, assert_frame_equal, assertRaisesRegexp) import pandas.core.common as com import pandas.util.testing as tm from pandas.compat import (range, lrange, StringIO, lzip, u, cPickle, product as cart_product, zip) import pandas as pd import pandas.index as _index class TestMultiLevel(tm.TestCase): _multiprocess_can_split_ = True def setUp(self): import warnings warnings.filterwarnings(action='ignore', category=FutureWarning) index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two', 'three']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) self.frame = DataFrame(np.random.randn(10, 3), index=index, columns=Index(['A', 'B', 'C'], name='exp')) self.single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']], labels=[[0, 1, 2, 3]], names=['first']) # create test series object arrays = [['bar', 'bar', 'baz', 'baz', 'qux', 'qux', 'foo', 'foo'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = lzip(*arrays) index = MultiIndex.from_tuples(tuples) s = Series(randn(8), index=index) s[3] = np.NaN self.series = s tm.N = 100 self.tdf = tm.makeTimeDataFrame() self.ymd = self.tdf.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]).sum() # use Int64Index, to make sure things work self.ymd.index.set_levels([lev.astype('i8') for lev in self.ymd.index.levels], inplace=True) self.ymd.index.set_names(['year', 'month', 'day'], inplace=True) def test_append(self): a, b = self.frame[:5], self.frame[5:] result = a.append(b) tm.assert_frame_equal(result, self.frame) result = a['A'].append(b['A']) tm.assert_series_equal(result, self.frame['A']) def test_dataframe_constructor(self): multi = DataFrame(np.random.randn(4, 4), index=[np.array(['a', 'a', 'b', 'b']), np.array(['x', 'y', 'x', 'y'])]) tm.assert_isinstance(multi.index, MultiIndex) self.assertNotIsInstance(multi.columns, MultiIndex) multi = DataFrame(np.random.randn(4, 4), columns=[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']]) tm.assert_isinstance(multi.columns, MultiIndex) def test_series_constructor(self): multi = Series(1., index=[np.array(['a', 'a', 'b', 'b']), np.array(['x', 'y', 'x', 'y'])]) tm.assert_isinstance(multi.index, MultiIndex) multi = Series(1., index=[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']]) tm.assert_isinstance(multi.index, MultiIndex) multi = Series(lrange(4), index=[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']]) tm.assert_isinstance(multi.index, MultiIndex) def test_reindex_level(self): # axis=0 month_sums = self.ymd.sum(level='month') result = month_sums.reindex(self.ymd.index, level=1) expected = self.ymd.groupby(level='month').transform(np.sum) assert_frame_equal(result, expected) # Series result = month_sums['A'].reindex(self.ymd.index, level=1) expected = self.ymd['A'].groupby(level='month').transform(np.sum) assert_series_equal(result, expected) # axis=1 month_sums = self.ymd.T.sum(axis=1, level='month') result = month_sums.reindex(columns=self.ymd.index, level=1) expected = self.ymd.groupby(level='month').transform(np.sum).T assert_frame_equal(result, expected) def test_binops_level(self): def _check_op(opname): op = getattr(DataFrame, opname) month_sums = self.ymd.sum(level='month') result = op(self.ymd, month_sums, level='month') broadcasted = self.ymd.groupby(level='month').transform(np.sum) expected = op(self.ymd, broadcasted) assert_frame_equal(result, expected) # Series op = getattr(Series, opname) result = op(self.ymd['A'], month_sums['A'], level='month') broadcasted = self.ymd['A'].groupby( level='month').transform(np.sum) expected = op(self.ymd['A'], broadcasted) assert_series_equal(result, expected) _check_op('sub') _check_op('add') _check_op('mul') _check_op('div') def test_pickle(self): def _test_roundtrip(frame): pickled = cPickle.dumps(frame) unpickled = cPickle.loads(pickled) assert_frame_equal(frame, unpickled) _test_roundtrip(self.frame) _test_roundtrip(self.frame.T) _test_roundtrip(self.ymd) _test_roundtrip(self.ymd.T) def test_reindex(self): reindexed = self.frame.ix[[('foo', 'one'), ('bar', 'one')]] expected = self.frame.ix[[0, 3]] assert_frame_equal(reindexed, expected) def test_reindex_preserve_levels(self): new_index = self.ymd.index[::10] chunk = self.ymd.reindex(new_index) self.assertIs(chunk.index, new_index) chunk = self.ymd.ix[new_index] self.assertIs(chunk.index, new_index) ymdT = self.ymd.T chunk = ymdT.reindex(columns=new_index) self.assertIs(chunk.columns, new_index) chunk = ymdT.ix[:, new_index] self.assertIs(chunk.columns, new_index) def test_sort_index_preserve_levels(self): result = self.frame.sort_index() self.assertEquals(result.index.names, self.frame.index.names) def test_repr_to_string(self): repr(self.frame) repr(self.ymd) repr(self.frame.T) repr(self.ymd.T) buf = StringIO() self.frame.to_string(buf=buf) self.ymd.to_string(buf=buf) self.frame.T.to_string(buf=buf) self.ymd.T.to_string(buf=buf) def test_repr_name_coincide(self): index = MultiIndex.from_tuples([('a', 0, 'foo'), ('b', 1, 'bar')], names=['a', 'b', 'c']) df = DataFrame({'value': [0, 1]}, index=index) lines = repr(df).split('\n') self.assert_(lines[2].startswith('a 0 foo')) def test_getitem_simple(self): df = self.frame.T col = df['foo', 'one'] assert_almost_equal(col.values, df.values[:, 0]) self.assertRaises(KeyError, df.__getitem__, ('foo', 'four')) self.assertRaises(KeyError, df.__getitem__, 'foobar') def test_series_getitem(self): s = self.ymd['A'] result = s[2000, 3] result2 = s.ix[2000, 3] expected = s.reindex(s.index[42:65]) expected.index = expected.index.droplevel(0).droplevel(0) assert_series_equal(result, expected) result = s[2000, 3, 10] expected = s[49] self.assertEquals(result, expected) # fancy result = s.ix[[(2000, 3, 10), (2000, 3, 13)]] expected = s.reindex(s.index[49:51]) assert_series_equal(result, expected) # key error self.assertRaises(KeyError, s.__getitem__, (2000, 3, 4)) def test_series_getitem_corner(self): s = self.ymd['A'] # don't segfault, GH #495 # out of bounds access self.assertRaises(IndexError, s.__getitem__, len(self.ymd)) # generator result = s[(x > 0 for x in s)] expected = s[s > 0] assert_series_equal(result, expected) def test_series_setitem(self): s = self.ymd['A'] s[2000, 3] = np.nan self.assert_(isnull(s.values[42:65]).all()) self.assert_(notnull(s.values[:42]).all()) self.assert_(notnull(s.values[65:]).all()) s[2000, 3, 10] = np.nan self.assert_(isnull(s[49])) def test_series_slice_partial(self): pass def test_frame_getitem_setitem_boolean(self): df = self.frame.T.copy() values = df.values result = df[df > 0] expected = df.where(df > 0) assert_frame_equal(result, expected) df[df > 0] = 5 values[values > 0] = 5 assert_almost_equal(df.values, values) df[df == 5] = 0 values[values == 5] = 0 assert_almost_equal(df.values, values) # a df that needs alignment first df[df[:-1] < 0] = 2 np.putmask(values[:-1], values[:-1] < 0, 2) assert_almost_equal(df.values, values) with assertRaisesRegexp(TypeError, 'boolean values only'): df[df * 0] = 2 def test_frame_getitem_setitem_slice(self): # getitem result = self.frame.ix[:4] expected = self.frame[:4] assert_frame_equal(result, expected) # setitem cp = self.frame.copy() cp.ix[:4] = 0 self.assert_((cp.values[:4] == 0).all()) self.assert_((cp.values[4:] != 0).all()) def test_frame_getitem_setitem_multislice(self): levels = [['t1', 't2'], ['a', 'b', 'c']] labels = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]] midx = MultiIndex(labels=labels, levels=levels, names=[None, 'id']) df = DataFrame({'value': [1, 2, 3, 7, 8]}, index=midx) result = df.ix[:, 'value'] assert_series_equal(df['value'], result) result = df.ix[1:3, 'value'] assert_series_equal(df['value'][1:3], result) result = df.ix[:, :] assert_frame_equal(df, result) result = df df.ix[:, 'value'] = 10 result['value'] = 10 assert_frame_equal(df, result) df.ix[:, :] = 10 assert_frame_equal(df, result) def test_frame_getitem_multicolumn_empty_level(self): f = DataFrame({'a': ['1', '2', '3'], 'b': ['2', '3', '4']}) f.columns = [['level1 item1', 'level1 item2'], ['', 'level2 item2'], ['level3 item1', 'level3 item2']] result = f['level1 item1'] expected = DataFrame([['1'], ['2'], ['3']], index=f.index, columns=['level3 item1']) assert_frame_equal(result, expected) def test_frame_setitem_multi_column(self): df = DataFrame(randn(10, 4), columns=[['a', 'a', 'b', 'b'], [0, 1, 0, 1]]) cp = df.copy() cp['a'] = cp['b'] assert_frame_equal(cp['a'], cp['b']) # set with ndarray cp = df.copy() cp['a'] = cp['b'].values assert_frame_equal(cp['a'], cp['b']) #---------------------------------------- # #1803 columns = MultiIndex.from_tuples([('A', '1'), ('A', '2'), ('B', '1')]) df = DataFrame(index=[1, 3, 5], columns=columns) # Works, but adds a column instead of updating the two existing ones df['A'] = 0.0 # Doesn't work self.assertTrue((df['A'].values == 0).all()) # it broadcasts df['B', '1'] = [1, 2, 3] df['A'] = df['B', '1'] assert_series_equal(df['A', '1'], df['B', '1']) assert_series_equal(df['A', '2'], df['B', '1']) def test_getitem_tuple_plus_slice(self): # GH #671 df = DataFrame({'a': lrange(10), 'b': lrange(10), 'c': np.random.randn(10), 'd': np.random.randn(10)}) idf = df.set_index(['a', 'b']) result = idf.ix[(0, 0), :] expected = idf.ix[0, 0] expected2 = idf.xs((0, 0)) assert_series_equal(result, expected) assert_series_equal(result, expected2) def test_getitem_setitem_tuple_plus_columns(self): # GH #1013 df = self.ymd[:5] result = df.ix[(2000, 1, 6), ['A', 'B', 'C']] expected = df.ix[2000, 1, 6][['A', 'B', 'C']] assert_series_equal(result, expected) def test_getitem_multilevel_index_tuple_unsorted(self): index_columns = list("abc") df = DataFrame([[0, 1, 0, "x"], [0, 0, 1, "y"]], columns=index_columns + ["data"]) df = df.set_index(index_columns) query_index = df.index[:1] rs = df.ix[query_index, "data"] xp = Series(['x'], index=MultiIndex.from_tuples([(0, 1, 0)])) assert_series_equal(rs, xp) def test_xs(self): xs = self.frame.xs(('bar', 'two')) xs2 = self.frame.ix[('bar', 'two')] assert_series_equal(xs, xs2) assert_almost_equal(xs.values, self.frame.values[4]) # GH 6574 # missing values in returned index should be preserrved acc = [ ('a','abcde',1), ('b','bbcde',2), ('y','yzcde',25), ('z','xbcde',24), ('z',None,26), ('z','zbcde',25), ('z','ybcde',26), ] df = DataFrame(acc, columns=['a1','a2','cnt']).set_index(['a1','a2']) expected = DataFrame({ 'cnt' : [24,26,25,26] }, index=Index(['xbcde',np.nan,'zbcde','ybcde'],name='a2')) result = df.xs('z',level='a1') assert_frame_equal(result, expected) def test_xs_partial(self): result = self.frame.xs('foo') result2 = self.frame.ix['foo'] expected = self.frame.T['foo'].T assert_frame_equal(result, expected) assert_frame_equal(result, result2) result = self.ymd.xs((2000, 4)) expected = self.ymd.ix[2000, 4] assert_frame_equal(result, expected) # ex from #1796 index = MultiIndex(levels=[['foo', 'bar'], ['one', 'two'], [-1, 1]], labels=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1]]) df = DataFrame(np.random.randn(8, 4), index=index, columns=list('abcd')) result = df.xs(['foo', 'one']) expected = df.ix['foo', 'one'] assert_frame_equal(result, expected) def test_xs_level(self): result = self.frame.xs('two', level='second') expected = self.frame[self.frame.index.get_level_values(1) == 'two'] expected.index = expected.index.droplevel(1) assert_frame_equal(result, expected) index = MultiIndex.from_tuples([('x', 'y', 'z'), ('a', 'b', 'c'), ('p', 'q', 'r')]) df = DataFrame(np.random.randn(3, 5), index=index) result = df.xs('c', level=2) expected = df[1:2] expected.index = expected.index.droplevel(2) assert_frame_equal(result, expected) # this is a copy in 0.14 result = self.frame.xs('two', level='second') # setting this will give a SettingWithCopyError # as we are trying to write a view def f(x): x[:] = 10 self.assertRaises(com.SettingWithCopyError, f, result) def test_xs_level_multiple(self): from pandas import read_table text = """ A B C D E one two three four a b 10.0032 5 -0.5109 -2.3358 -0.4645 0.05076 0.3640 a q 20 4 0.4473 1.4152 0.2834 1.00661 0.1744 x q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838""" df = read_table(StringIO(text), sep='\s+', engine='python') result = df.xs(('a', 4), level=['one', 'four']) expected = df.xs('a').xs(4, level='four') assert_frame_equal(result, expected) # this is a copy in 0.14 result = df.xs(('a', 4), level=['one', 'four']) # setting this will give a SettingWithCopyError # as we are trying to write a view def f(x): x[:] = 10 self.assertRaises(com.SettingWithCopyError, f, result) # GH2107 dates = lrange(20111201, 20111205) ids = 'abcde' idx = MultiIndex.from_tuples([x for x in cart_product(dates, ids)]) idx.names = ['date', 'secid'] df = DataFrame(np.random.randn(len(idx), 3), idx, ['X', 'Y', 'Z']) rs = df.xs(20111201, level='date') xp = df.ix[20111201, :] assert_frame_equal(rs, xp) def test_xs_level0(self): from pandas import read_table text = """ A B C D E one two three four a b 10.0032 5 -0.5109 -2.3358 -0.4645 0.05076 0.3640 a q 20 4 0.4473 1.4152 0.2834 1.00661 0.1744 x q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838""" df = read_table(StringIO(text), sep='\s+', engine='python') result = df.xs('a', level=0) expected = df.xs('a') self.assertEqual(len(result), 2) assert_frame_equal(result, expected) def test_xs_level_series(self): s = self.frame['A'] result = s[:, 'two'] expected = self.frame.xs('two', level=1)['A'] assert_series_equal(result, expected) s = self.ymd['A'] result = s[2000, 5] expected = self.ymd.ix[2000, 5]['A'] assert_series_equal(result, expected) # not implementing this for now self.assertRaises(TypeError, s.__getitem__, (2000, slice(3, 4))) # result = s[2000, 3:4] # lv =s.index.get_level_values(1) # expected = s[(lv == 3) | (lv == 4)] # expected.index = expected.index.droplevel(0) # assert_series_equal(result, expected) # can do this though def test_get_loc_single_level(self): s = Series(np.random.randn(len(self.single_level)), index=self.single_level) for k in self.single_level.values: s[k] def test_getitem_toplevel(self): df = self.frame.T result = df['foo'] expected = df.reindex(columns=df.columns[:3]) expected.columns = expected.columns.droplevel(0) assert_frame_equal(result, expected) result = df['bar'] result2 = df.ix[:, 'bar'] expected = df.reindex(columns=df.columns[3:5]) expected.columns = expected.columns.droplevel(0) assert_frame_equal(result, expected) assert_frame_equal(result, result2) def test_getitem_setitem_slice_integers(self): index = MultiIndex(levels=[[0, 1, 2], [0, 2]], labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]]) frame = DataFrame(np.random.randn(len(index), 4), index=index, columns=['a', 'b', 'c', 'd']) res = frame.ix[1:2] exp = frame.reindex(frame.index[2:]) assert_frame_equal(res, exp) frame.ix[1:2] = 7 self.assert_((frame.ix[1:2] == 7).values.all()) series = Series(np.random.randn(len(index)), index=index) res = series.ix[1:2] exp = series.reindex(series.index[2:]) assert_series_equal(res, exp) series.ix[1:2] = 7 self.assert_((series.ix[1:2] == 7).values.all()) def test_getitem_int(self): levels = [[0, 1], [0, 1, 2]] labels = [[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]] index = MultiIndex(levels=levels, labels=labels) frame = DataFrame(np.random.randn(6, 2), index=index) result = frame.ix[1] expected = frame[-3:] expected.index = expected.index.droplevel(0) assert_frame_equal(result, expected) # raises exception self.assertRaises(KeyError, frame.ix.__getitem__, 3) # however this will work result = self.frame.ix[2] expected = self.frame.xs(self.frame.index[2]) assert_series_equal(result, expected) def test_getitem_partial(self): ymd = self.ymd.T result = ymd[2000, 2] expected = ymd.reindex(columns=ymd.columns[ymd.columns.labels[1] == 1]) expected.columns = expected.columns.droplevel(0).droplevel(0) assert_frame_equal(result, expected) def test_getitem_slice_not_sorted(self): df = self.frame.sortlevel(1).T # buglet with int typechecking result = df.ix[:, :np.int32(3)] expected = df.reindex(columns=df.columns[:3]) assert_frame_equal(result, expected) def test_setitem_change_dtype(self): dft = self.frame.T s = dft['foo', 'two'] dft['foo', 'two'] = s > s.median() assert_series_equal(dft['foo', 'two'], s > s.median()) # tm.assert_isinstance(dft._data.blocks[1].items, MultiIndex) reindexed = dft.reindex(columns=[('foo', 'two')]) assert_series_equal(reindexed['foo', 'two'], s > s.median()) def test_frame_setitem_ix(self): self.frame.ix[('bar', 'two'), 'B'] = 5 self.assertEquals(self.frame.ix[('bar', 'two'), 'B'], 5) # with integer labels df = self.frame.copy() df.columns = lrange(3) df.ix[('bar', 'two'), 1] = 7 self.assertEquals(df.ix[('bar', 'two'), 1], 7) def test_fancy_slice_partial(self): result = self.frame.ix['bar':'baz'] expected = self.frame[3:7] assert_frame_equal(result, expected) result = self.ymd.ix[(2000, 2):(2000, 4)] lev = self.ymd.index.labels[1] expected = self.ymd[(lev >= 1) & (lev <= 3)] assert_frame_equal(result, expected) def test_getitem_partial_column_select(self): idx = MultiIndex(labels=[[0, 0, 0], [0, 1, 1], [1, 0, 1]], levels=[['a', 'b'], ['x', 'y'], ['p', 'q']]) df = DataFrame(np.random.rand(3, 2), index=idx) result = df.ix[('a', 'y'), :] expected = df.ix[('a', 'y')] assert_frame_equal(result, expected) result = df.ix[('a', 'y'), [1, 0]] expected = df.ix[('a', 'y')][[1, 0]] assert_frame_equal(result, expected) self.assertRaises(KeyError, df.ix.__getitem__, (('a', 'foo'), slice(None, None))) def test_sortlevel(self): df = self.frame.copy() df.index = np.arange(len(df)) assertRaisesRegexp(TypeError, 'hierarchical index', df.sortlevel, 0) # axis=1 # series a_sorted = self.frame['A'].sortlevel(0) with assertRaisesRegexp(TypeError, 'hierarchical index'): self.frame.reset_index()['A'].sortlevel() # preserve names self.assertEquals(a_sorted.index.names, self.frame.index.names) # inplace rs = self.frame.copy() rs.sortlevel(0, inplace=True) assert_frame_equal(rs, self.frame.sortlevel(0)) def test_sortlevel_large_cardinality(self): # #2684 (int64) index = MultiIndex.from_arrays([np.arange(4000)]*3) df = DataFrame(np.random.randn(4000), index=index, dtype = np.int64) # it works! result = df.sortlevel(0) self.assertTrue(result.index.lexsort_depth == 3) # #2684 (int32) index = MultiIndex.from_arrays([np.arange(4000)]*3) df = DataFrame(np.random.randn(4000), index=index, dtype = np.int32) # it works! result = df.sortlevel(0) self.assert_((result.dtypes.values == df.dtypes.values).all() == True) self.assertTrue(result.index.lexsort_depth == 3) def test_delevel_infer_dtype(self): tuples = [tuple for tuple in cart_product(['foo', 'bar'], [10, 20], [1.0, 1.1])] index = MultiIndex.from_tuples(tuples, names=['prm0', 'prm1', 'prm2']) df = DataFrame(np.random.randn(8, 3), columns=['A', 'B', 'C'], index=index) deleveled = df.reset_index() self.assert_(com.is_integer_dtype(deleveled['prm1'])) self.assert_(com.is_float_dtype(deleveled['prm2'])) def test_reset_index_with_drop(self): deleveled = self.ymd.reset_index(drop=True) self.assertEquals(len(deleveled.columns), len(self.ymd.columns)) deleveled = self.series.reset_index() tm.assert_isinstance(deleveled, DataFrame) self.assertEqual(len(deleveled.columns), len(self.series.index.levels) + 1) deleveled = self.series.reset_index(drop=True) tm.assert_isinstance(deleveled, Series) def test_sortlevel_by_name(self): self.frame.index.names = ['first', 'second'] result = self.frame.sortlevel(level='second') expected = self.frame.sortlevel(level=1) assert_frame_equal(result, expected) def test_sortlevel_mixed(self): sorted_before = self.frame.sortlevel(1) df = self.frame.copy() df['foo'] = 'bar' sorted_after = df.sortlevel(1) assert_frame_equal(sorted_before, sorted_after.drop(['foo'], axis=1)) dft = self.frame.T sorted_before = dft.sortlevel(1, axis=1) dft['foo', 'three'] = 'bar' sorted_after = dft.sortlevel(1, axis=1) assert_frame_equal(sorted_before.drop([('foo', 'three')], axis=1), sorted_after.drop([('foo', 'three')], axis=1)) def test_count_level(self): def _check_counts(frame, axis=0): index = frame._get_axis(axis) for i in range(index.nlevels): result = frame.count(axis=axis, level=i) expected = frame.groupby(axis=axis, level=i).count(axis=axis) expected = expected.reindex_like(result).astype('i8') assert_frame_equal(result, expected) self.frame.ix[1, [1, 2]] = np.nan self.frame.ix[7, [0, 1]] = np.nan self.ymd.ix[1, [1, 2]] = np.nan self.ymd.ix[7, [0, 1]] = np.nan _check_counts(self.frame) _check_counts(self.ymd) _check_counts(self.frame.T, axis=1) _check_counts(self.ymd.T, axis=1) # can't call with level on regular DataFrame df = tm.makeTimeDataFrame() assertRaisesRegexp(TypeError, 'hierarchical', df.count, level=0) self.frame['D'] = 'foo' result = self.frame.count(level=0, numeric_only=True) assert_almost_equal(result.columns, ['A', 'B', 'C']) def test_count_level_series(self): index = MultiIndex(levels=[['foo', 'bar', 'baz'], ['one', 'two', 'three', 'four']], labels=[[0, 0, 0, 2, 2], [2, 0, 1, 1, 2]]) s = Series(np.random.randn(len(index)), index=index) result = s.count(level=0) expected = s.groupby(level=0).count() assert_series_equal(result.astype('f8'), expected.reindex(result.index).fillna(0)) result = s.count(level=1) expected = s.groupby(level=1).count() assert_series_equal(result.astype('f8'), expected.reindex(result.index).fillna(0)) def test_count_level_corner(self): s = self.frame['A'][:0] result = s.count(level=0) expected = Series(0, index=s.index.levels[0]) assert_series_equal(result, expected) df = self.frame[:0] result = df.count(level=0) expected = DataFrame({}, index=s.index.levels[0], columns=df.columns).fillna(0).astype(np.int64) assert_frame_equal(result, expected) def test_unstack(self): # just check that it works for now unstacked = self.ymd.unstack() unstacked2 = unstacked.unstack() # test that ints work unstacked = self.ymd.astype(int).unstack() # test that int32 work unstacked = self.ymd.astype(np.int32).unstack() def test_unstack_multiple_no_empty_columns(self): index = MultiIndex.from_tuples([(0, 'foo', 0), (0, 'bar', 0), (1, 'baz', 1), (1, 'qux', 1)]) s = Series(np.random.randn(4), index=index) unstacked = s.unstack([1, 2]) expected = unstacked.dropna(axis=1, how='all') assert_frame_equal(unstacked, expected) def test_stack(self): # regular roundtrip unstacked = self.ymd.unstack() restacked = unstacked.stack() assert_frame_equal(restacked, self.ymd) unlexsorted = self.ymd.sortlevel(2) unstacked = unlexsorted.unstack(2) restacked = unstacked.stack() assert_frame_equal(restacked.sortlevel(0), self.ymd) unlexsorted = unlexsorted[::-1] unstacked = unlexsorted.unstack(1) restacked = unstacked.stack().swaplevel(1, 2) assert_frame_equal(restacked.sortlevel(0), self.ymd) unlexsorted = unlexsorted.swaplevel(0, 1) unstacked = unlexsorted.unstack(0).swaplevel(0, 1, axis=1) restacked = unstacked.stack(0).swaplevel(1, 2) assert_frame_equal(restacked.sortlevel(0), self.ymd) # columns unsorted unstacked = self.ymd.unstack() unstacked = unstacked.sort(axis=1, ascending=False) restacked = unstacked.stack() assert_frame_equal(restacked, self.ymd) # more than 2 levels in the columns unstacked = self.ymd.unstack(1).unstack(1) result = unstacked.stack(1) expected = self.ymd.unstack() assert_frame_equal(result, expected) result = unstacked.stack(2) expected = self.ymd.unstack(1) assert_frame_equal(result, expected) result = unstacked.stack(0) expected = self.ymd.stack().unstack(1).unstack(1) assert_frame_equal(result, expected) # not all levels present in each echelon unstacked = self.ymd.unstack(2).ix[:, ::3] stacked = unstacked.stack().stack() ymd_stacked = self.ymd.stack() assert_series_equal(stacked, ymd_stacked.reindex(stacked.index)) # stack with negative number result = self.ymd.unstack(0).stack(-2) expected = self.ymd.unstack(0).stack(0) def test_unstack_odd_failure(self): data = """day,time,smoker,sum,len Fri,Dinner,No,8.25,3. Fri,Dinner,Yes,27.03,9 Fri,Lunch,No,3.0,1 Fri,Lunch,Yes,13.68,6 Sat,Dinner,No,139.63,45 Sat,Dinner,Yes,120.77,42 Sun,Dinner,No,180.57,57 Sun,Dinner,Yes,66.82,19 Thur,Dinner,No,3.0,1 Thur,Lunch,No,117.32,44 Thur,Lunch,Yes,51.51,17""" df = pd.read_csv(StringIO(data)).set_index(['day', 'time', 'smoker']) # it works, #2100 result = df.unstack(2) recons = result.stack() assert_frame_equal(recons, df) def test_stack_mixed_dtype(self): df = self.frame.T df['foo', 'four'] = 'foo' df = df.sortlevel(1, axis=1) stacked = df.stack() assert_series_equal(stacked['foo'], df['foo'].stack()) self.assertEqual(stacked['bar'].dtype, np.float_) def test_unstack_bug(self): df = DataFrame({'state': ['naive', 'naive', 'naive', 'activ', 'activ', 'activ'], 'exp': ['a', 'b', 'b', 'b', 'a', 'a'], 'barcode': [1, 2, 3, 4, 1, 3], 'v': ['hi', 'hi', 'bye', 'bye', 'bye', 'peace'], 'extra': np.arange(6.)}) result = df.groupby(['state', 'exp', 'barcode', 'v']).apply(len) unstacked = result.unstack() restacked = unstacked.stack() assert_series_equal(restacked, result.reindex(restacked.index).astype(float)) def test_stack_unstack_preserve_names(self): unstacked = self.frame.unstack() self.assertEquals(unstacked.index.name, 'first') self.assertEquals(unstacked.columns.names, ['exp', 'second']) restacked = unstacked.stack() self.assertEquals(restacked.index.names, self.frame.index.names) def test_unstack_level_name(self): result = self.frame.unstack('second') expected = self.frame.unstack(level=1) assert_frame_equal(result, expected) def test_stack_level_name(self): unstacked = self.frame.unstack('second') result = unstacked.stack('exp') expected = self.frame.unstack().stack(0) assert_frame_equal(result, expected) result = self.frame.stack('exp') expected = self.frame.stack() assert_series_equal(result, expected) def test_stack_unstack_multiple(self): unstacked = self.ymd.unstack(['year', 'month']) expected = self.ymd.unstack('year').unstack('month') assert_frame_equal(unstacked, expected) self.assertEquals(unstacked.columns.names, expected.columns.names) # series s = self.ymd['A'] s_unstacked = s.unstack(['year', 'month']) assert_frame_equal(s_unstacked, expected['A']) restacked = unstacked.stack(['year', 'month']) restacked = restacked.swaplevel(0, 1).swaplevel(1, 2) restacked = restacked.sortlevel(0) assert_frame_equal(restacked, self.ymd) self.assertEquals(restacked.index.names, self.ymd.index.names) # GH #451 unstacked = self.ymd.unstack([1, 2]) expected = self.ymd.unstack(1).unstack(1).dropna(axis=1, how='all') assert_frame_equal(unstacked, expected) unstacked = self.ymd.unstack([2, 1]) expected = self.ymd.unstack(2).unstack(1).dropna(axis=1, how='all') assert_frame_equal(unstacked, expected.ix[:, unstacked.columns]) def test_unstack_period_series(self): # GH 4342 idx1 = pd.PeriodIndex(['2013-01', '2013-01', '2013-02', '2013-02', '2013-03', '2013-03'], freq='M', name='period') idx2 = Index(['A', 'B'] * 3, name='str') value = [1, 2, 3, 4, 5, 6] idx = MultiIndex.from_arrays([idx1, idx2]) s = Series(value, index=idx) result1 = s.unstack() result2 = s.unstack(level=1) result3 = s.unstack(level=0) e_idx = pd.PeriodIndex(['2013-01', '2013-02', '2013-03'], freq='M', name='period') expected = DataFrame({'A': [1, 3, 5], 'B': [2, 4, 6]}, index=e_idx, columns=['A', 'B']) expected.columns.name = 'str' assert_frame_equal(result1, expected) assert_frame_equal(result2, expected) assert_frame_equal(result3, expected.T) idx1 = pd.PeriodIndex(['2013-01', '2013-01', '2013-02', '2013-02', '2013-03', '2013-03'], freq='M', name='period1') idx2 = pd.PeriodIndex(['2013-12', '2013-11', '2013-10', '2013-09', '2013-08', '2013-07'], freq='M', name='period2') idx = pd.MultiIndex.from_arrays([idx1, idx2]) s = Series(value, index=idx) result1 = s.unstack() result2 = s.unstack(level=1) result3 = s.unstack(level=0) e_idx = pd.PeriodIndex(['2013-01', '2013-02', '2013-03'], freq='M', name='period1') e_cols = pd.PeriodIndex(['2013-07', '2013-08', '2013-09', '2013-10', '2013-11', '2013-12'], freq='M', name='period2') expected = DataFrame([[np.nan, np.nan, np.nan, np.nan, 2, 1], [np.nan, np.nan, 4, 3, np.nan, np.nan], [6, 5, np.nan, np.nan, np.nan, np.nan]], index=e_idx, columns=e_cols) assert_frame_equal(result1, expected) assert_frame_equal(result2, expected) assert_frame_equal(result3, expected.T) def test_unstack_period_frame(self): # GH 4342 idx1 = pd.PeriodIndex(['2014-01', '2014-02', '2014-02', '2014-02', '2014-01', '2014-01'], freq='M', name='period1') idx2 = pd.PeriodIndex(['2013-12', '2013-12', '2014-02', '2013-10', '2013-10', '2014-02'], freq='M', name='period2') value = {'A': [1, 2, 3, 4, 5, 6], 'B': [6, 5, 4, 3, 2, 1]} idx = pd.MultiIndex.from_arrays([idx1, idx2]) df = pd.DataFrame(value, index=idx) result1 = df.unstack() result2 = df.unstack(level=1) result3 = df.unstack(level=0) e_1 = pd.PeriodIndex(['2014-01', '2014-02'], freq='M', name='period1') e_2 = pd.PeriodIndex(['2013-10', '2013-12', '2014-02', '2013-10', '2013-12', '2014-02'], freq='M', name='period2') e_cols = pd.MultiIndex.from_arrays(['A A A B B B'.split(), e_2]) expected = DataFrame([[5, 1, 6, 2, 6, 1], [4, 2, 3, 3, 5, 4]], index=e_1, columns=e_cols) assert_frame_equal(result1, expected) assert_frame_equal(result2, expected) e_1 = pd.PeriodIndex(['2014-01', '2014-02', '2014-01', '2014-02'], freq='M', name='period1') e_2 = pd.PeriodIndex(['2013-10', '2013-12', '2014-02'], freq='M', name='period2') e_cols = pd.MultiIndex.from_arrays(['A A B B'.split(), e_1]) expected = DataFrame([[5, 4, 2, 3], [1, 2, 6, 5], [6, 3, 1, 4]], index=e_2, columns=e_cols) assert_frame_equal(result3, expected) def test_stack_multiple_bug(self): """ bug when some uniques are not present in the data #3170""" id_col = ([1] * 3) + ([2] * 3) name = (['a'] * 3) + (['b'] * 3) date = pd.to_datetime(['2013-01-03', '2013-01-04', '2013-01-05'] * 2) var1 = np.random.randint(0, 100, 6) df = DataFrame(dict(ID=id_col, NAME=name, DATE=date, VAR1=var1)) multi = df.set_index(['DATE', 'ID']) multi.columns.name = 'Params' unst = multi.unstack('ID') down = unst.resample('W-THU') rs = down.stack('ID') xp = unst.ix[:, ['VAR1']].resample('W-THU').stack('ID') xp.columns.name = 'Params' assert_frame_equal(rs, xp) def test_stack_dropna(self): # GH #3997 df = pd.DataFrame({'A': ['a1', 'a2'], 'B': ['b1', 'b2'], 'C': [1, 1]}) df = df.set_index(['A', 'B']) stacked = df.unstack().stack(dropna=False) self.assertTrue(len(stacked) > len(stacked.dropna())) stacked = df.unstack().stack(dropna=True) assert_frame_equal(stacked, stacked.dropna()) def test_unstack_multiple_hierarchical(self): df = DataFrame(index=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1]], columns=[[0, 0, 1, 1], [0, 1, 0, 1]]) df.index.names = ['a', 'b', 'c'] df.columns.names = ['d', 'e'] # it works! df.unstack(['b', 'c']) def test_groupby_transform(self): s = self.frame['A'] grouper = s.index.get_level_values(0) grouped = s.groupby(grouper) applied = grouped.apply(lambda x: x * 2) expected = grouped.transform(lambda x: x * 2) assert_series_equal(applied.reindex(expected.index), expected) def test_unstack_sparse_keyspace(self): # memory problems with naive impl #2278 # Generate Long File & Test Pivot NUM_ROWS = 1000 df = DataFrame({'A': np.random.randint(100, size=NUM_ROWS), 'B': np.random.randint(300, size=NUM_ROWS), 'C': np.random.randint(-7, 7, size=NUM_ROWS), 'D': np.random.randint(-19, 19, size=NUM_ROWS), 'E': np.random.randint(3000, size=NUM_ROWS), 'F': np.random.randn(NUM_ROWS)}) idf = df.set_index(['A', 'B', 'C', 'D', 'E']) # it works! is sufficient idf.unstack('E') def test_unstack_unobserved_keys(self): # related to #2278 refactoring levels = [[0, 1], [0, 1, 2, 3]] labels = [[0, 0, 1, 1], [0, 2, 0, 2]] index = MultiIndex(levels, labels) df = DataFrame(np.random.randn(4, 2), index=index) result = df.unstack() self.assertEquals(len(result.columns), 4) recons = result.stack() assert_frame_equal(recons, df) def test_groupby_corner(self): midx = MultiIndex(levels=[['foo'], ['bar'], ['baz']], labels=[[0], [0], [0]], names=['one', 'two', 'three']) df = DataFrame([np.random.rand(4)], columns=['a', 'b', 'c', 'd'], index=midx) # should work df.groupby(level='three') def test_groupby_level_no_obs(self): # #1697 midx = MultiIndex.from_tuples([('f1', 's1'), ('f1', 's2'), ('f2', 's1'), ('f2', 's2'), ('f3', 's1'), ('f3', 's2')]) df = DataFrame( [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx) df1 = df.select(lambda u: u[0] in ['f2', 'f3'], axis=1) grouped = df1.groupby(axis=1, level=0) result = grouped.sum() self.assert_((result.columns == ['f2', 'f3']).all()) def test_join(self): a = self.frame.ix[:5, ['A']] b = self.frame.ix[2:, ['B', 'C']] joined = a.join(b, how='outer').reindex(self.frame.index) expected = self.frame.copy() expected.values[np.isnan(joined.values)] = np.nan self.assert_(not np.isnan(joined.values).all())
assert_frame_equal(joined, expected, check_names=False)
pandas.util.testing.assert_frame_equal
from __future__ import division #brings in Python 3.0 mixed type calculation rules import datetime import inspect import numpy as np import numpy.testing as npt import os.path import pandas as pd import sys from tabulate import tabulate import unittest print("Python version: " + sys.version) print("Numpy version: " + np.__version__) # #find parent directory and import model # parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) # sys.path.append(parent_dir) from ..trex_exe import Trex test = {} class TestTrex(unittest.TestCase): """ Unit tests for T-Rex model. """ print("trex unittests conducted at " + str(datetime.datetime.today())) def setUp(self): """ Setup routine for trex unit tests. :return: """ pass # setup the test as needed # e.g. pandas to open trex qaqc csv # Read qaqc csv and create pandas DataFrames for inputs and expected outputs def tearDown(self): """ Teardown routine for trex unit tests. :return: """ pass # teardown called after each test # e.g. maybe write test results to some text file def create_trex_object(self): # create empty pandas dataframes to create empty object for testing df_empty = pd.DataFrame() # create an empty trex object trex_empty = Trex(df_empty, df_empty) return trex_empty def test_app_rate_parsing(self): """ unittest for function app_rate_testing: method extracts 1st and maximum from each list in a series of lists of app rates """ # create empty pandas dataframes to create empty object for this unittest trex_empty = self.create_trex_object() expected_results = pd.Series([], dtype="object") result = pd.Series([], dtype="object") expected_results = [[0.34, 0.78, 2.34], [0.34, 3.54, 2.34]] try: trex_empty.app_rates = pd.Series([[0.34], [0.78, 3.54], [2.34, 1.384, 2.22]], dtype='object') # trex_empty.app_rates = ([[0.34], [0.78, 3.54], [2.34, 1.384, 2.22]]) # parse app_rates Series of lists trex_empty.app_rate_parsing() result = [trex_empty.first_app_rate, trex_empty.max_app_rate] npt.assert_allclose(result,expected_results,rtol=1e-4, atol=0, err_msg='', verbose=True) finally: tab = [result, expected_results] print("\n") print(inspect.currentframe().f_code.co_name) print(tabulate(tab, headers='keys', tablefmt='rst')) return def test_conc_initial(self): """ unittest for function conc_initial: conc_0 = (app_rate * self.frac_act_ing * food_multiplier) """ # create empty pandas dataframes to create empty object for this unittest trex_empty = self.create_trex_object() result = pd.Series([], dtype = 'float') expected_results = [12.7160, 9.8280, 11.2320] try: # specify an app_rates Series (that is a series of lists, each list representing # a set of application rates for 'a' model simulation) trex_empty.app_rates = pd.Series([[0.34, 1.384, 13.54], [0.78, 11.34, 3.54], [2.34, 1.384, 3.4]], dtype='float') trex_empty.food_multiplier_init_sg = pd.Series([110., 15., 240.], dtype='float') trex_empty.frac_act_ing = pd.Series([0.34, 0.84, 0.02], dtype='float') for i in range(len(trex_empty.frac_act_ing)): result[i] = trex_empty.conc_initial(i, trex_empty.app_rates[i][0], trex_empty.food_multiplier_init_sg[i]) npt.assert_allclose(result,expected_results,rtol=1e-4, atol=0, err_msg='', verbose=True) finally: tab = [result, expected_results] print("\n") print(inspect.currentframe().f_code.co_name) print(tabulate(tab, headers='keys', tablefmt='rst')) return def test_conc_timestep(self): """ unittest for function conc_timestep: """ # create empty pandas dataframes to create empty object for this unittest trex_empty = self.create_trex_object() result = pd.Series([], dtype = 'float') expected_results = [6.25e-5, 0.039685, 7.8886e-30] try: trex_empty.foliar_diss_hlife = pd.Series([.25, 0.75, 0.01], dtype='float') conc_0 = pd.Series([0.001, 0.1, 10.0]) for i in range(len(conc_0)): result[i] = trex_empty.conc_timestep(i, conc_0[i]) npt.assert_allclose(result,expected_results,rtol=1e-4, atol=0, err_msg='', verbose=True) finally: tab = [result, expected_results] print("\n") print(inspect.currentframe().f_code.co_name) print(tabulate(tab, headers='keys', tablefmt='rst')) return def test_percent_to_frac(self): """ unittest for function percent_to_frac: """ # create empty pandas dataframes to create empty object for this unittest trex_empty = self.create_trex_object() expected_results = pd.Series([.04556, .1034, .9389], dtype='float') try: trex_empty.percent_incorp = pd.Series([4.556, 10.34, 93.89], dtype='float') result = trex_empty.percent_to_frac(trex_empty.percent_incorp) npt.assert_allclose(result,expected_results,rtol=1e-4, atol=0, err_msg='', verbose=True) finally: tab = [result, expected_results] print("\n") print(inspect.currentframe().f_code.co_name) print(tabulate(tab, headers='keys', tablefmt='rst')) return def test_inches_to_feet(self): """ unittest for function inches_to_feet: """ # create empty pandas dataframes to create empty object for this unittest trex_empty = self.create_trex_object() expected_results = pd.Series([0.37966, 0.86166, 7.82416], dtype='float') try: trex_empty.bandwidth = pd.Series([4.556, 10.34, 93.89], dtype='float') result = trex_empty.inches_to_feet(trex_empty.bandwidth) npt.assert_allclose(result,expected_results,rtol=1e-4, atol=0, err_msg='', verbose=True) finally: tab = [result, expected_results] print("\n") print(inspect.currentframe().f_code.co_name) print(tabulate(tab, headers='keys', tablefmt='rst')) return def test_at_bird(self): """ unittest for function at_bird: adjusted_toxicity = self.ld50_bird * (aw_bird / self.tw_bird_ld50) ** (self.mineau_sca_fact - 1) """ # create empty pandas dataframes to create empty object for this unittest trex_empty = self.create_trex_object() result = pd.Series([], dtype = 'float') expected_results = pd.Series([69.17640, 146.8274, 56.00997], dtype='float') try: trex_empty.ld50_bird = pd.Series([100., 125., 90.], dtype='float') trex_empty.tw_bird_ld50 = pd.Series([175., 100., 200.], dtype='float') trex_empty.mineau_sca_fact = pd.Series([1.15, 0.9, 1.25], dtype='float') # following variable is unique to at_bird and is thus sent via arg list trex_empty.aw_bird_sm = pd.Series([15., 20., 30.], dtype='float') for i in range(len(trex_empty.aw_bird_sm)): result[i] = trex_empty.at_bird(i, trex_empty.aw_bird_sm[i]) npt.assert_allclose(result,expected_results,rtol=1e-4, atol=0, err_msg='', verbose=True) finally: tab = [result, expected_results] print("\n") print(inspect.currentframe().f_code.co_name) print(tabulate(tab, headers='keys', tablefmt='rst')) return def test_at_bird1(self): """ unittest for function at_bird1; alternative approach using more vectorization: adjusted_toxicity = self.ld50_bird * (aw_bird / self.tw_bird_ld50) ** (self.mineau_sca_fact - 1) """ # create empty pandas dataframes to create empty object for this unittest trex_empty = self.create_trex_object() result = pd.Series([], dtype = 'float') expected_results = pd.Series([69.17640, 146.8274, 56.00997], dtype='float') try: trex_empty.ld50_bird = pd.Series([100., 125., 90.], dtype='float') trex_empty.tw_bird_ld50 = pd.Series([175., 100., 200.], dtype='float') trex_empty.mineau_sca_fact = pd.Series([1.15, 0.9, 1.25], dtype='float') trex_empty.aw_bird_sm = pd.Series([15., 20., 30.], dtype='float') # for i in range(len(trex_empty.aw_bird_sm)): # result[i] = trex_empty.at_bird(i, trex_empty.aw_bird_sm[i]) result = trex_empty.at_bird1(trex_empty.aw_bird_sm) npt.assert_allclose(result,expected_results,rtol=1e-4, atol=0, err_msg='', verbose=True) finally: tab = [result, expected_results] print("\n") print(inspect.currentframe().f_code.co_name) print(tabulate(tab, headers='keys', tablefmt='rst')) return def test_fi_bird(self): """ unittest for function fi_bird: food_intake = (0.648 * (aw_bird ** 0.651)) / (1 - mf_w_bird) """ # create empty pandas dataframes to create empty object for this unittest trex_empty = self.create_trex_object() expected_results = pd.Series([4.19728, 22.7780, 59.31724], dtype='float') try: #?? 'mf_w_bird_1' is a constant (i.e., not an input whose value changes per model simulation run); thus it should #?? be specified here as a constant and not a pd.series -- if this is correct then go ahead and change next line trex_empty.mf_w_bird_1 = pd.Series([0.1, 0.8, 0.9], dtype='float') trex_empty.aw_bird_sm = pd.Series([15., 20., 30.], dtype='float') result = trex_empty.fi_bird(trex_empty.aw_bird_sm, trex_empty.mf_w_bird_1) npt.assert_allclose(result,expected_results,rtol=1e-4, atol=0, err_msg='', verbose=True) finally: tab = [result, expected_results] print("\n") print(inspect.currentframe().f_code.co_name) print(tabulate(tab, headers='keys', tablefmt='rst')) return def test_sc_bird(self): """ unittest for function sc_bird: m_s_a_r = ((self.app_rate * self.frac_act_ing) / 128) * self.density * 10000 # maximum seed application rate=application rate*10000 risk_quotient = m_s_a_r / self.noaec_bird """ # create empty pandas dataframes to create empty object for this unittest trex_empty = self.create_trex_object() expected_results = pd.Series([6.637969, 77.805, 34.96289, np.nan], dtype='float') try: trex_empty.app_rates = pd.Series([[0.34, 1.384, 13.54], [0.78, 11.34, 3.54], [2.34, 1.384, 3.4], [3.]], dtype='object') trex_empty.app_rate_parsing() #get 'first_app_rate' per model simulation run trex_empty.frac_act_ing = pd.Series([0.15, 0.20, 0.34, np.nan], dtype='float') trex_empty.density =
pd.Series([8.33, 7.98, 6.75, np.nan], dtype='float')
pandas.Series
import json import logging import uuid from abc import ABC, abstractmethod from pathlib import Path import numpy as np import pandas as pd import pickle5 as pickle import sklearn from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler import apollo from apollo import metrics logger = logging.getLogger(__name__) def list_templates(): '''List the model templates in the Apollo database. Untrained models can be constructed from these template names using :func:`apollo.models.make_model`. Returns: list of str: The named templates. ''' base = apollo.path('templates') base.mkdir(parents=True, exist_ok=True) template_paths = base.glob('*.json') template_stems = [p.stem for p in template_paths] return template_stems def list_models(): '''List trained models in the Apollo database. Trained models can be constructed from these names using :func:`apollo.models.load_named_model`. Returns: list of str: The trained models. ''' base = apollo.path('models') base.mkdir(parents=True, exist_ok=True) model_paths = base.glob('*.model') model_stems = [p.stem for p in model_paths] return model_stems def make_estimator(e): '''An enhanced version of :func:`sklearn.pipeline.make_pipeline`. If the input is a string, it is interpreted as a dotted import path to a constructor for the estimator. That constructor is called without arguments to create the estimator. If the input is a list, it is interpreted as a pipeline of transformers and estimators. Each element must be a pair ``(name, params)`` where ``name`` is a dotted import path to a constructor, and ``params`` is a dict providing hyper parameters. The final step must be an estimator, and the intermediate steps must be transformers. If the input is any other object, it is checked to contain ``fit`` and ``predict`` methods and is assumed to be the estimator. Otherwise this function raises an :class:`ValueError`. Returns: sklearn.base.BaseEstimator: The estimator. Raises: ValueError: The input could not be cast to an estimator. ''' # If ``e`` is a dotted import path, import it then call it. if isinstance(e, str): ctor = apollo._import_from_str(e) estimator = ctor() # If it has a length, interpret ``e`` as a list of pipeline steps. elif hasattr(e, '__len__'): steps = [] for (name, params) in e: if isinstance(name, str): ctor = apollo._import_from_str(name) step = ctor(**params) steps.append(step) estimator = make_pipeline(*steps) # Otherwise interpret ``e`` directly as an estimator. else: estimator = e # Ensure that it at least has `fit` and `predict`. try: getattr(estimator, 'fit') getattr(estimator, 'predict') except AttributeError: raise ValueError('could not cast into an estimator') return estimator def load_model_from(stream): '''Load a model from a file-like object. Arguments: stream (io.IOBase): A readable, binary stream containing a serialized model. Returns: apollo.models.Model: The model. ''' model = pickle.load(stream) assert isinstance(model, Model), f'{path} is not an Apollo model' return model def load_model_at(path): '''Load a model that is serialized at some path. Arguments: path (str or pathlib.Path): A path to a model. Returns: apollo.models.Model: The model. ''' path = Path(path) stream = path.open('rb') return load_model_from(stream) def load_model(name): '''Load a model from the Apollo database. Models in the Apollo database can be listed with :func:`list_models` or from the command line with ``apollo ls models``. Arguments: name (str): The name of the model. Returns: apollo.models.Model: The model. Raises: FileNotFoundError: No model exists in the database with the given name. ''' path = apollo.path(f'models/{name}.model') if not path.exists(): raise FileNotFoundError(f'No such model: {name}') return load_model_at(path) def make_model_from(template, **kwargs): '''Construct a model from a template. A template is a dictionary giving keyword arguments for the constructor :class:`apollo.models.Model`. Alternativly, the dictionary may contain the key ``_cls`` giving a dotted import path to an alternate constructor. The ``template`` argument may take several forms: :class:`dict` A dictionary is interpreted as a template directly. :class:`io.IOBase` A file-like object containing JSON is parsed into a template. :class:`pathlib.Path` or :class:`str` A path to a JSON file containing the template. Arguments: template (dict or str or pathlib.Path or io.IOBase): A template dictionary or path to a template file. **kwargs: Additional keyword arguments to pass to the model constructor. Returns: apollo.models.Model: An untrained model. ''' # Convert str to Path. if isinstance(template, str): template = Path(template) # Convert Path to file-like. if isinstance(template, Path): template = template.open('r') # Convert file-like to dict. if hasattr(template, 'read'): template = json.load(template) # The kwargs override the template. template.update(kwargs) # Determine which class to instantiate. cls = template.pop('_cls', 'apollo.models.NamModel') cls = apollo._import_from_str(cls) # Load from dict. logger.debug(f'using template: {template}') model = cls(**template) return model def make_model(template_name, **kwargs): '''Construct a model from named template in the Apollo database. Templates in the Apollo database can be listed with :func:`list_templates` or from the command line with ``apollo ls templates``. Arguments: template_name (str): The name of a template in the Apollo database. **kwargs: Additional keyword arguments to pass to the model constructor. Returns: apollo.models.Model: An untrained model. Raises: FileNotFoundError: No template exists in the database with the given name. ''' path = apollo.path(f'templates/{template_name}.json') if not path.exists(): raise FileNotFoundError(f'No such template: {template_name}') return make_model_from(path) class Model(ABC): '''Base class for all Apollo models. In general, an Apollo model is an object which makes predictions, similar to a Scikit-learn estimator. The features being predicted are determined by the target data when the model is fit, and a model must be fit before it can make predictions. The :class:`NamModel` provides a fully functioning model that makes predictions from NAM forecasts and provides several useful preprocesses for predicting solar irradiance. Unlike a Scikit-learn estimator, an Apollo model only recieves target data when it is fit; the model is responsible for loading its own feature data for training and prediction. Also unlike a Scikit-learn estimator, the methods :meth:`fit` and :meth:`predict` deal in Pandas data frames and indices rather than raw Numpy arrays. All models must have the following attributes and methods: - :attr:`name`: Each model must provide a name. This is used to when saving and loading models to and from the Apollo database. The name is accessed as an attribute. - :meth:`load_data`: Models are responsible for loading their own feature data for training and prediction. This method recieves a Pandas index and returns some object representing the feature data. It may accept additional, optional arguments. - :meth:`fit`: Like Scikit-learn estimators, Apollo models must have a ``fit`` method for training the model. However, unlike Scikit-learn estimators, Apollo models have a single required argument, a target DataFrame to fit against. Additional arguments should be forwarded to :meth:`load_data`. - :meth:`predict`: Again like Scikit-learn estimators, Apollo models must have a ``predict`` method for generating predictions. The input to this method is a Pandas index for the resulting prediction. The return value is a DataFrame using that index and columns like the target data frame passed to :meth:`fit`. Additional arguments should be forwarded to :meth:`load_data`. - :meth:`score`: All models have a score method, but unlike Scikit-learn, this method produces a data frame rather than a scalar value. The data frame has one column for each column in th training data, and each row gives a different metric. It is not specified what metrics should be computed nor how they should be interpreted. The default implementation delegates to :func:`apollo.metrics.all`. This base class provides default implementations of :meth:`fit` and :meth:`predict`, however using these requires you to understand a handfull of lower-level pieces. - :attr:`estimator`: The default implementation wraps a Scikit-learn style estimator to perform the actual predictions. It recieves as input the values produced by :meth:`preprocess` (described below). You **must** provide an estimator attribute if you use the default :meth:`fit` or :meth:`predict`. - :meth:`preprocess`: This method transforms the "structured data" returned by :meth:`load_data` and "structured targets" provided by the user into the "raw data" and "raw targets" passed to the estimator. A default implementation is provided that passes the input to the :class:`pandas.DataFrame` constructor. The values returned by the preprocess method are cast to numpy arrays with :func:`numpy.asanyarray` before being sent to the estimator. - :meth:`postprocess`: This method transforms the "raw predictions" returned by the estimator into a fully-fledged DataFrame. The default implementation simply delegates to the DataFrame constructor. ''' def __init__( self, *, name=None, estimator='sklearn.linear_model.LinearRegression', ): '''Initialize a model. Subclasses which do not use the default :meth:`fit` and :meth:`predict` need not call this constructor. keyword Arguments: name (str or None): A name for the estimator. If not given, a UUID is generated. estimator (sklearn.base.BaseEstimator or str or list): A Scikit-learn estimator to generate predictions. It is interpreted by :func:`apollo.models.make_estimator`. ''' self._name = str(name or uuid.uuid4()) self._estimator = make_estimator(estimator) @property def name(self): '''The name of the model. ''' return self._name @property def estimator(self): '''The underlying estimator. ''' return self._estimator @abstractmethod def load_data(self, index, **kwargs): '''Load structured feature data according to some index. Arguments: index (pandas.Index): The index of the data. **kwargs: Implementations may accept additional, optional arguments. Returns: features: Structured feature data, typically a :class:`pandas.DataFrame` or a :class:`xarray.Dataset`. ''' pass def preprocess(self, features, targets=None, fit=False): '''Convert structured data into raw data for the estimator. The default implementation passes both the features and targets to :func:`numpy.asanyarray`. Arguments: features: Structured data returned by :meth:`load_data`. targets: The target data passed into :meth:`fit`. fit (bool): If true, fit lernable transforms against this target data. Returns: pair of pandas.DataFrame: A pair of data frames ``(raw_features, raw_targets)`` containing processed feature data and processed target data respectivly. The ``raw_targets`` will be ``None`` if ``targets`` was None. ''' raw_features = pd.DataFrame(features) raw_targets = pd.DataFrame(raw_targets) if targets is not None else None return raw_features, raw_targets def postprocess(self, raw_predictions, index): '''Convert raw predictions into a :class:`pandas.DataFrame`. The default implementation simply delegates to the :class:`pandas.DataFrame` constructor. Arguments: raw_predictions: The output of ``self.estimator.predict``. index (pandas.Index): The index of the resulting data frame. Returns: pandas.DataFrame: The predictions. ''' return pd.DataFrame(raw_predictions, index=index) def fit(self, targets, **kwargs): '''Fit the models to some target data. Arguments: targets (pandas.DataFrame): The data to fit against. **kwargs: Additional arguments are forwarded to :meth:`load_data`. Returns: Model: self ''' data = self.load_data(targets.index, **kwargs) data, targets = self.preprocess(data, targets, fit=True) logger.debug('fit: casting to numpy') data = np.asanyarray(data) targets = np.asanyarray(targets) logger.debug('fit: fitting estimator') self.estimator.fit(data, targets) return self def predict(self, index, **kwargs): '''Generate a prediction from this model. Arguments: index (pandas.Index): Make predictions for this index. **kwargs: Additional arguments are forwarded to :meth:`load_data`. Returns: pandas.DataFrame: A data frame of predicted values. ''' data = self.load_data(index, **kwargs) data, _ = self.preprocess(data) index = data.index # The preprocess step may change the index. logger.debug('predict: casting to numpy') data = np.asanyarray(data) logger.debug('predict: executing estimator') predictions = self.estimator.predict(data) predictions = self.postprocess(predictions, index) return predictions def save(self, path=None): '''Persist a model to disk. Arguments: path (str or pathlib.Path or None): The path at which to save the model. The default is a path within the Apollo database derived from the model's name. Returns: pathlib.Path: The path at which the model was saved. ''' if path is None: path = apollo.path(f'models/{self.name}.model') path.parent.mkdir(parents=True, exist_ok=True) else: path = Path(path) logger.debug(f'save: writing model to {path}') fd = path.open('wb') pickle.dump(self, fd, protocol=5) return path def score(self, targets, **kwargs): '''Score this model against some target values. Arguments: targets (pandas.DataFrame): The targets to compare against. **kwargs: Additional arguments are forwarded to :meth:`load_data`. Returns: pandas.DataFrame: A table of metrics. ''' targets = targets.replace([np.inf, -np.inf], np.nan).dropna() predictions = self.predict(targets.index, **kwargs) n_missing = len(targets.index) - len(predictions.index) if n_missing != 0: logger.warning(f'missing {n_missing} predictions') targets = targets.reindex(predictions.index) scores = apollo.metrics.all(targets, predictions) scores.index.name = 'metric' return scores class IrradianceModel(Model): '''Base class for irradiance modeling. This class implements :meth:`preprocess` and :meth:`postprocess` methods specifically for irradiance modeling. They require feature and target data to be both be a :class:`~pandas.DataFrame` indexed by timezone-aware :class:`~pandas.DatetimeIndex`. ''' def __init__( self, *, standardize=False, add_time_of_day=True, add_time_of_year=True, daylight_only=False, center=None, **kwargs, ): '''Construct a new model. Keyword Arguments: name (str or None): A name for the estimator. If not given, a UUID is generated. estimator (sklearn.base.BaseEstimator or str or list): A Scikit-learn estimator to generate predictions. It is interpreted by :func:`apollo.models.make_estimator`. standardize (bool): If true, standardize the feature and target data before sending it to the estimator. This transform is not applied to the computed time-of-day and time-of-year features. add_time_of_day (bool): If true, compute time-of-day features. add_time_of_year (bool): If true, compute time-of-year features. daylight_only (bool): If true, timestamps which occur at night are ignored during training and are always predicted to be zero. center (pair of float): The center of the geographic area, as a latitude-longited pair. Used to compute the sunrise and sunset times. Required only when ``daylight_only`` is True. ''' super().__init__(**kwargs) self.add_time_of_day = bool(add_time_of_day) self.add_time_of_year = bool(add_time_of_year) self.daylight_only = bool(daylight_only) self.standardize = bool(standardize) # The names of the output columns, derived from the targets. self.columns = None # The standardizers. The feature scaler may not be used. self.feature_scaler = StandardScaler(copy=False) self.target_scaler = StandardScaler(copy=False) def preprocess(self, data, targets=None, fit=False): '''Process feature data into a numpy array. ''' # If we're fitting, we record the column names. # Otherwise we ensure the targets have the expected columns. if fit: logger.debug('preprocess: recording columns') self.columns = list(targets.columns) elif targets is not None: logger.debug('preprocess: checking columns') assert set(targets.columns) == set(self.columns) # Drop NaNs and infinities. logger.debug('preprocess: dropping NaNs and infinities') data = data.replace([np.inf, -np.inf], np.nan).dropna() if targets is not None: targets = targets.replace([np.inf, -np.inf], np.nan).dropna() # We only support 1-hour frequencies. # For overlapping targets, take the mean. if targets is not None: logger.debug('preprocess: aggregating targets') targets = targets.groupby(targets.index.floor('1h')).mean() # Ignore targets at night (optionally). if targets is not None and self.daylight_only: logger.debug('preprocess: dropping night time targets') times = targets.index (lat, lon) = self.center targets = targets[apollo.is_daylight(times, lat, lon)] # The indices for the data and targets may not match. # We can only consider their intersection. if targets is not None: logger.debug('preprocess: joining features and targets') index = data.index.intersection(targets.index) data = data.loc[index] targets = targets.loc[index] else: index = data.index # Scale the feature data (optionally). if self.standardize: logger.debug('preprocess: scaling features') cols = list(data.columns) raw_data = data[cols].to_numpy() if fit: self.feature_scaler.fit(raw_data) data[cols] = self.feature_scaler.transform(raw_data) # Scale the target data (optionally). if self.standardize and targets is not None: logger.debug('preprocess: scaling targets') cols = self.columns raw_targets = targets[cols].to_numpy() if fit: self.target_scaler.fit(raw_targets) targets[cols] = self.target_scaler.transform(raw_targets) # Compute additional features (optionally). if self.add_time_of_day: logger.debug('preprocess: computing time-of-day') data = data.join(apollo.time_of_day(index)) if self.add_time_of_year: logger.debug('preprocess: computing time-of-year') data = data.join(apollo.time_of_year(index)) # We always return both, even if targets was not given. # We must return numpy arrays. logger.debug('preprocess: casting to numpy') return data, targets def postprocess(self, raw_predictions, index): ''' ''' # Reconstruct the data frame. logger.debug('postprocess: constructing data frame') index = apollo.DatetimeIndex(index, name='time') predictions = super().postprocess(raw_predictions, index) # Set the columns. cols = list(self.columns) assert len(predictions.columns) == len(cols) predictions.columns =
pd.Index(cols)
pandas.Index
""" """ """ >>> # --- >>> # SETUP >>> # --- >>> import os >>> import logging >>> logger = logging.getLogger('PT3S.Rm') >>> # --- >>> # path >>> # --- >>> if __name__ == "__main__": ... try: ... dummy=__file__ ... logger.debug("{0:s}{1:s}{2:s}".format('DOCTEST: __main__ Context: ','path = os.path.dirname(__file__)'," .")) ... path = os.path.dirname(__file__) ... except NameError: ... logger.debug("{0:s}{1:s}{2:s}".format('DOCTEST: __main__ Context: ',"path = '.' because __file__ not defined and: "," from Rm import Rm")) ... path = '.' ... from Rm import Rm ... else: ... path = '.' ... logger.debug("{0:s}{1:s}".format('Not __main__ Context: ',"path = '.' .")) >>> try: ... from PT3S import Mx ... except ImportError: ... logger.debug("{0:s}{1:s}".format("DOCTEST: from PT3S import Mx: ImportError: ","trying import Mx instead ... maybe pip install -e . is active ...")) ... import Mx >>> try: ... from PT3S import Xm ... except ImportError: ... logger.debug("{0:s}{1:s}".format("DOCTEST: from PT3S import Xm: ImportError: ","trying import Xm instead ... maybe pip install -e . is active ...")) ... import Xm >>> # --- >>> # testDir >>> # --- >>> # globs={'testDir':'testdata'} >>> try: ... dummy= testDir ... except NameError: ... testDir='testdata' >>> # --- >>> # dotResolution >>> # --- >>> # globs={'dotResolution':''} >>> try: ... dummy= dotResolution ... except NameError: ... dotResolution='' >>> import pandas as pd >>> import matplotlib.pyplot as plt >>> pd.set_option('display.max_columns',None) >>> pd.set_option('display.width',666666666) >>> # --- >>> # LocalHeatingNetwork SETUP >>> # --- >>> xmlFile=os.path.join(os.path.join(path,testDir),'LocalHeatingNetwork.XML') >>> xm=Xm.Xm(xmlFile=xmlFile) >>> mx1File=os.path.join(path,os.path.join(testDir,'WDLocalHeatingNetwork\B1\V0\BZ1\M-1-0-1'+dotResolution+'.MX1')) >>> mx=Mx.Mx(mx1File=mx1File,NoH5Read=True,NoMxsRead=True) >>> mx.setResultsToMxsFile(NewH5Vec=True) 5 >>> xm.MxSync(mx=mx) >>> rm=Rm(xm=xm,mx=mx) >>> # --- >>> # Plot 3Classes False >>> # --- >>> plt.close('all') >>> ppi=72 # matplotlib default >>> dpi_screen=2*ppi >>> fig=plt.figure(dpi=dpi_screen,linewidth=1.) >>> timeDeltaToT=mx.df.index[2]-mx.df.index[0] >>> # 3Classes und FixedLimits sind standardmaessig Falsch; RefPerc ist standardmaessig Wahr >>> # die Belegung von MCategory gemaess FixedLimitsHigh/Low erfolgt immer ... >>> pFWVB=rm.pltNetDHUS(timeDeltaToT=timeDeltaToT,pFWVBMeasureCBFixedLimitHigh=0.80,pFWVBMeasureCBFixedLimitLow=0.66,pFWVBGCategory=['BLNZ1u5u7'],pVICsDf=pd.DataFrame({'Kundenname': ['VIC1'],'Knotenname': ['V-K007']})) >>> # --- >>> # Check pFWVB Return >>> # --- >>> f=lambda x: "{0:8.5f}".format(x) >>> print(pFWVB[['Measure','MCategory','GCategory','VIC']].round(2).to_string(formatters={'Measure':f})) Measure MCategory GCategory VIC 0 0.81000 Top BLNZ1u5u7 NaN 1 0.67000 Middle NaN 2 0.66000 Middle BLNZ1u5u7 NaN 3 0.66000 Bottom BLNZ1u5u7 VIC1 4 0.69000 Middle NaN >>> # --- >>> # Print >>> # --- >>> (wD,fileName)=os.path.split(xm.xmlFile) >>> (base,ext)=os.path.splitext(fileName) >>> plotFileName=wD+os.path.sep+base+'.'+'pdf' >>> if os.path.exists(plotFileName): ... os.remove(plotFileName) >>> plt.savefig(plotFileName,dpi=2*dpi_screen) >>> os.path.exists(plotFileName) True >>> # --- >>> # Plot 3Classes True >>> # --- >>> plt.close('all') >>> # FixedLimits wird automatisch auf Wahr gesetzt wenn 3Classes Wahr ... >>> pFWVB=rm.pltNetDHUS(timeDeltaToT=timeDeltaToT,pFWVBMeasure3Classes=True,pFWVBMeasureCBFixedLimitHigh=0.80,pFWVBMeasureCBFixedLimitLow=0.66) >>> # --- >>> # LocalHeatingNetwork Clean Up >>> # --- >>> if os.path.exists(mx.h5File): ... os.remove(mx.h5File) >>> if os.path.exists(mx.mxsZipFile): ... os.remove(mx.mxsZipFile) >>> if os.path.exists(mx.h5FileVecs): ... os.remove(mx.h5FileVecs) >>> if os.path.exists(plotFileName): ... os.remove(plotFileName) """ __version__='172.16.58.3.dev1' import warnings # 3.6 #...\Anaconda3\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. # from ._conv import register_converters as _register_converters warnings.simplefilter(action='ignore', category=FutureWarning) #C:\Users\Wolters\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py:107: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. # warnings.warn(message, mplDeprecation, stacklevel=1) import matplotlib.cbook warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation) import os import sys import nbformat from nbconvert.preprocessors import ExecutePreprocessor from nbconvert.preprocessors.execute import CellExecutionError import timeit import xml.etree.ElementTree as ET import re import struct import collections import zipfile import pandas as pd import h5py from collections import namedtuple from operator import attrgetter import subprocess import warnings import tables import math import matplotlib.pyplot as plt from matplotlib import colors from matplotlib.colorbar import make_axes import matplotlib as mpl import matplotlib.gridspec as gridspec import matplotlib.dates as mdates from matplotlib import markers from matplotlib.path import Path from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.backends.backend_pdf import PdfPages import numpy as np import scipy import networkx as nx from itertools import chain import math import sys from copy import deepcopy from itertools import chain import scipy from scipy.signal import savgol_filter import logging # --- # --- PT3S Imports # --- logger = logging.getLogger('PT3S') if __name__ == "__main__": logger.debug("{0:s}{1:s}".format('in MODULEFILE: __main__ Context','.')) else: logger.debug("{0:s}{1:s}{2:s}{3:s}".format('in MODULEFILE: Not __main__ Context: ','__name__: ',__name__," .")) try: from PT3S import Mx except ImportError: logger.debug("{0:s}{1:s}".format('ImportError: ','from PT3S import Mx - trying import Mx instead ... maybe pip install -e . is active ...')) import Mx try: from PT3S import Xm except ImportError: logger.debug("{0:s}{1:s}".format('ImportError: ','from PT3S import Xm - trying import Xm instead ... maybe pip install -e . is active ...')) import Xm try: from PT3S import Am except ImportError: logger.debug("{0:s}{1:s}".format('ImportError: ','from PT3S import Am - trying import Am instead ... maybe pip install -e . is active ...')) import Am try: from PT3S import Lx except ImportError: logger.debug("{0:s}{1:s}".format('ImportError: ','from PT3S import Lx - trying import Lx instead ... maybe pip install -e . is active ...')) import Lx # --- # --- main Imports # --- import argparse import unittest import doctest import math from itertools import tee # --- Parameter Allgemein # ----------------------- DINA6 = (4.13 , 5.83) DINA5 = (5.83 , 8.27) DINA4 = (8.27 , 11.69) DINA3 = (11.69 , 16.54) DINA2 = (16.54 , 23.39) DINA1 = (23.39 , 33.11) DINA0 = (33.11 , 46.81) DINA6q = ( 5.83, 4.13) DINA5q = ( 8.27, 5.83) DINA4q = ( 11.69, 8.27) DINA3q = ( 16.54,11.69) DINA2q = ( 23.39,16.54) DINA1q = ( 33.11,23.39) DINA0q = ( 46.81,33.11) dpiSize=72 DINA4_x=8.2677165354 DINA4_y=11.6929133858 DINA3_x=DINA4_x*math.sqrt(2) DINA3_y=DINA4_y*math.sqrt(2) linestyle_tuple = [ ('loosely dotted', (0, (1, 10))), ('dotted', (0, (1, 1))), ('densely dotted', (0, (1, 1))), ('loosely dashed', (0, (5, 10))), ('dashed', (0, (5, 5))), ('densely dashed', (0, (5, 1))), ('loosely dashdotted', (0, (3, 10, 1, 10))), ('dashdotted', (0, (3, 5, 1, 5))), ('densely dashdotted', (0, (3, 1, 1, 1))), ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))), ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))), ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))] ylimpD=(-5,70) ylimpDmlc=(600,1350) #(300,1050) ylimQD=(-75,300) ylim3rdD=(0,3) yticks3rdD=[0,1,2,3] yGridStepsD=30 yticksALD=[0,3,4,10,20,30,40] ylimALD=(yticksALD[0],yticksALD[-1]) yticksRD=[0,2,4,10,15,30,45] ylimRD=(-yticksRD[-1],yticksRD[-1]) ylimACD=(-5,5) yticksACD=[-5,0,5] yticksTVD=[0,100,135,180,200,300] ylimTVD=(yticksTVD[0],yticksTVD[-1]) plotTVAmLabelD='TIMER u. AM [Sek. u. (N)m3*100]' def getDerivative(df,col,shiftSize=1,windowSize=60,fct=None,savgol_polyorder=None): """ returns a df df: the df col: the col of df to be derived shiftsize: the Difference between 2 indices for dValue and dt windowSize: size for rolling mean or window_length of savgol_filter; choosen filtertechnique is applied after fct windowsSize must be an even number for savgol_filter windowsSize-1 is used fct: function to be applied on dValue/dt savgol_polyorder: if not None savgol_filter is applied; pandas' rolling.mean() is applied otherwise new cols: dt (with shiftSize) dValue (from col) dValueDt (from col); fct applied dValueDtFiltered; choosen filtertechnique is applied """ mDf=df.dropna().copy(deep=True) try: dt=mDf.index.to_series().diff(periods=shiftSize) mDf['dt']=dt mDf['dValue']=mDf[col].diff(periods=shiftSize) mDf=mDf.iloc[shiftSize:] mDf['dValueDt']=mDf.apply(lambda row: row['dValue']/row['dt'].total_seconds(),axis=1) if fct != None: mDf['dValueDt']=mDf['dValueDt'].apply(fct) if savgol_polyorder == None: mDf['dValueDtFiltered']=mDf['dValueDt'].rolling(window=windowSize).mean() mDf=mDf.iloc[windowSize-1:] else: mDf['dValueDtFiltered']=savgol_filter(mDf['dValueDt'].values,windowSize-1, savgol_polyorder) mDf=mDf.iloc[windowSize/2+1+savgol_polyorder-1:] #mDf=mDf.iloc[windowSize-1:] except Exception as e: raise e finally: return mDf def fCVDNodesFromName(x): Nodes=x.replace('°','~') Nodes=Nodes.split('~') Nodes =[Node.lstrip().rstrip() for Node in Nodes if len(Node)>0] return Nodes def fgetMaxpMinFromName(CVDName,dfSegsNodesNDataDpkt): """ returns max. pMin for alle NODEs in CVDName """ nodeLst=fCVDNodesFromName(CVDName) df=dfSegsNodesNDataDpkt[dfSegsNodesNDataDpkt['NODEsName'].isin(nodeLst)][['pMin','pMinMlc']] s=df.max() return s.pMin # --- Funktionen Allgemein # ----------------------- def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) def genTimespans(timeStart ,timeEnd ,timeSpan=pd.Timedelta('12 Minutes') ,timeOverlap=pd.Timedelta('0 Seconds') ,timeStartPraefix=pd.Timedelta('0 Seconds') ,timeEndPostfix=pd.Timedelta('0 Seconds') ): # generates timeSpan-Sections # if timeStart is # an int, it is considered as the number of desired Sections before timeEnd; timeEnd must be a time # a time, it is considered as timeStart # if timeEnd is # an int, it is considered as the number of desired Sections after timeStart; timeStart must be a time # a time, it is considered as timeEnd # if timeSpan is # an int, it is considered as the number of desired Sections # a time, it is considered as timeSpan # returns an array of tuples logStr = "{0:s}.{1:s}: ".format(__name__, sys._getframe().f_code.co_name) logger.debug("{0:s}{1:s}".format(logStr,'Start.')) xlims=[] try: if type(timeStart) == int: numOfDesiredSections=timeStart timeStartEff=timeEnd+timeEndPostfix-numOfDesiredSections*timeSpan+(numOfDesiredSections-1)*timeOverlap-timeStartPraefix else: timeStartEff=timeStart-timeStartPraefix logger.debug("{0:s}timeStartEff: {1:s}".format(logStr,str(timeStartEff))) if type(timeEnd) == int: numOfDesiredSections=timeEnd timeEndEff=timeStart-timeStartPraefix+numOfDesiredSections*timeSpan-(numOfDesiredSections-1)*timeOverlap+timeEndPostfix else: timeEndEff=timeEnd+timeEndPostfix logger.debug("{0:s}timeEndEff: {1:s}".format(logStr,str(timeEndEff))) if type(timeSpan) == int: numOfDesiredSections=timeSpan dt=timeEndEff-timeStartEff timeSpanEff=dt/numOfDesiredSections+(numOfDesiredSections-1)*timeOverlap else: timeSpanEff=timeSpan logger.debug("{0:s}timeSpanEff: {1:s}".format(logStr,str(timeSpanEff))) logger.debug("{0:s}timeOverlap: {1:s}".format(logStr,str(timeOverlap))) timeStartAct = timeStartEff while timeStartAct < timeEndEff: logger.debug("{0:s}timeStartAct: {1:s}".format(logStr,str(timeStartAct))) timeEndAct=timeStartAct+timeSpanEff xlim=(timeStartAct,timeEndAct) xlims.append(xlim) timeStartAct = timeEndAct - timeOverlap except RmError: raise except Exception as e: logStrFinal="{:s}Exception: Line: {:d}: {!s:s}: {:s}".format(logStr,sys.exc_info()[-1].tb_lineno,type(e),str(e)) logger.error(logStrFinal) raise RmError(logStrFinal) finally: logger.debug("{0:s}{1:s}".format(logStr,'_Done.')) return xlims def gen2Timespans( timeStart # Anfang eines "Prozesses" ,timeEnd # Ende eines "Prozesses" ,timeSpan=pd.Timedelta('12 Minutes') ,timeStartPraefix=pd.Timedelta('0 Seconds') ,timeEndPostfix=pd.Timedelta('0 Seconds') ,roundStr=None # i.e. '5min': timeStart.round(roundStr) und timeEnd dito ): """ erzeugt 2 gleich lange Zeitbereiche 1 um timeStart herum 1 um timeEnd herum """ #print("timeStartPraefix: {:s}".format(str(timeStartPraefix))) #print("timeEndPostfix: {:s}".format(str(timeEndPostfix))) xlims=[] logStr = "{0:s}.{1:s}: ".format(__name__, sys._getframe().f_code.co_name) logger.debug("{0:s}{1:s}".format(logStr,'Start.')) try: if roundStr != None: timeStart=timeStart.round(roundStr) timeEnd=timeEnd.round(roundStr) xlims.append((timeStart-timeStartPraefix,timeStart-timeStartPraefix+timeSpan)) xlims.append((timeEnd+timeEndPostfix-timeSpan,timeEnd+timeEndPostfix)) return xlims except RmError: raise except Exception as e: logStrFinal="{:s}Exception: Line: {:d}: {!s:s}: {:s}".format(logStr,sys.exc_info()[-1].tb_lineno,type(e),str(e)) logger.error(logStrFinal) raise RmError(logStrFinal) finally: logger.debug("{0:s}{1:s}".format(logStr,'_Done.')) return xlims def fTotalTimeFromPairs( x ,denominator=None # i.e. pd.Timedelta('1 minute') for totalTime in Minutes ,roundToInt=True # round to and return as int if denominator is specified; else td is rounded by 2 ): tdTotal=pd.Timedelta('0 seconds') for idx,tPairs in enumerate(x): t1,t2=tPairs if idx==0: tLast=t2 else: if t1 <= tLast: print("Zeitpaar überlappt?!") td=t2-t1 if td < pd.Timedelta('1 seconds'): pass #print("Zeitpaar < als 1 Sekunde?!") tdTotal=tdTotal+td if denominator==None: return tdTotal else: td=tdTotal / denominator if roundToInt: td=int(round(td,0)) else: td=round(td,2) return td def findAllTimeIntervalls( df ,fct=lambda row: True if row['col'] == 46 else False ,tdAllowed=None ): logStr = "{0:s}.{1:s}: ".format(__name__, sys._getframe().f_code.co_name) logger.debug("{0:s}{1:s}".format(logStr,'Start.')) tPairs=[] try: rows,cols=df.shape if df.empty: logger.debug("{:s}df ist leer".format(logStr)) elif rows == 1: logger.debug("{:s}df hat nur 1 Zeile: {:s}".format(logStr,df.to_string())) rowValue=fct(df.iloc[0]) if rowValue: tPair=(df.index[0],df.index[0]) tPairs.append(tPair) else: pass else: tEin=None # paarweise über alle Zeilen for (i1, row1), (i2, row2) in pairwise(df.iterrows()): row1Value=fct(row1) row2Value=fct(row2) # wenn 1 nicht x und 2 x tEin=t2 "geht Ein" if not row1Value and row2Value: tEin=i2 # wenn 1 x und 2 nicht x tAus=t2 "geht Aus" elif row1Value and not row2Value: if tEin != None: # Paar speichern tPair=(tEin,i1) tPairs.append(tPair) else: pass # sonst: Bed. ist jetzt Aus und war nicht Ein # Bed. kann nur im ersten Fall Ein gehen # wenn 1 x und 2 x elif row1Value and row2Value: if tEin != None: pass else: # im ersten Wertepaar ist der Bereich Ein tEin=i1 # letztes Paar if row1Value and row2Value: if tEin != None: tPair=(tEin,i2) tPairs.append(tPair) if tdAllowed != None: tPairs=fCombineSubsequenttPairs(tPairs,tdAllowed) except RmError: raise except Exception as e: logStrFinal="{:s}Exception: Line: {:d}: {!s:s}: {:s}".format(logStr,sys.exc_info()[-1].tb_lineno,type(e),str(e)) logger.error(logStrFinal) raise RmError(logStrFinal) finally: logger.debug("{0:s}{1:s}".format(logStr,'_Done.')) return tPairs def findAllTimeIntervallsSeries( s=pd.Series() ,fct=lambda x: True if x == 46 else False ,tdAllowed=None # if not None all subsequent TimePairs with TimeDifference <= tdAllowed are combined to one TimePair ,debugOutput=True ): """ # if fct: # alle [Zeitbereiche] finden fuer die fct Wahr ist; diese Zeitbereiche werden geliefert; es werden nur Paare geliefert; Wahr-Solitäre gehen nicht verloren sondern werden als Paar (t,t) geliefert # Wahr-Solitäre sind NUR dann enthalten, wenn s nur 1 Wert enthält und dieser Wahr ist; das 1 gelieferte Paar enthaelt dann den Solitär-Zeitstempel für beide Zeiten # tdAllowed can be be specified # dann im Anschluss in Zeitbereiche zusammenfassen, die nicht mehr als tdAllowed auseinander liegen; diese Zeitbereiche werden dann geliefert # if fct None: # tdAllowed must be specified # in Zeitbereiche zerlegen, die nicht mehr als Schwellwert tdAllowed auseinander liegen; diese Zeitbereiche werden geliefert # generell hat jeder gelieferte Zeitbereich Anfang und Ende (d.h. 2 Zeiten), auch dann, wenn dadurch ein- oder mehrfach der Schwellwert ignoriert werden muss # denn es soll kein Zeitbereich verloren gehen, der in s enthalten ist # wenn s nur 1 Wert enthält, wird 1 Zeitpaar mit demselben Zeitstempel für beide Zeiten geliefert, wenn Wert nicht Null # returns array of Time-Pair-Tuples >>> import pandas as pd >>> t=pd.Timestamp('2021-03-19 01:02:00') >>> t1=t +pd.Timedelta('1 second') >>> t2=t1+pd.Timedelta('1 second') >>> t3=t2+pd.Timedelta('1 second') >>> t4=t3+pd.Timedelta('1 second') >>> t5=t4+pd.Timedelta('1 second') >>> t6=t5+pd.Timedelta('1 second') >>> t7=t6+pd.Timedelta('1 second') >>> d = {t1: 46, t2: 0} # geht aus - kein Paar >>> s1PaarGehtAus=pd.Series(data=d, index=[t1, t2]) >>> d = {t1: 0, t2: 46} # geht ein - kein Paar >>> s1PaarGehtEin=pd.Series(data=d, index=[t1, t2]) >>> d = {t5: 46, t6: 0} # geht ausE - kein Paar >>> s1PaarGehtAusE=pd.Series(data=d, index=[t5, t6]) >>> d = {t5: 0, t6: 46} # geht einE - kein Paar >>> s1PaarGehtEinE=pd.Series(data=d, index=[t5, t6]) >>> d = {t1: 46, t2: 46} # geht aus - ein Paar >>> s1PaarEin=pd.Series(data=d, index=[t1, t2]) >>> d = {t1: 0, t2: 0} # geht aus - kein Paar >>> s1PaarAus=pd.Series(data=d, index=[t1, t2]) >>> s2PaarAus=pd.concat([s1PaarGehtAus,s1PaarGehtAusE]) >>> s2PaarEin=pd.concat([s1PaarGehtEin,s1PaarGehtEinE]) >>> s2PaarAusEin=pd.concat([s1PaarGehtAus,s1PaarGehtEinE]) >>> s2PaarEinAus=pd.concat([s1PaarGehtEin,s1PaarGehtAusE]) >>> # 1 Wert >>> d = {t1: 46} # 1 Wert - Wahr >>> s1WertWahr=pd.Series(data=d, index=[t1]) >>> d = {t1: 44} # 1 Wert - Falsch >>> s1WertFalsch=pd.Series(data=d, index=[t1]) >>> d = {t1: None} # 1 Wert - None >>> s1WertNone=pd.Series(data=d, index=[t1]) >>> ### >>> # 46 0 >>> # 0 46 >>> # 0 0 >>> # 46 46 !1 Paar >>> # 46 0 46 0 >>> # 46 0 0 46 >>> # 0 46 0 46 >>> # 0 46 46 0 !1 Paar >>> ### >>> findAllTimeIntervallsSeries(s1PaarGehtAus) [] >>> findAllTimeIntervallsSeries(s1PaarGehtEin) [] >>> findAllTimeIntervallsSeries(s1PaarEin) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02'))] >>> findAllTimeIntervallsSeries(s1PaarAus) [] >>> findAllTimeIntervallsSeries(s2PaarAus) [] >>> findAllTimeIntervallsSeries(s2PaarEin) [] >>> findAllTimeIntervallsSeries(s2PaarAusEin) [] >>> findAllTimeIntervallsSeries(s2PaarEinAus) [(Timestamp('2021-03-19 01:02:02'), Timestamp('2021-03-19 01:02:05'))] >>> # 1 Wert >>> findAllTimeIntervallsSeries(s1WertWahr) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:01'))] >>> findAllTimeIntervallsSeries(s1WertFalsch) [] >>> ### >>> # 46 0 !1 Paar >>> # 0 46 !1 Paar >>> # 0 0 !1 Paar >>> # 46 46 !1 Paar >>> # 46 0 46 0 !2 Paare >>> # 46 0 0 46 !2 Paare >>> # 0 46 0 46 !2 Paare >>> # 0 46 46 0 !2 Paare >>> ### >>> findAllTimeIntervallsSeries(s1PaarGehtAus,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02'))] >>> findAllTimeIntervallsSeries(s1PaarGehtEin,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02'))] >>> findAllTimeIntervallsSeries(s1PaarEin,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02'))] >>> findAllTimeIntervallsSeries(s1PaarAus,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02'))] >>> findAllTimeIntervallsSeries(s2PaarAus,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02')), (Timestamp('2021-03-19 01:02:05'), Timestamp('2021-03-19 01:02:06'))] >>> findAllTimeIntervallsSeries(s2PaarEin,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02')), (Timestamp('2021-03-19 01:02:05'), Timestamp('2021-03-19 01:02:06'))] >>> findAllTimeIntervallsSeries(s2PaarAusEin,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02')), (Timestamp('2021-03-19 01:02:05'), Timestamp('2021-03-19 01:02:06'))] >>> findAllTimeIntervallsSeries(s2PaarEinAus,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02')), (Timestamp('2021-03-19 01:02:05'), Timestamp('2021-03-19 01:02:06'))] >>> # 1 Wert >>> findAllTimeIntervallsSeries(s1WertWahr,fct=None) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:01'))] >>> findAllTimeIntervallsSeries(s1WertNone,fct=None) [] >>> ### >>> d = {t1: 0, t3: 0} >>> s1PaarmZ=pd.Series(data=d, index=[t1, t3]) >>> findAllTimeIntervallsSeries(s1PaarmZ,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:03'))] >>> d = {t4: 0, t5: 0} >>> s1PaaroZ=pd.Series(data=d, index=[t4, t5]) >>> s2PaarmZoZ=pd.concat([s1PaarmZ,s1PaaroZ]) >>> findAllTimeIntervallsSeries(s2PaarmZoZ,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:05'))] >>> ### >>> d = {t1: 0, t2: 0} >>> s1PaaroZ=pd.Series(data=d, index=[t1, t2]) >>> d = {t3: 0, t5: 0} >>> s1PaarmZ=pd.Series(data=d, index=[t3, t5]) >>> s2PaaroZmZ=pd.concat([s1PaaroZ,s1PaarmZ]) >>> findAllTimeIntervallsSeries(s2PaaroZmZ,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:05'))] >>> ### >>> d = {t6: 0, t7: 0} >>> s1PaaroZ2=pd.Series(data=d, index=[t6, t7]) >>> d = {t4: 0} >>> solitaer=pd.Series(data=d, index=[t4]) >>> s5er=pd.concat([s1PaaroZ,solitaer,s1PaaroZ2]) >>> findAllTimeIntervallsSeries(s5er,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:02')), (Timestamp('2021-03-19 01:02:04'), Timestamp('2021-03-19 01:02:07'))] >>> s3er=pd.concat([s1PaaroZ,solitaer]) >>> findAllTimeIntervallsSeries(s3er,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:01'), Timestamp('2021-03-19 01:02:04'))] >>> s3er=pd.concat([solitaer,s1PaaroZ2]) >>> findAllTimeIntervallsSeries(s3er,fct=None,tdAllowed=pd.Timedelta('1 second')) [(Timestamp('2021-03-19 01:02:04'), Timestamp('2021-03-19 01:02:07'))] """ logStr = "{0:s}.{1:s}: ".format(__name__, sys._getframe().f_code.co_name) #logger.debug("{0:s}{1:s}".format(logStr,'Start.')) tPairs=[] try: if s.empty: logger.debug("{:s}Series {!s:s} ist leer".format(logStr,s.name)) elif s.size == 1: logger.debug("{:s}Series {!s:s} hat nur 1 Element: {:s}".format(logStr,s.name,s.to_string())) if fct != None: # 1 Paar mit selben Zeiten wenn das 1 Element Wahr sValue=fct(s.iloc[0]) if sValue: tPair=(s.index[0],s.index[0]) tPairs.append(tPair) else: pass else: # 1 Paar mit selben Zeiten wenn das 1 Element nicht None sValue=s.iloc[0] if sValue != None: tPair=(s.index[0],s.index[0]) tPairs.append(tPair) else: pass else: tEin=None if fct != None: # paarweise über alle Zeiten for idx,((i1, s1), (i2, s2)) in enumerate(pairwise(s.iteritems())): s1Value=fct(s1) s2Value=fct(s2) # wenn 1 nicht x und 2 x tEin=t2 "geht Ein" if not s1Value and s2Value: tEin=i2 if idx > 0: # Info pass else: # beim ersten Paar "geht Ein" pass # wenn 1 x und 2 nicht x tAus=t2 "geht Aus" elif s1Value and not s2Value: if tEin != None: if tEin<i1: # Paar speichern tPair=(tEin,i1) tPairs.append(tPair) else: # singulaeres Ereignis # Paar mit selben Zeiten tPair=(tEin,i1) tPairs.append(tPair) pass else: # geht Aus ohne Ein zu sein if idx > 0: # Info pass else: # im ersten Paar pass # wenn 1 x und 2 x elif s1Value and s2Value: if tEin != None: pass else: # im ersten Wertepaar ist der Bereich Ein tEin=i1 # Behandlung letztes Paar # bleibt Ein am Ende der Series: Paar speichern if s1Value and s2Value: if tEin != None: tPair=(tEin,i2) tPairs.append(tPair) # Behandlung tdAllowed if tdAllowed != None: if debugOutput: logger.debug("{:s}Series {!s:s}: Intervalle werden mit {!s:s} zusammengefasst ...".format(logStr,s.name,tdAllowed)) tPairsOld=tPairs.copy() tPairs=fCombineSubsequenttPairs(tPairs,tdAllowed,debugOutput=debugOutput) if debugOutput: tPairsZusammengefasst=sorted(list(set(tPairsOld) - set(tPairs))) if len(tPairsZusammengefasst)>0: logger.debug("{:s}Series {!s:s}: Intervalle wurden wg. {!s:s} zusammengefasst. Nachfolgend die zusgefassten Intervalle: {!s:s}. Sowie die entsprechenden neuen: {!s:s}".format( logStr ,s.name ,tdAllowed ,tPairsZusammengefasst ,sorted(list(set(tPairs) - set(tPairsOld))) )) else: # paarweise über alle Zeiten # neues Paar beginnen anzInPair=1 # Anzahl der Zeiten in aktueller Zeitspanne for (i1, s1), (i2, s2) in pairwise(s.iteritems()): td=i2-i1 if td > tdAllowed: # Zeit zwischen 2 Zeiten > als Schwelle: Zeitspanne ist abgeschlossen if tEin==None: # erstes Paar liegt bereits > als Schwelle auseinander # Zeitspannenabschluss wird ignoriert, denn sonst Zeitspanne mit nur 1 Wert # aktuelle Zeitspanne beginnt beim 1. Wert und geht über Schwellwert tEin=i1 anzInPair=2 else: if anzInPair>=2: # Zeitspanne abschließen tPair=(tEin,i1) tPairs.append(tPair) # neue Zeitspanne beginnen tEin=i2 anzInPair=1 else: # Zeitspannenabschluss wird ignoriert, denn sonst Zeitspanne mit nur 1 Wert anzInPair=2 else: # Zeitspanne zugelassen, weiter ... if tEin==None: tEin=i1 anzInPair=anzInPair+1 # letztes Zeitpaar behandeln if anzInPair>=2: tPair=(tEin,i2) tPairs.append(tPair) else: # ein letzter Wert wuerde ueber bleiben, letzte Zeitspanne verlängern ... tPair=tPairs[-1] tPair=(tPair[0],i2) tPairs[-1]=tPair except RmError: raise except Exception as e: logStrFinal="{:s}Exception: Line: {:d}: {!s:s}: {:s}".format(logStr,sys.exc_info()[-1].tb_lineno,type(e),str(e)) logger.error(logStrFinal) raise RmError(logStrFinal) finally: #logger.debug("{0:s}{1:s}".format(logStr,'_Done.')) return tPairs def fCombineSubsequenttPairs( tPairs ,tdAllowed=pd.Timedelta('1 second') # all subsequent TimePairs with TimeDifference <= tdAllowed are combined to one TimePair ,debugOutput=False ): # returns tPairs logStr = "{0:s}.{1:s}: ".format(__name__, sys._getframe().f_code.co_name) #logger.debug("{0:s}{1:s}".format(logStr,'Start.')) try: for idx,(tp1,tp2) in enumerate(pairwise(tPairs)): t1Ende=tp1[1] t2Start=tp2[0] if t2Start-t1Ende <= tdAllowed: if debugOutput: logger.debug("{:s} t1Ende: {!s:s} t2Start: {!s:s} Gap: {!s:s}".format(logStr,t1Ende,t2Start,t2Start-t1Ende)) tPairs[idx]=(tp1[0],tp2[1]) # Folgepaar in vorheriges Paar integrieren tPairs.remove(tp2) # Folgepaar löschen tPairs=fCombineSubsequenttPairs(tPairs,tdAllowed) # Rekursion except RmError: raise except Exception as e: logStrFinal="{:s}Exception: Line: {:d}: {!s:s}: {:s}".format(logStr,sys.exc_info()[-1].tb_lineno,type(e),str(e)) logger.error(logStrFinal) raise RmError(logStrFinal) finally: #logger.debug("{0:s}{1:s}".format(logStr,'_Done.')) return tPairs class RmError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) AlarmEvent = namedtuple('alarmEvent','tA,tE,ZHKNR,LDSResBaseType') # --- Parameter und Funktionen LDS Reports # ---------------------------------------- def pltMakeCategoricalColors(color,nOfSubColorsReq=3,reversedOrder=False): """ Returns an array of rgb colors derived from color. Parameter: color: a rgb color nOfSubColorsReq: number of SubColors requested Raises: RmError >>> import matplotlib >>> color='red' >>> c=list(matplotlib.colors.to_rgb(color)) >>> import Rm >>> Rm.pltMakeCategoricalColors(c) array([[1. , 0. , 0. ], [1. , 0.375, 0.375], [1. , 0.75 , 0.75 ]]) """ logStr = "{0:s}.{1:s}: ".format(__name__, sys._getframe().f_code.co_name) logger.debug("{0:s}{1:s}".format(logStr,'Start.')) rgb=None try: chsv = matplotlib.colors.rgb_to_hsv(color[:3]) arhsv = np.tile(chsv,nOfSubColorsReq).reshape(nOfSubColorsReq,3) arhsv[:,1] = np.linspace(chsv[1],0.25,nOfSubColorsReq) arhsv[:,2] = np.linspace(chsv[2],1,nOfSubColorsReq) rgb = matplotlib.colors.hsv_to_rgb(arhsv) if reversedOrder: rgb=list(reversed(rgb)) except RmError: raise except Exception as e: logStrFinal="{:s}Exception: Line: {:d}: {!s:s}: {:s}".format(logStr,sys.exc_info()[-1].tb_lineno,type(e),str(e)) logger.error(logStrFinal) raise RmError(logStrFinal) finally: logger.debug("{0:s}{1:s}".format(logStr,'_Done.')) return rgb # Farben fuer Druecke SrcColorp='green' SrcColorsp=pltMakeCategoricalColors(list(matplotlib.colors.to_rgb(SrcColorp)),nOfSubColorsReq=4,reversedOrder=False) # erste Farbe ist Original-Farbe SnkColorp='blue' SnkColorsp=pltMakeCategoricalColors(list(matplotlib.colors.to_rgb(SnkColorp)),nOfSubColorsReq=4,reversedOrder=True) # letzte Farbe ist Original-Farbe # Farben fuer Fluesse SrcColorQ='red' SrcColorsQ=pltMakeCategoricalColors(list(matplotlib.colors.to_rgb(SrcColorQ)),nOfSubColorsReq=4,reversedOrder=False) # erste Farbe ist Original-Farbe SnkColorQ='orange' SnkColorsQ=pltMakeCategoricalColors(list(matplotlib.colors.to_rgb(SnkColorQ)),nOfSubColorsReq=4,reversedOrder=True) # letzte Farbe ist Original-Farbe lwBig=4.5 lwSmall=2.5 attrsDct={ 'p Src':{'color':SrcColorp,'lw':lwBig,'where':'post'} ,'p Snk':{'color':SnkColorp,'lw':lwSmall+1.,'where':'post'} ,'p Snk 2':{'color':'mediumorchid','where':'post'} ,'p Snk 3':{'color':'darkviolet','where':'post'} ,'p Snk 4':{'color':'plum','where':'post'} ,'Q Src':{'color':SrcColorQ,'lw':lwBig,'where':'post'} ,'Q Snk':{'color':SnkColorQ,'lw':lwSmall+1.,'where':'post'} ,'Q Snk 2':{'color':'indianred','where':'post'} ,'Q Snk 3':{'color':'coral','where':'post'} ,'Q Snk 4':{'color':'salmon','where':'post'} ,'Q Src RTTM':{'color':SrcColorQ,'lw':matplotlib.rcParams['lines.linewidth']+1.,'ls':'dotted','where':'post'} ,'Q Snk RTTM':{'color':SnkColorQ,'lw':matplotlib.rcParams['lines.linewidth'] ,'ls':'dotted','where':'post'} ,'Q Snk 2 RTTM':{'color':'indianred','ls':'dotted','where':'post'} ,'Q Snk 3 RTTM':{'color':'coral','ls':'dotted','where':'post'} ,'Q Snk 4 RTTM':{'color':'salmon','ls':'dotted','where':'post'} ,'p ISrc 1':{'color':SrcColorsp[-1],'ls':'dashdot','where':'post'} ,'p ISrc 2':{'color':SrcColorsp[-2],'ls':'dashdot','where':'post'} ,'p ISrc 3':{'color':SrcColorsp[-2],'ls':'dashdot','where':'post'} # ab hier selbe Farbe ,'p ISrc 4':{'color':SrcColorsp[-2],'ls':'dashdot','where':'post'} ,'p ISrc 5':{'color':SrcColorsp[-2],'ls':'dashdot','where':'post'} ,'p ISrc 6':{'color':SrcColorsp[-2],'ls':'dashdot','where':'post'} ,'p ISnk 1':{'color':SnkColorsp[0],'ls':'dashdot','where':'post'} ,'p ISnk 2':{'color':SnkColorsp[1],'ls':'dashdot','where':'post'} ,'p ISnk 3':{'color':SnkColorsp[1],'ls':'dashdot','where':'post'} # ab hier selbe Farbe ,'p ISnk 4':{'color':SnkColorsp[1],'ls':'dashdot','where':'post'} ,'p ISnk 5':{'color':SnkColorsp[1],'ls':'dashdot','where':'post'} ,'p ISnk 6':{'color':SnkColorsp[1],'ls':'dashdot','where':'post'} ,'Q xSrc 1':{'color':SrcColorsQ[-1],'ls':'dashdot','where':'post'} ,'Q xSrc 2':{'color':SrcColorsQ[-2],'ls':'dashdot','where':'post'} ,'Q xSrc 3':{'color':SrcColorsQ[-3],'ls':'dashdot','where':'post'} ,'Q xSnk 1':{'color':SnkColorsQ[0],'ls':'dashdot','where':'post'} ,'Q xSnk 2':{'color':SnkColorsQ[1],'ls':'dashdot','where':'post'} ,'Q xSnk 3':{'color':SnkColorsQ[2],'ls':'dashdot','where':'post'} ,'Q (DE) Me':{'color': 'indigo','ls': 'dashdot','where': 'post','lw':1.5} ,'Q (DE) Re':{'color': 'cyan','ls': 'dashdot','where': 'post','lw':3.5} ,'p (DE) SS Me':{'color': 'magenta','ls': 'dashdot','where': 'post'} ,'p (DE) DS Me':{'color': 'darkviolet','ls': 'dashdot','where': 'post'} ,'p (DE) SS Re':{'color': 'magenta','ls': 'dotted','where': 'post'} ,'p (DE) DS Re':{'color': 'darkviolet','ls': 'dotted','where': 'post'} ,'p OPC LDSErgV':{'color':'olive' ,'lw':lwSmall-.5 ,'ms':matplotlib.rcParams['lines.markersize'] ,'marker':'x' ,'mec':'olive' ,'mfc':'olive' ,'where':'post'} ,'p OPC Src':{'color':SrcColorp ,'lw':0.05+2 ,'ms':matplotlib.rcParams['lines.markersize']/2 ,'marker':'D' ,'mec':SrcColorp ,'mfc':SrcColorQ ,'where':'post'} ,'p OPC Snk':{'color':SnkColorp ,'lw':0.05+2 ,'ms':matplotlib.rcParams['lines.markersize']/2 ,'marker':'D' ,'mec':SnkColorp ,'mfc':SnkColorQ ,'where':'post'} ,'Q OPC Src':{'color':SrcColorQ ,'lw':0.05+2 ,'ms':matplotlib.rcParams['lines.markersize']/2 ,'marker':'D' ,'mec':SrcColorQ ,'mfc':SrcColorp ,'where':'post'} ,'Q OPC Snk':{'color':SnkColorQ ,'lw':0.05+2 ,'ms':matplotlib.rcParams['lines.markersize']/2 ,'marker':'D' ,'mec':SnkColorQ ,'mfc':SnkColorp ,'where':'post'} } attrsDctLDS={ 'Seg_AL_S_Attrs':{'color':'blue','lw':3.,'where':'post'} ,'Druck_AL_S_Attrs':{'color':'blue','lw':3.,'ls':'dashed','where':'post'} ,'Seg_MZ_AV_Attrs':{'color':'orange','zorder':3,'where':'post'} ,'Druck_MZ_AV_Attrs':{'color':'orange','zorder':3,'ls':'dashed','where':'post'} ,'Seg_LR_AV_Attrs':{'color':'green','zorder':1,'where':'post'} ,'Druck_LR_AV_Attrs':{'color':'green','zorder':1,'ls':'dashed','where':'post'} ,'Seg_LP_AV_Attrs':{'color':'turquoise','zorder':0,'lw':1.50,'where':'post'} ,'Druck_LP_AV_Attrs':{'color':'turquoise','zorder':0,'lw':1.50,'ls':'dashed','where':'post'} ,'Seg_NG_AV_Attrs':{'color':'red','zorder':2,'where':'post'} ,'Druck_NG_AV_Attrs':{'color':'red','zorder':2,'ls':'dashed','where':'post'} ,'Seg_SB_S_Attrs':{'color':'black','alpha':.5,'where':'post'} ,'Druck_SB_S_Attrs':{'color':'black','ls':'dashed','alpha':.75,'where':'post','lw':1.0} ,'Seg_AC_AV_Attrs':{'color':'indigo','where':'post'} ,'Druck_AC_AV_Attrs':{'color':'indigo','ls':'dashed','where':'post'} ,'Seg_ACF_AV_Attrs':{'color':'blueviolet','where':'post','lw':1.0} ,'Druck_ACF_AV_Attrs':{'color':'blueviolet','ls':'dashed','where':'post','lw':1.0} ,'Seg_ACC_Limits_Attrs':{'color':'indigo','ls':linestyle_tuple[2][1]} # 'densely dotted' ,'Druck_ACC_Limits_Attrs':{'color':'indigo','ls':linestyle_tuple[8][1]} # 'densely dashdotted' ,'Seg_TIMER_AV_Attrs':{'color':'chartreuse','where':'post'} ,'Druck_TIMER_AV_Attrs':{'color':'chartreuse','ls':'dashed','where':'post'} ,'Seg_AM_AV_Attrs':{'color':'chocolate','where':'post'} ,'Druck_AM_AV_Attrs':{'color':'chocolate','ls':'dashed','where':'post'} # ,'Seg_DPDT_REF_Attrs':{'color':'violet','ls':linestyle_tuple[2][1]} # 'densely dotted' ,'Druck_DPDT_REF_Attrs':{'color':'violet','ls':linestyle_tuple[8][1]} # 'densely dashdotted' ,'Seg_DPDT_AV_Attrs':{'color':'fuchsia','where':'post','lw':2.0} ,'Druck_DPDT_AV_Attrs':{'color':'fuchsia','ls':'dashed','where':'post','lw':2.0} ,'Seg_QM16_AV_Attrs':{'color':'sandybrown','ls':linestyle_tuple[6][1],'where':'post','lw':1.0} # 'loosely dashdotted' ,'Druck_QM16_AV_Attrs':{'color':'sandybrown','ls':linestyle_tuple[10][1],'where':'post','lw':1.0} # 'loosely dashdotdotted' } pSIDEvents=re.compile('(?P<Prae>IMDI\.)?Objects\.(?P<colRegExMiddle>3S_FBG_ESCHIEBER|FBG_ESCHIEBER{1})\.(3S_)?(?P<colRegExSchieberID>[a-z,A-Z,0-9,_]+)\.(?P<colRegExEventID>(In\.ZUST|In\.LAEUFT|In\.LAEUFT_NICHT|In\.STOER|Out\.AUF|Out\.HALT|Out\.ZU)$)') # ausgewertet werden: colRegExSchieberID (um welchen Schieber geht es), colRegExMiddle (Befehl oder Zustand) und colRegExEventID (welcher Befehl bzw. Zustand) # die Befehle bzw. Zustaende (die Auspraegungen von colRegExEventID) muessen nachf. def. sein um den Marker (des Befehls bzw. des Zustandes) zu definieren eventCCmds={ 'Out.AUF':0 ,'Out.ZU':1 ,'Out.HALT':2} eventCStats={'In.LAEUFT':3 ,'In.LAEUFT_NICHT':4 ,'In.ZUST':5 ,'Out.AUF':6 ,'Out.ZU':7 ,'Out.HALT':8 ,'In.STOER':9} valRegExMiddleCmds='3S_FBG_ESCHIEBER' # colRegExMiddle-Auspraegung fuer Befehle (==> eventCCmds) LDSParameter=[ 'ACC_SLOWTRANSIENT' ,'ACC_TRANSIENT' ,'DESIGNFLOW' ,'DT' ,'FILTERWINDOW' #,'L_PERCENT' ,'L_PERCENT_STDY' ,'L_PERCENT_STRAN' ,'L_PERCENT_TRANS' ,'L_SHUTOFF' ,'L_SLOWTRANSIENT' ,'L_SLOWTRANSIENTQP' ,'L_STANDSTILL' ,'L_STANDSTILLQP' ,'L_TRANSIENT' ,'L_TRANSIENTQP' ,'L_TRANSIENTVBIGF' ,'L_TRANSIENTPDNTF' ,'MEAN' ,'NAME' ,'ORDER' ,'TIMER' ,'TTIMERTOALARM' ,'TIMERTOLISS' ,'TIMERTOLIST' ] LDSParameterDataD={ 'ACC_SLOWTRANSIENT':0.1 ,'ACC_TRANSIENT':0.8 ,'DESIGNFLOW':250. ,'DT':1 ,'FILTERWINDOW':180 #,'L_PERCENT':1.6 ,'L_PERCENT_STDY':1.6 ,'L_PERCENT_STRAN':1.6 ,'L_PERCENT_TRANS':1.6 ,'L_SHUTOFF':2. ,'L_SLOWTRANSIENT':4. ,'L_SLOWTRANSIENTQP':4. ,'L_STANDSTILL':2. ,'L_STANDSTILLQP':2. ,'L_TRANSIENT':10. ,'L_TRANSIENTQP':10. ,'L_TRANSIENTVBIGF':3. ,'L_TRANSIENTPDNTF':1.5 ,'MEAN':1 ,'ORDER':1 ,'TIMER':180 ,'TTIMERTOALARM':45 # TIMER/4 ,'TIMERTOLISS':180 ,'TIMERTOLIST':180 ,'NAME':'' } def fSEGNameFromPV_2(Beschr): # fSEGNameFromSWVTBeschr # 2,3,4,5 if Beschr in ['',None]: return None m=re.search(Lx.pID,Beschr) if m == None: return Beschr return m.group('C2')+'_'+m.group('C3')+'_'+m.group('C4')+'_'+m.group('C5') def fSEGNameFromPV_3(PV): # fSEGNameFromPV # ... m=re.search(Lx.pID,PV) return m.group('C3')+'_'+m.group('C4')+'_'+m.group('C5')+m.group('C6') def fSEGNameFromPV_3m(PV): # fSEGNameFromPV # ... m=re.search(Lx.pID,PV) #print("C4: {:s} C6: {:s}".format(m.group('C4'),m.group('C6'))) if m.group('C4')=='AAD' and m.group('C6')=='_OHN': return m.group('C3')+'_'+m.group('C4')+'_'+m.group('C5')+'_OHV1' elif m.group('C4')=='OHN' and m.group('C6')=='_NGD': return m.group('C3')+'_'+'OHV2'+'_'+m.group('C5')+m.group('C6') else: return m.group('C3')+'_'+m.group('C4')+'_'+m.group('C5')+m.group('C6') # Ableitung eines DIVPipelineNamens von PV def fDIVNameFromPV(PV): m=re.search(Lx.pID,PV) return m.group('C2')+'-'+m.group('C4') # Ableitung eines DIVPipelineNamens von SEGName def fDIVNameFromSEGName(SEGName): if pd.isnull(SEGName): return None # dfSegsNodesNDataDpkt['DIVPipelineName']=dfSegsNodesNDataDpkt['SEGName'].apply(lambda x: re.search('(\d+)_(\w+)_(\w+)_(\w+)',x).group(1)+'_'+re.search('(\d+)_(\w+)_(\w+)_(\w+)',x).group(3) ) m=re.search('(\d+)_(\w+)_(\w+)_(\w+)',SEGName) if m == None: return SEGName return m.group(1)+'_'+m.group(3) #def getNamesFromOPCITEM_ID(dfSegsNodesNDataDpkt # ,OPCITEM_ID): # """ # Returns tuple (DIVPipelineName,SEGName) from OPCITEM_ID PH # """ # df=dfSegsNodesNDataDpkt[dfSegsNodesNDataDpkt['OPCITEM_ID']==OPCITEM_ID] # if not df.empty: # return (df['DIVPipelineName'].iloc[0],df['SEGName'].iloc[0]) def fGetBaseIDFromResID( ID='Objects.3S_XXX_DRUCK.3S_6_BNV_01_PTI_01.In.MW.value' ): """ Returns 'Objects.3S_XXX_DRUCK.3S_6_BNV_01_PTI_01.In.' funktioniert im Prinzip fuer SEG- und Druck-Ergs: jede Erg-PV eines Vektors liefert die Basis gueltig fuer alle Erg-PVs des Vektors d.h. die Erg-PVs eines Vektors unterscheiden sich nur hinten siehe auch fGetSEGBaseIDFromSEGName """ if pd.isnull(ID): return None m=re.search(Lx.pID,ID) if m == None: return None try: base=m.group('A')+'.'+m.group('B')\ +'.'+m.group('C1')\ +'_'+m.group('C2')\ +'_'+m.group('C3')\ +'_'+m.group('C4')\ +'_'+m.group('C5')\ +m.group('C6') #print(m.groups()) #print(m.groupdict()) if 'C7' in m.groupdict().keys(): if m.group('C7') != None: base=base+m.group('C7') base=base+'.'+m.group('D')\ +'.' #print(base) except: base=m.group(0)+' (Fehler in fGetBaseIDFromResID)' return base def fGetSEGBaseIDFromSEGName( SEGName='6_AAD_41_OHV1' ): """ Returns 'Objects.3S_FBG_SEG_INFO.3S_L_'+SEGName+'.In.' In some cases SEGName is manipulated ... siehe auch fGetBaseIDFromResID """ if SEGName == '6_AAD_41_OHV1': x='6_AAD_41_OHN' elif SEGName == '6_OHV2_41_NGD': x='6_OHN_41_NGD' else: x=SEGName return 'Objects.3S_FBG_SEG_INFO.3S_L_'+x+'.In.' def getNamesFromSEGResIDBase(dfSegsNodesNDataDpkt ,SEGResIDBase): """ Returns tuple (DIVPipelineName,SEGName) from SEGResIDBase """ df=dfSegsNodesNDataDpkt[dfSegsNodesNDataDpkt['SEGResIDBase']==SEGResIDBase] if not df.empty: return (df['DIVPipelineName'].iloc[0],df['SEGName'].iloc[0]) def getNamesFromDruckResIDBase(dfSegsNodesNDataDpkt ,DruckResIDBase): """ Returns tuple (DIVPipelineName,SEGName,SEGResIDBase,SEGOnlyInLDSPara) from DruckResIDBase """ df=dfSegsNodesNDataDpkt[dfSegsNodesNDataDpkt['DruckResIDBase']==DruckResIDBase] if not df.empty: #return (df['DIVPipelineName'].iloc[0],df['SEGName'].iloc[0],df['SEGResIDBase'].iloc[0]) tupleLst=[] for index,row in df.iterrows(): tupleItem=(row['DIVPipelineName'],row['SEGName'],row['SEGResIDBase'],row['SEGOnlyInLDSPara']) tupleLst.append(tupleItem) return tupleLst else: return [] def fGetErgIDsFromBaseID( baseID='Objects.3S_FBG_SEG_INFO.3S_L_6_BUV_01_BUA.In.' ,dfODI=pd.DataFrame() # df mit ODI Parametrierungsdaten ,strSep=' ' ,patternPat='^IMDI.' # ,pattern=True # nur ergIDs, fuer die 2ndPatternPat zutrifft liefern ): """ returns string mit strSep getrennten IDs aus dfODI, welche baseID enthalten (und bei pattern WAHR patternPat matchen) baseID (und group(0) von patternPat bei pattern WAHR) sind in den IDs entfernt """ if baseID in [None,'']: return None df=dfODI[dfODI.index.str.contains(baseID)] if df.empty: return None if pattern: ergIDs=''.join([e.replace(baseID,'').replace(re.search(patternPat,e).group(0),'')+' ' for e in df.index if re.search(patternPat,e) != None]) else: ergIDs=''.join([e.replace(baseID,'')+' ' for e in df.index if re.search(patternPat,e) == None]) return ergIDs def dfSegsNodesNDataDpkt( VersionsDir=r"C:\3s\Projekte\Projekt\04 - Versionen\Version82.3" ,Model=r"MDBDOC\FBG.mdb" # a Access Model ,am=None # a Access Model already processed ,SEGsDefPattern='(?P<SEG_Ki>\S+)~(?P<SEG_Kk>\S+)$' # RSLW-Beschreibung: liefert die Knotennamen der Segmentdefinition () ,RIDefPattern='(?P<Prae>\S+)\.(?P<Post>RICHT.S)$' # SWVT-Beschreibung (RICHT-DP): liefert u.a. SEGName ,fSEGNameFromPV_2=fSEGNameFromPV_2 # Funktion, die von SWVT-Beschreibung (RICHT-DP) u.a. SEGName liefert ,fGetBaseIDFromResID=fGetBaseIDFromResID # Funktion, die von OPCITEM-ID des PH-Kanals eines KNOTens den Wortstamm der Knotenergebnisse liefert ,fGetSEGBaseIDFromSEGName=fGetSEGBaseIDFromSEGName # Funktion, die aus SEGName den Wortstamm der Segmentergebnisse liefert ,LDSPara=r"App LDS\Modelle\WDFBG\B1\V0\BZ1\LDS_Para.xml" ,LDSParaPT=r"App LDS\SirOPC\AppLDS_DPDTParams.csv" ,ODI=r"App LDS\SirOPC\AppLDS_ODI.csv" ,LDSParameter=LDSParameter ,LDSParameterDataD=LDSParameterDataD ): """ alle Segmente mit Pfaddaten (Kantenzuege) mit Kanten- und Knotendaten sowie Parametrierungsdaten returns df: DIVPipelineName SEGName SEGNodes (Ki~Kk; Schluessel in LDSPara) SEGOnlyInLDSPara NODEsRef NODEsRef_max NODEsSEGLfdNr NODEsSEGLfdNrType NODEsName OBJTYPE ZKOR Blockname ATTRTYPE (PH) CLIENT_ID OPCITEM_ID NAME (der DPKT-Gruppe) DruckResIDBase SEGResIDBase SEGResIDs SEGResIDsIMDI DruckResIDs DruckResIDsIMDI NODEsSEGDruckErgLfdNr # LDSPara ACC_SLOWTRANSIENT ACC_TRANSIENT DESIGNFLOW DT FILTERWINDOW L_PERCENT_STDY L_PERCENT_STRAN L_PERCENT_TRANS L_SHUTOFF L_SLOWTRANSIENT L_SLOWTRANSIENTQP L_STANDSTILL L_STANDSTILLQP L_TRANSIENT L_TRANSIENTPDNTF L_TRANSIENTQP L_TRANSIENTVBIGF MEAN ORDER TIMER TIMERTOLISS TIMERTOLIST TTIMERTOALARM # LDSParaPT #ID pMin DT_Vorhaltemass TTimer_PMin Faktor_PMin MaxL_PMin pMinMlc pMinMlcMinSEG pMinMlcMaxSEG """ logStr = "{0:s}.{1:s}: ".format(__name__, sys._getframe().f_code.co_name) logger.debug("{0:s}{1:s}".format(logStr,'Start.')) dfSegsNodesNDataDpkt=
pd.DataFrame()
pandas.DataFrame
#! /user/bin/env python3 import argparse import xlrd from datetime import datetime import pandas as pd import os import shutil import configparser config = configparser.ConfigParser() config.read("config.ini") unixFilesPath = os.getcwd() + config["FilePaths"]["unixFilesPath"] unixConvertedPath = os.getcwd() + config["FilePaths"]["unixConvertedPath"] windowsFilesPath = os.getcwd() + config["FilePaths"]["windowsFilesPath"] windowsConvertedPath = os.getcwd() + config["FilePaths"]["windowsConvertedPath"] user = config["User"]["username"] homeBankCols = config["HomeBank"]["homeBankCols"].split(sep=",") amexHeaders = config["CSVHeaders"]["amexHeaders"].split(sep=",") boaCAHeaders = config["CSVHeaders"]["boaCAHeaders"].split(sep=",") boaCCHeaders = config["CSVHeaders"]["boaCCHeaders"].split(sep=",") earnestHeaders = config["CSVHeaders"]["earnestHeaders"].split(sep=",") vanguardRothHeaders = config["CSVHeaders"]["vanguardRothHeaders"].split(sep=",") vanguard401KHeaders = config["CSVHeaders"]["vanguard401KHeaders"].split(sep=",") venmoHeaders = config["CSVHeaders"]["venmoHeaders"].split(sep=",") paypalHeaders = config["CSVHeaders"]["paypalHeaders"].split(sep=",") def amexCCConversion(filename): try: inputDataDict = pd.read_csv(filepath_or_buffer=filename, header=0) if all(inputDataDict.columns == amexHeaders): inputDataDict = inputDataDict.to_dict("records") except: raise Exception data = [] for row in inputDataDict: if pd.notna: data.append([row["Date"], None, None, row["Description"], None, -1*row["Amount"], None, None]) outputDataFrame = pd.DataFrame(data=data, columns=homeBankCols) outputDataFrame.to_csv( "convertedfiles/amexHomeBank.csv", index=False, sep=";") def boaCAConversion(filename): try: inputDataDict = pd.read_csv(filepath_or_buffer=filename, header=5) if all(inputDataDict.columns == boaCAHeaders): inputDataDict = inputDataDict.to_dict("records") except: raise Exception data = [] for row in inputDataDict: data.append([row["Date"], None, None, row["Description"], None, row["Amount"], None, None]) outputDataFrame = pd.DataFrame(data=data, columns=homeBankCols) outputDataFrame.to_csv( "convertedfiles/boaCAHomeBank.csv", index=False, sep=";") def boaCCConversion(filename): try: inputDataDict = pd.read_csv(filepath_or_buffer=filename, header=0) if all(inputDataDict.columns == boaCCHeaders): inputDataDict = inputDataDict.to_dict("records") except: raise Exception data = [] for row in inputDataDict: data.append([row["Posted Date"], None, row["Reference Number"], row["Payee"], None, row["Amount"], None, None]) outputDataFrame = pd.DataFrame(data=data, columns=homeBankCols) outputDataFrame.to_csv( "convertedfiles/boaCCHomeBank.csv", index=False, sep=";") def earnestConversion(filename): inputDataDict = pd.read_html(io=filename)[0] try: if all(inputDataDict.columns == earnestHeaders): inputDataDict = pd.read_html(io=filename)[0].to_dict("records") except: raise Exception data = [] for row in inputDataDict: # Just the loan data.append([row["Date"], None, None, user, None, row["Total"][2:], "Loan Payment", None]) # Just the interest data.append([row["Date"], None, None, "Earnest", None, "-" + row["Interest"][2:], "Loan Interest", None]) outputDataFrame = pd.DataFrame(data=data, columns=homeBankCols) outputDataFrame.to_csv( "convertedfiles/earnestHomeBank.csv", index=False, sep=";") def vanguardRothConversion(filename): try: inputDataDict = pd.read_csv(filepath_or_buffer=filename,header=3) inputDataDict = inputDataDict.loc[:, ~inputDataDict.columns.str.contains('^Unnamed')] if all(inputDataDict.columns == vanguardRothHeaders): inputDataDict = inputDataDict.to_dict("records") except: raise Exception data = [] for row in inputDataDict: if vanguardRothLogic(row["Transaction Type"]): data.append([row["Settlement Date"], 0, row["Transaction Description"], "Vanguard", None, row["Principal Amount"], None, None]) outputDataFrame = pd.DataFrame(data=data, columns=homeBankCols) outputDataFrame.to_csv( "convertedfiles/vanguardRothHomeBank.csv", index=False, sep=";") def vanguardRothLogic(rowType): if rowType == "Dividend": return True elif rowType == "Contribution": return True elif rowType == "Capital gain (LT)": return True elif rowType == "Capital gain (ST)": return True else: return False def vanguard401KConversion(filename): try: inputDataDict = pd.read_csv(filepath_or_buffer=filename,header=16) inputDataDict = inputDataDict.loc[:, ~inputDataDict.columns.str.contains('^Unnamed')] if all(inputDataDict.columns == vanguard401KHeaders): inputDataDict = inputDataDict.to_dict("records") except: raise Exception data = [] for row in inputDataDict: if vanguard401KLogic(row["Transaction Description"]): data.append([ row["Run Date"], None, row["Transaction Description"], "Vanguard", None, row["Dollar Amount"], None, row["Investment Name"] ]) outputDataFrame = pd.DataFrame(data=data, columns=homeBankCols) outputDataFrame.to_csv( "convertedfiles/vanguard401KHomeBank.csv", index=False, sep=";") def vanguard401KLogic(rowType): if rowType == "Plan Contribution": return True elif rowType == "Dividends on Equity Investments": return True else: return False def venmoConversion(filename): try: inputDataDict = pd.read_csv(filepath_or_buffer=filename,header=0) inputDataDict["Datetime"] =
pd.to_datetime(inputDataDict["Datetime"],format="%Y-%m-%dT%H:%M:%S")
pandas.to_datetime
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Keras implementation of Dilated Causal Convolutional Neural Network for Time Series Predictions based on the following sources: [1] <NAME> et al., “Wavenet: A generative model for raw audio,” arXiv preprint arXiv:1609.03499, 2016. [2] <NAME>, <NAME>, and <NAME>, “Conditional Time Series Forecasting with Convolutional Neural Networks,” arXiv:1703.04691 [stat], Mar. 2017. Initial 1D convolutional code structure based on: https://gist.github.com/jkleint/1d878d0401b28b281eb75016ed29f2ee Author: <NAME> V0 Date: March 31, 2018 V1 Data: September 12, 2018 - updated Keras merge function to Add for Keras 2.2.2 tensorflow==1.10.1 Keras==2.2.2 numpy==1.14.5 """ from __future__ import print_function, division import numpy as np import pandas as pd import math import matplotlib.pyplot as plt from keras.layers import Conv1D, Input, Add, Activation, Dropout from keras.models import Sequential, Model from keras.regularizers import l2 from keras.initializers import TruncatedNormal from keras.layers.advanced_activations import LeakyReLU, ELU from keras import optimizers from tqdm import trange def DC_CNN_Block(nb_filter, filter_length, dilation, l2_layer_reg): def f(input_): residual = input_ layer_out = Conv1D(filters=nb_filter, kernel_size=filter_length, dilation_rate=dilation, activation='linear', padding='causal', use_bias=False, kernel_initializer=TruncatedNormal(mean=0.0, stddev=0.05, seed=42), kernel_regularizer=l2(l2_layer_reg))(input_) layer_out = Activation('selu')(layer_out) skip_out = Conv1D(1,1, activation='linear', use_bias=False, kernel_initializer=TruncatedNormal(mean=0.0, stddev=0.05, seed=42), kernel_regularizer=l2(l2_layer_reg))(layer_out) network_in = Conv1D(1,1, activation='linear', use_bias=False, kernel_initializer=TruncatedNormal(mean=0.0, stddev=0.05, seed=42), kernel_regularizer=l2(l2_layer_reg))(layer_out) network_out = Add()([residual, network_in]) return network_out, skip_out return f def DC_CNN_Model(length): input = Input(shape=(length,1)) l1a, l1b = DC_CNN_Block(32,2,1,0.001)(input) l2a, l2b = DC_CNN_Block(32,2,2,0.001)(l1a) l3a, l3b = DC_CNN_Block(32,2,4,0.001)(l2a) l4a, l4b = DC_CNN_Block(32,2,8,0.001)(l3a) l5a, l5b = DC_CNN_Block(32,2,16,0.001)(l4a) l6a, l6b = DC_CNN_Block(32,2,32,0.001)(l5a) l6b = Dropout(0.8)(l6b) #dropout used to limit influence of earlier data l7a, l7b = DC_CNN_Block(32,2,64,0.001)(l6a) l7b = Dropout(0.8)(l7b) #dropout used to limit influence of earlier data l8 = Add()([l1b, l2b, l3b, l4b, l5b, l6b, l7b]) l9 = Activation('relu')(l8) l21 = Conv1D(1,1, activation='linear', use_bias=False, kernel_initializer=TruncatedNormal(mean=0.0, stddev=0.05, seed=42), kernel_regularizer=l2(0.001))(l9) model = Model(input=input, output=l21) adam = optimizers.Adam(lr=0.00075, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False) model.compile(loss='mae', optimizer=adam, metrics=['mse']) return model def evaluate_timeseries(timeseries, predict_size): # timeseries input is 1-D numpy array # forecast_size is the forecast horizon timeseries = timeseries[~
pd.isna(timeseries)
pandas.isna
import folium.plugins as plugins import pandas as pd import folium #siteList = ['1418A', '3015A', '3133A', '3014A', '1419A'] siteList = [] siteRecord = {} df =
pd.DataFrame()
pandas.DataFrame
import pandas as pd import numpy as np def create_table(col_names, data_array, type_array): new_data_array = data_array.copy() string_to_type = {'int' : int, 'string' : str, 'double' : float} for j in range(0, len(col_names)): for i in range(0, len(data_array)): if type_array[j] != 'string': if data_array[i][j] == None: new_data_array[i][j] = np.nan else: new_data_array[i][j] = string_to_type[type_array[j]](data_array[i][j]) else: if data_array[i][j] == None: new_data_array[i][j] = '' out_table =
pd.DataFrame(new_data_array, columns=col_names)
pandas.DataFrame
# -*- coding: utf-8 -*- import re import warnings from datetime import timedelta from itertools import product import pytest import numpy as np import pandas as pd from pandas import (CategoricalIndex, DataFrame, Index, MultiIndex, compat, date_range, period_range) from pandas.compat import PY3, long, lrange, lzip, range, u, PYPY from pandas.errors import PerformanceWarning, UnsortedIndexError from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.indexes.base import InvalidIndexError from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike from pandas._libs.tslib import Timestamp import pandas.util.testing as tm from pandas.util.testing import assert_almost_equal, assert_copy from .common import Base class TestMultiIndex(Base): _holder = MultiIndex _compat_props = ['shape', 'ndim', 'size'] def setup_method(self, method): major_axis = Index(['foo', 'bar', 'baz', 'qux']) minor_axis = Index(['one', 'two']) major_labels = np.array([0, 0, 1, 2, 3, 3]) minor_labels = np.array([0, 1, 0, 1, 0, 1]) self.index_names = ['first', 'second'] self.indices = dict(index=MultiIndex(levels=[major_axis, minor_axis], labels=[major_labels, minor_labels ], names=self.index_names, verify_integrity=False)) self.setup_indices() def create_index(self): return self.index def test_can_hold_identifiers(self): idx = self.create_index() key = idx[0] assert idx._can_hold_identifiers_and_holds_name(key) is True def test_boolean_context_compat2(self): # boolean context compat # GH7897 i1 = MultiIndex.from_tuples([('A', 1), ('A', 2)]) i2 = MultiIndex.from_tuples([('A', 1), ('A', 3)]) common = i1.intersection(i2) def f(): if common: pass tm.assert_raises_regex(ValueError, 'The truth value of a', f) def test_labels_dtypes(self): # GH 8456 i = MultiIndex.from_tuples([('A', 1), ('A', 2)]) assert i.labels[0].dtype == 'int8' assert i.labels[1].dtype == 'int8' i = MultiIndex.from_product([['a'], range(40)]) assert i.labels[1].dtype == 'int8' i = MultiIndex.from_product([['a'], range(400)]) assert i.labels[1].dtype == 'int16' i = MultiIndex.from_product([['a'], range(40000)]) assert i.labels[1].dtype == 'int32' i = pd.MultiIndex.from_product([['a'], range(1000)]) assert (i.labels[0] >= 0).all() assert (i.labels[1] >= 0).all() def test_where(self): i = MultiIndex.from_tuples([('A', 1), ('A', 2)]) def f(): i.where(True) pytest.raises(NotImplementedError, f) def test_where_array_like(self): i = MultiIndex.from_tuples([('A', 1), ('A', 2)]) klasses = [list, tuple, np.array, pd.Series] cond = [False, True] for klass in klasses: def f(): return i.where(klass(cond)) pytest.raises(NotImplementedError, f) def test_repeat(self): reps = 2 numbers = [1, 2, 3] names = np.array(['foo', 'bar']) m = MultiIndex.from_product([ numbers, names], names=names) expected = MultiIndex.from_product([ numbers, names.repeat(reps)], names=names) tm.assert_index_equal(m.repeat(reps), expected) with tm.assert_produces_warning(FutureWarning): result = m.repeat(n=reps) tm.assert_index_equal(result, expected) def test_numpy_repeat(self): reps = 2 numbers = [1, 2, 3] names = np.array(['foo', 'bar']) m = MultiIndex.from_product([ numbers, names], names=names) expected = MultiIndex.from_product([ numbers, names.repeat(reps)], names=names) tm.assert_index_equal(np.repeat(m, reps), expected) msg = "the 'axis' parameter is not supported" tm.assert_raises_regex( ValueError, msg, np.repeat, m, reps, axis=1) def test_set_name_methods(self): # so long as these are synonyms, we don't need to test set_names assert self.index.rename == self.index.set_names new_names = [name + "SUFFIX" for name in self.index_names] ind = self.index.set_names(new_names) assert self.index.names == self.index_names assert ind.names == new_names with tm.assert_raises_regex(ValueError, "^Length"): ind.set_names(new_names + new_names) new_names2 = [name + "SUFFIX2" for name in new_names] res = ind.set_names(new_names2, inplace=True) assert res is None assert ind.names == new_names2 # set names for specific level (# GH7792) ind = self.index.set_names(new_names[0], level=0) assert self.index.names == self.index_names assert ind.names == [new_names[0], self.index_names[1]] res = ind.set_names(new_names2[0], level=0, inplace=True) assert res is None assert ind.names == [new_names2[0], self.index_names[1]] # set names for multiple levels ind = self.index.set_names(new_names, level=[0, 1]) assert self.index.names == self.index_names assert ind.names == new_names res = ind.set_names(new_names2, level=[0, 1], inplace=True) assert res is None assert ind.names == new_names2 @pytest.mark.parametrize('inplace', [True, False]) def test_set_names_with_nlevel_1(self, inplace): # GH 21149 # Ensure that .set_names for MultiIndex with # nlevels == 1 does not raise any errors expected = pd.MultiIndex(levels=[[0, 1]], labels=[[0, 1]], names=['first']) m = pd.MultiIndex.from_product([[0, 1]]) result = m.set_names('first', level=0, inplace=inplace) if inplace: result = m tm.assert_index_equal(result, expected) def test_set_levels_labels_directly(self): # setting levels/labels directly raises AttributeError levels = self.index.levels new_levels = [[lev + 'a' for lev in level] for level in levels] labels = self.index.labels major_labels, minor_labels = labels major_labels = [(x + 1) % 3 for x in major_labels] minor_labels = [(x + 1) % 1 for x in minor_labels] new_labels = [major_labels, minor_labels] with pytest.raises(AttributeError): self.index.levels = new_levels with pytest.raises(AttributeError): self.index.labels = new_labels def test_set_levels(self): # side note - you probably wouldn't want to use levels and labels # directly like this - but it is possible. levels = self.index.levels new_levels = [[lev + 'a' for lev in level] for level in levels] def assert_matching(actual, expected, check_dtype=False): # avoid specifying internal representation # as much as possible assert len(actual) == len(expected) for act, exp in zip(actual, expected): act = np.asarray(act) exp = np.asarray(exp) tm.assert_numpy_array_equal(act, exp, check_dtype=check_dtype) # level changing [w/o mutation] ind2 = self.index.set_levels(new_levels) assert_matching(ind2.levels, new_levels) assert_matching(self.index.levels, levels) # level changing [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_levels(new_levels, inplace=True) assert inplace_return is None assert_matching(ind2.levels, new_levels) # level changing specific level [w/o mutation] ind2 = self.index.set_levels(new_levels[0], level=0) assert_matching(ind2.levels, [new_levels[0], levels[1]]) assert_matching(self.index.levels, levels) ind2 = self.index.set_levels(new_levels[1], level=1) assert_matching(ind2.levels, [levels[0], new_levels[1]]) assert_matching(self.index.levels, levels) # level changing multiple levels [w/o mutation] ind2 = self.index.set_levels(new_levels, level=[0, 1]) assert_matching(ind2.levels, new_levels) assert_matching(self.index.levels, levels) # level changing specific level [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_levels(new_levels[0], level=0, inplace=True) assert inplace_return is None assert_matching(ind2.levels, [new_levels[0], levels[1]]) assert_matching(self.index.levels, levels) ind2 = self.index.copy() inplace_return = ind2.set_levels(new_levels[1], level=1, inplace=True) assert inplace_return is None assert_matching(ind2.levels, [levels[0], new_levels[1]]) assert_matching(self.index.levels, levels) # level changing multiple levels [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_levels(new_levels, level=[0, 1], inplace=True) assert inplace_return is None assert_matching(ind2.levels, new_levels) assert_matching(self.index.levels, levels) # illegal level changing should not change levels # GH 13754 original_index = self.index.copy() for inplace in [True, False]: with tm.assert_raises_regex(ValueError, "^On"): self.index.set_levels(['c'], level=0, inplace=inplace) assert_matching(self.index.levels, original_index.levels, check_dtype=True) with tm.assert_raises_regex(ValueError, "^On"): self.index.set_labels([0, 1, 2, 3, 4, 5], level=0, inplace=inplace) assert_matching(self.index.labels, original_index.labels, check_dtype=True) with tm.assert_raises_regex(TypeError, "^Levels"): self.index.set_levels('c', level=0, inplace=inplace) assert_matching(self.index.levels, original_index.levels, check_dtype=True) with tm.assert_raises_regex(TypeError, "^Labels"): self.index.set_labels(1, level=0, inplace=inplace) assert_matching(self.index.labels, original_index.labels, check_dtype=True) def test_set_labels(self): # side note - you probably wouldn't want to use levels and labels # directly like this - but it is possible. labels = self.index.labels major_labels, minor_labels = labels major_labels = [(x + 1) % 3 for x in major_labels] minor_labels = [(x + 1) % 1 for x in minor_labels] new_labels = [major_labels, minor_labels] def assert_matching(actual, expected): # avoid specifying internal representation # as much as possible assert len(actual) == len(expected) for act, exp in zip(actual, expected): act = np.asarray(act) exp = np.asarray(exp, dtype=np.int8) tm.assert_numpy_array_equal(act, exp) # label changing [w/o mutation] ind2 = self.index.set_labels(new_labels) assert_matching(ind2.labels, new_labels) assert_matching(self.index.labels, labels) # label changing [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_labels(new_labels, inplace=True) assert inplace_return is None assert_matching(ind2.labels, new_labels) # label changing specific level [w/o mutation] ind2 = self.index.set_labels(new_labels[0], level=0) assert_matching(ind2.labels, [new_labels[0], labels[1]]) assert_matching(self.index.labels, labels) ind2 = self.index.set_labels(new_labels[1], level=1) assert_matching(ind2.labels, [labels[0], new_labels[1]]) assert_matching(self.index.labels, labels) # label changing multiple levels [w/o mutation] ind2 = self.index.set_labels(new_labels, level=[0, 1]) assert_matching(ind2.labels, new_labels) assert_matching(self.index.labels, labels) # label changing specific level [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_labels(new_labels[0], level=0, inplace=True) assert inplace_return is None assert_matching(ind2.labels, [new_labels[0], labels[1]]) assert_matching(self.index.labels, labels) ind2 = self.index.copy() inplace_return = ind2.set_labels(new_labels[1], level=1, inplace=True) assert inplace_return is None assert_matching(ind2.labels, [labels[0], new_labels[1]]) assert_matching(self.index.labels, labels) # label changing multiple levels [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_labels(new_labels, level=[0, 1], inplace=True) assert inplace_return is None assert_matching(ind2.labels, new_labels) assert_matching(self.index.labels, labels) # label changing for levels of different magnitude of categories ind = pd.MultiIndex.from_tuples([(0, i) for i in range(130)]) new_labels = range(129, -1, -1) expected = pd.MultiIndex.from_tuples( [(0, i) for i in new_labels]) # [w/o mutation] result = ind.set_labels(labels=new_labels, level=1) assert result.equals(expected) # [w/ mutation] result = ind.copy() result.set_labels(labels=new_labels, level=1, inplace=True) assert result.equals(expected) def test_set_levels_labels_names_bad_input(self): levels, labels = self.index.levels, self.index.labels names = self.index.names with tm.assert_raises_regex(ValueError, 'Length of levels'): self.index.set_levels([levels[0]]) with tm.assert_raises_regex(ValueError, 'Length of labels'): self.index.set_labels([labels[0]]) with tm.assert_raises_regex(ValueError, 'Length of names'): self.index.set_names([names[0]]) # shouldn't scalar data error, instead should demand list-like with tm.assert_raises_regex(TypeError, 'list of lists-like'): self.index.set_levels(levels[0]) # shouldn't scalar data error, instead should demand list-like with tm.assert_raises_regex(TypeError, 'list of lists-like'): self.index.set_labels(labels[0]) # shouldn't scalar data error, instead should demand list-like with tm.assert_raises_regex(TypeError, 'list-like'): self.index.set_names(names[0]) # should have equal lengths with tm.assert_raises_regex(TypeError, 'list of lists-like'): self.index.set_levels(levels[0], level=[0, 1]) with tm.assert_raises_regex(TypeError, 'list-like'): self.index.set_levels(levels, level=0) # should have equal lengths with tm.assert_raises_regex(TypeError, 'list of lists-like'): self.index.set_labels(labels[0], level=[0, 1]) with tm.assert_raises_regex(TypeError, 'list-like'): self.index.set_labels(labels, level=0) # should have equal lengths with tm.assert_raises_regex(ValueError, 'Length of names'): self.index.set_names(names[0], level=[0, 1]) with tm.assert_raises_regex(TypeError, 'string'): self.index.set_names(names, level=0) def test_set_levels_categorical(self): # GH13854 index = MultiIndex.from_arrays([list("xyzx"), [0, 1, 2, 3]]) for ordered in [False, True]: cidx = CategoricalIndex(list("bac"), ordered=ordered) result = index.set_levels(cidx, 0) expected = MultiIndex(levels=[cidx, [0, 1, 2, 3]], labels=index.labels) tm.assert_index_equal(result, expected) result_lvl = result.get_level_values(0) expected_lvl = CategoricalIndex(list("bacb"), categories=cidx.categories, ordered=cidx.ordered) tm.assert_index_equal(result_lvl, expected_lvl) def test_metadata_immutable(self): levels, labels = self.index.levels, self.index.labels # shouldn't be able to set at either the top level or base level mutable_regex = re.compile('does not support mutable operations') with tm.assert_raises_regex(TypeError, mutable_regex): levels[0] = levels[0] with tm.assert_raises_regex(TypeError, mutable_regex): levels[0][0] = levels[0][0] # ditto for labels with tm.assert_raises_regex(TypeError, mutable_regex): labels[0] = labels[0] with tm.assert_raises_regex(TypeError, mutable_regex): labels[0][0] = labels[0][0] # and for names names = self.index.names with tm.assert_raises_regex(TypeError, mutable_regex): names[0] = names[0] def test_inplace_mutation_resets_values(self): levels = [['a', 'b', 'c'], [4]] levels2 = [[1, 2, 3], ['a']] labels = [[0, 1, 0, 2, 2, 0], [0, 0, 0, 0, 0, 0]] mi1 = MultiIndex(levels=levels, labels=labels) mi2 = MultiIndex(levels=levels2, labels=labels) vals = mi1.values.copy() vals2 = mi2.values.copy() assert mi1._tuples is not None # Make sure level setting works new_vals = mi1.set_levels(levels2).values tm.assert_almost_equal(vals2, new_vals) # Non-inplace doesn't kill _tuples [implementation detail] tm.assert_almost_equal(mi1._tuples, vals) # ...and values is still same too tm.assert_almost_equal(mi1.values, vals) # Inplace should kill _tuples mi1.set_levels(levels2, inplace=True) tm.assert_almost_equal(mi1.values, vals2) # Make sure label setting works too labels2 = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] exp_values = np.empty((6,), dtype=object) exp_values[:] = [(long(1), 'a')] * 6 # Must be 1d array of tuples assert exp_values.shape == (6,) new_values = mi2.set_labels(labels2).values # Not inplace shouldn't change tm.assert_almost_equal(mi2._tuples, vals2) # Should have correct values tm.assert_almost_equal(exp_values, new_values) # ...and again setting inplace should kill _tuples, etc mi2.set_labels(labels2, inplace=True) tm.assert_almost_equal(mi2.values, new_values) def test_copy_in_constructor(self): levels = np.array(["a", "b", "c"]) labels = np.array([1, 1, 2, 0, 0, 1, 1]) val = labels[0] mi = MultiIndex(levels=[levels, levels], labels=[labels, labels], copy=True) assert mi.labels[0][0] == val labels[0] = 15 assert mi.labels[0][0] == val val = levels[0] levels[0] = "PANDA" assert mi.levels[0][0] == val def test_set_value_keeps_names(self): # motivating example from #3742 lev1 = ['hans', 'hans', 'hans', 'grethe', 'grethe', 'grethe'] lev2 = ['1', '2', '3'] * 2 idx = pd.MultiIndex.from_arrays([lev1, lev2], names=['Name', 'Number']) df = pd.DataFrame( np.random.randn(6, 4), columns=['one', 'two', 'three', 'four'], index=idx) df = df.sort_index() assert df._is_copy is None assert df.index.names == ('Name', 'Number') df.at[('grethe', '4'), 'one'] = 99.34 assert df._is_copy is None assert df.index.names == ('Name', 'Number') def test_copy_names(self): # Check that adding a "names" parameter to the copy is honored # GH14302 multi_idx = pd.Index([(1, 2), (3, 4)], names=['MyName1', 'MyName2']) multi_idx1 = multi_idx.copy() assert multi_idx.equals(multi_idx1) assert multi_idx.names == ['MyName1', 'MyName2'] assert multi_idx1.names == ['MyName1', 'MyName2'] multi_idx2 = multi_idx.copy(names=['NewName1', 'NewName2']) assert multi_idx.equals(multi_idx2) assert multi_idx.names == ['MyName1', 'MyName2'] assert multi_idx2.names == ['NewName1', 'NewName2'] multi_idx3 = multi_idx.copy(name=['NewName1', 'NewName2']) assert multi_idx.equals(multi_idx3) assert multi_idx.names == ['MyName1', 'MyName2'] assert multi_idx3.names == ['NewName1', 'NewName2'] def test_names(self): # names are assigned in setup names = self.index_names level_names = [level.name for level in self.index.levels] assert names == level_names # setting bad names on existing index = self.index tm.assert_raises_regex(ValueError, "^Length of names", setattr, index, "names", list(index.names) + ["third"]) tm.assert_raises_regex(ValueError, "^Length of names", setattr, index, "names", []) # initializing with bad names (should always be equivalent) major_axis, minor_axis = self.index.levels major_labels, minor_labels = self.index.labels tm.assert_raises_regex(ValueError, "^Length of names", MultiIndex, levels=[major_axis, minor_axis], labels=[major_labels, minor_labels], names=['first']) tm.assert_raises_regex(ValueError, "^Length of names", MultiIndex, levels=[major_axis, minor_axis], labels=[major_labels, minor_labels], names=['first', 'second', 'third']) # names are assigned index.names = ["a", "b"] ind_names = list(index.names) level_names = [level.name for level in index.levels] assert ind_names == level_names def test_astype(self): expected = self.index.copy() actual = self.index.astype('O') assert_copy(actual.levels, expected.levels) assert_copy(actual.labels, expected.labels) self.check_level_names(actual, expected.names) with tm.assert_raises_regex(TypeError, "^Setting.*dtype.*object"): self.index.astype(np.dtype(int)) @pytest.mark.parametrize('ordered', [True, False]) def test_astype_category(self, ordered): # GH 18630 msg = '> 1 ndim Categorical are not supported at this time' with tm.assert_raises_regex(NotImplementedError, msg): self.index.astype(CategoricalDtype(ordered=ordered)) if ordered is False: # dtype='category' defaults to ordered=False, so only test once with tm.assert_raises_regex(NotImplementedError, msg): self.index.astype('category') def test_constructor_single_level(self): result = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']], labels=[[0, 1, 2, 3]], names=['first']) assert isinstance(result, MultiIndex) expected = Index(['foo', 'bar', 'baz', 'qux'], name='first') tm.assert_index_equal(result.levels[0], expected) assert result.names == ['first'] def test_constructor_no_levels(self): tm.assert_raises_regex(ValueError, "non-zero number " "of levels/labels", MultiIndex, levels=[], labels=[]) both_re = re.compile('Must pass both levels and labels') with tm.assert_raises_regex(TypeError, both_re): MultiIndex(levels=[]) with tm.assert_raises_regex(TypeError, both_re): MultiIndex(labels=[]) def test_constructor_mismatched_label_levels(self): labels = [np.array([1]), np.array([2]), np.array([3])] levels = ["a"] tm.assert_raises_regex(ValueError, "Length of levels and labels " "must be the same", MultiIndex, levels=levels, labels=labels) length_error = re.compile('>= length of level') label_error = re.compile(r'Unequal label lengths: \[4, 2\]') # important to check that it's looking at the right thing. with tm.assert_raises_regex(ValueError, length_error): MultiIndex(levels=[['a'], ['b']], labels=[[0, 1, 2, 3], [0, 3, 4, 1]]) with tm.assert_raises_regex(ValueError, label_error): MultiIndex(levels=[['a'], ['b']], labels=[[0, 0, 0, 0], [0, 0]]) # external API with tm.assert_raises_regex(ValueError, length_error): self.index.copy().set_levels([['a'], ['b']]) with tm.assert_raises_regex(ValueError, label_error): self.index.copy().set_labels([[0, 0, 0, 0], [0, 0]]) def test_constructor_nonhashable_names(self): # GH 20527 levels = [[1, 2], [u'one', u'two']] labels = [[0, 0, 1, 1], [0, 1, 0, 1]] names = ((['foo'], ['bar'])) message = "MultiIndex.name must be a hashable type" tm.assert_raises_regex(TypeError, message, MultiIndex, levels=levels, labels=labels, names=names) # With .rename() mi = MultiIndex(levels=[[1, 2], [u'one', u'two']], labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=('foo', 'bar')) renamed = [['foor'], ['barr']] tm.assert_raises_regex(TypeError, message, mi.rename, names=renamed) # With .set_names() tm.assert_raises_regex(TypeError, message, mi.set_names, names=renamed) @pytest.mark.parametrize('names', [['a', 'b', 'a'], ['1', '1', '2'], ['1', 'a', '1']]) def test_duplicate_level_names(self, names): # GH18872 pytest.raises(ValueError, pd.MultiIndex.from_product, [[0, 1]] * 3, names=names) # With .rename() mi = pd.MultiIndex.from_product([[0, 1]] * 3) tm.assert_raises_regex(ValueError, "Duplicated level name:", mi.rename, names) # With .rename(., level=) mi.rename(names[0], level=1, inplace=True) tm.assert_raises_regex(ValueError, "Duplicated level name:", mi.rename, names[:2], level=[0, 2]) def assert_multiindex_copied(self, copy, original): # Levels should be (at least, shallow copied) tm.assert_copy(copy.levels, original.levels) tm.assert_almost_equal(copy.labels, original.labels) # Labels doesn't matter which way copied tm.assert_almost_equal(copy.labels, original.labels) assert copy.labels is not original.labels # Names doesn't matter which way copied assert copy.names == original.names assert copy.names is not original.names # Sort order should be copied assert copy.sortorder == original.sortorder def test_copy(self): i_copy = self.index.copy() self.assert_multiindex_copied(i_copy, self.index) def test_shallow_copy(self): i_copy = self.index._shallow_copy() self.assert_multiindex_copied(i_copy, self.index) def test_view(self): i_view = self.index.view() self.assert_multiindex_copied(i_view, self.index) def check_level_names(self, index, names): assert [level.name for level in index.levels] == list(names) def test_changing_names(self): # names should be applied to levels level_names = [level.name for level in self.index.levels] self.check_level_names(self.index, self.index.names) view = self.index.view() copy = self.index.copy() shallow_copy = self.index._shallow_copy() # changing names should change level names on object new_names = [name + "a" for name in self.index.names] self.index.names = new_names self.check_level_names(self.index, new_names) # but not on copies self.check_level_names(view, level_names) self.check_level_names(copy, level_names) self.check_level_names(shallow_copy, level_names) # and copies shouldn't change original shallow_copy.names = [name + "c" for name in shallow_copy.names] self.check_level_names(self.index, new_names) def test_get_level_number_integer(self): self.index.names = [1, 0] assert self.index._get_level_number(1) == 0 assert self.index._get_level_number(0) == 1 pytest.raises(IndexError, self.index._get_level_number, 2) tm.assert_raises_regex(KeyError, 'Level fourth not found', self.index._get_level_number, 'fourth') def test_from_arrays(self): arrays = [] for lev, lab in zip(self.index.levels, self.index.labels): arrays.append(np.asarray(lev).take(lab)) # list of arrays as input result = MultiIndex.from_arrays(arrays, names=self.index.names) tm.assert_index_equal(result, self.index) # infer correctly result = MultiIndex.from_arrays([[pd.NaT, Timestamp('20130101')], ['a', 'b']]) assert result.levels[0].equals(Index([Timestamp('20130101')])) assert result.levels[1].equals(Index(['a', 'b'])) def test_from_arrays_iterator(self): # GH 18434 arrays = [] for lev, lab in zip(self.index.levels, self.index.labels): arrays.append(np.asarray(lev).take(lab)) # iterator as input result = MultiIndex.from_arrays(iter(arrays), names=self.index.names) tm.assert_index_equal(result, self.index) # invalid iterator input with tm.assert_raises_regex( TypeError, "Input must be a list / sequence of array-likes."): MultiIndex.from_arrays(0) def test_from_arrays_index_series_datetimetz(self): idx1 = pd.date_range('2015-01-01 10:00', freq='D', periods=3, tz='US/Eastern') idx2 = pd.date_range('2015-01-01 10:00', freq='H', periods=3, tz='Asia/Tokyo') result = pd.MultiIndex.from_arrays([idx1, idx2]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) result2 = pd.MultiIndex.from_arrays([pd.Series(idx1), pd.Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) tm.assert_index_equal(result, result2) def test_from_arrays_index_series_timedelta(self): idx1 = pd.timedelta_range('1 days', freq='D', periods=3) idx2 = pd.timedelta_range('2 hours', freq='H', periods=3) result = pd.MultiIndex.from_arrays([idx1, idx2]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) result2 = pd.MultiIndex.from_arrays([pd.Series(idx1), pd.Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) tm.assert_index_equal(result, result2) def test_from_arrays_index_series_period(self): idx1 = pd.period_range('2011-01-01', freq='D', periods=3) idx2 = pd.period_range('2015-01-01', freq='H', periods=3) result = pd.MultiIndex.from_arrays([idx1, idx2]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) result2 = pd.MultiIndex.from_arrays([pd.Series(idx1), pd.Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) tm.assert_index_equal(result, result2) def test_from_arrays_index_datetimelike_mixed(self): idx1 = pd.date_range('2015-01-01 10:00', freq='D', periods=3, tz='US/Eastern') idx2 = pd.date_range('2015-01-01 10:00', freq='H', periods=3) idx3 = pd.timedelta_range('1 days', freq='D', periods=3) idx4 = pd.period_range('2011-01-01', freq='D', periods=3) result = pd.MultiIndex.from_arrays([idx1, idx2, idx3, idx4]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) tm.assert_index_equal(result.get_level_values(2), idx3) tm.assert_index_equal(result.get_level_values(3), idx4) result2 = pd.MultiIndex.from_arrays([pd.Series(idx1), pd.Series(idx2), pd.Series(idx3), pd.Series(idx4)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) tm.assert_index_equal(result2.get_level_values(2), idx3) tm.assert_index_equal(result2.get_level_values(3), idx4) tm.assert_index_equal(result, result2) def test_from_arrays_index_series_categorical(self): # GH13743 idx1 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=False) idx2 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=True) result = pd.MultiIndex.from_arrays([idx1, idx2]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) result2 = pd.MultiIndex.from_arrays([pd.Series(idx1), pd.Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) result3 = pd.MultiIndex.from_arrays([idx1.values, idx2.values]) tm.assert_index_equal(result3.get_level_values(0), idx1) tm.assert_index_equal(result3.get_level_values(1), idx2) def test_from_arrays_empty(self): # 0 levels with tm.assert_raises_regex( ValueError, "Must pass non-zero number of levels/labels"): MultiIndex.from_arrays(arrays=[]) # 1 level result = MultiIndex.from_arrays(arrays=[[]], names=['A']) assert isinstance(result, MultiIndex) expected = Index([], name='A') tm.assert_index_equal(result.levels[0], expected) # N levels for N in [2, 3]: arrays = [[]] * N names = list('ABC')[:N] result = MultiIndex.from_arrays(arrays=arrays, names=names) expected = MultiIndex(levels=[[]] * N, labels=[[]] * N, names=names) tm.assert_index_equal(result, expected) def test_from_arrays_invalid_input(self): invalid_inputs = [1, [1], [1, 2], [[1], 2], 'a', ['a'], ['a', 'b'], [['a'], 'b']] for i in invalid_inputs: pytest.raises(TypeError, MultiIndex.from_arrays, arrays=i) def test_from_arrays_different_lengths(self): # see gh-13599 idx1 = [1, 2, 3] idx2 = ['a', 'b'] tm.assert_raises_regex(ValueError, '^all arrays must ' 'be same length$', MultiIndex.from_arrays, [idx1, idx2]) idx1 = [] idx2 = ['a', 'b'] tm.assert_raises_regex(ValueError, '^all arrays must ' 'be same length$', MultiIndex.from_arrays, [idx1, idx2]) idx1 = [1, 2, 3] idx2 = [] tm.assert_raises_regex(ValueError, '^all arrays must ' 'be same length$', MultiIndex.from_arrays, [idx1, idx2]) def test_from_product(self): first = ['foo', 'bar', 'buz'] second = ['a', 'b', 'c'] names = ['first', 'second'] result = MultiIndex.from_product([first, second], names=names) tuples = [('foo', 'a'), ('foo', 'b'), ('foo', 'c'), ('bar', 'a'), ('bar', 'b'), ('bar', 'c'), ('buz', 'a'), ('buz', 'b'), ('buz', 'c')] expected = MultiIndex.from_tuples(tuples, names=names) tm.assert_index_equal(result, expected) def test_from_product_iterator(self): # GH 18434 first = ['foo', 'bar', 'buz'] second = ['a', 'b', 'c'] names = ['first', 'second'] tuples = [('foo', 'a'), ('foo', 'b'), ('foo', 'c'), ('bar', 'a'), ('bar', 'b'), ('bar', 'c'), ('buz', 'a'), ('buz', 'b'), ('buz', 'c')] expected = MultiIndex.from_tuples(tuples, names=names) # iterator as input result = MultiIndex.from_product(iter([first, second]), names=names) tm.assert_index_equal(result, expected) # Invalid non-iterable input with tm.assert_raises_regex( TypeError, "Input must be a list / sequence of iterables."): MultiIndex.from_product(0) def test_from_product_empty(self): # 0 levels with tm.assert_raises_regex( ValueError, "Must pass non-zero number of levels/labels"): MultiIndex.from_product([]) # 1 level result = MultiIndex.from_product([[]], names=['A']) expected = pd.Index([], name='A') tm.assert_index_equal(result.levels[0], expected) # 2 levels l1 = [[], ['foo', 'bar', 'baz'], []] l2 = [[], [], ['a', 'b', 'c']] names = ['A', 'B'] for first, second in zip(l1, l2): result = MultiIndex.from_product([first, second], names=names) expected = MultiIndex(levels=[first, second], labels=[[], []], names=names) tm.assert_index_equal(result, expected) # GH12258 names = ['A', 'B', 'C'] for N in range(4): lvl2 = lrange(N) result = MultiIndex.from_product([[], lvl2, []], names=names) expected = MultiIndex(levels=[[], lvl2, []], labels=[[], [], []], names=names) tm.assert_index_equal(result, expected) def test_from_product_invalid_input(self): invalid_inputs = [1, [1], [1, 2], [[1], 2], 'a', ['a'], ['a', 'b'], [['a'], 'b']] for i in invalid_inputs: pytest.raises(TypeError, MultiIndex.from_product, iterables=i) def test_from_product_datetimeindex(self): dt_index = date_range('2000-01-01', periods=2) mi = pd.MultiIndex.from_product([[1, 2], dt_index]) etalon = construct_1d_object_array_from_listlike([(1, pd.Timestamp( '2000-01-01')), (1, pd.Timestamp('2000-01-02')), (2, pd.Timestamp( '2000-01-01')), (2, pd.Timestamp('2000-01-02'))]) tm.assert_numpy_array_equal(mi.values, etalon) def test_from_product_index_series_categorical(self): # GH13743 first = ['foo', 'bar'] for ordered in [False, True]: idx = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=ordered) expected = pd.CategoricalIndex(list("abcaab") + list("abcaab"), categories=list("bac"), ordered=ordered) for arr in [idx, pd.Series(idx), idx.values]: result = pd.MultiIndex.from_product([first, arr]) tm.assert_index_equal(result.get_level_values(1), expected) def test_values_boxed(self): tuples = [(1, pd.Timestamp('2000-01-01')), (2, pd.NaT), (3, pd.Timestamp('2000-01-03')), (1, pd.Timestamp('2000-01-04')), (2, pd.Timestamp('2000-01-02')), (3, pd.Timestamp('2000-01-03'))] result = pd.MultiIndex.from_tuples(tuples) expected = construct_1d_object_array_from_listlike(tuples) tm.assert_numpy_array_equal(result.values, expected) # Check that code branches for boxed values produce identical results tm.assert_numpy_array_equal(result.values[:4], result[:4].values) def test_values_multiindex_datetimeindex(self): # Test to ensure we hit the boxing / nobox part of MI.values ints = np.arange(10 ** 18, 10 ** 18 + 5) naive = pd.DatetimeIndex(ints) aware = pd.DatetimeIndex(ints, tz='US/Central') idx = pd.MultiIndex.from_arrays([naive, aware]) result = idx.values outer = pd.DatetimeIndex([x[0] for x in result]) tm.assert_index_equal(outer, naive) inner = pd.DatetimeIndex([x[1] for x in result]) tm.assert_index_equal(inner, aware) # n_lev > n_lab result = idx[:2].values outer = pd.DatetimeIndex([x[0] for x in result]) tm.assert_index_equal(outer, naive[:2]) inner = pd.DatetimeIndex([x[1] for x in result]) tm.assert_index_equal(inner, aware[:2]) def test_values_multiindex_periodindex(self): # Test to ensure we hit the boxing / nobox part of MI.values ints = np.arange(2007, 2012) pidx = pd.PeriodIndex(ints, freq='D') idx = pd.MultiIndex.from_arrays([ints, pidx]) result = idx.values outer = pd.Int64Index([x[0] for x in result]) tm.assert_index_equal(outer, pd.Int64Index(ints)) inner = pd.PeriodIndex([x[1] for x in result]) tm.assert_index_equal(inner, pidx) # n_lev > n_lab result = idx[:2].values outer = pd.Int64Index([x[0] for x in result]) tm.assert_index_equal(outer, pd.Int64Index(ints[:2])) inner = pd.PeriodIndex([x[1] for x in result]) tm.assert_index_equal(inner, pidx[:2]) def test_append(self): result = self.index[:3].append(self.index[3:]) assert result.equals(self.index) foos = [self.index[:1], self.index[1:3], self.index[3:]] result = foos[0].append(foos[1:]) assert result.equals(self.index) # empty result = self.index.append([]) assert result.equals(self.index) def test_append_mixed_dtypes(self): # GH 13660 dti = date_range('2011-01-01', freq='M', periods=3, ) dti_tz = date_range('2011-01-01', freq='M', periods=3, tz='US/Eastern') pi = period_range('2011-01', freq='M', periods=3) mi = MultiIndex.from_arrays([[1, 2, 3], [1.1, np.nan, 3.3], ['a', 'b', 'c'], dti, dti_tz, pi]) assert mi.nlevels == 6 res = mi.append(mi) exp = MultiIndex.from_arrays([[1, 2, 3, 1, 2, 3], [1.1, np.nan, 3.3, 1.1, np.nan, 3.3], ['a', 'b', 'c', 'a', 'b', 'c'], dti.append(dti), dti_tz.append(dti_tz), pi.append(pi)]) tm.assert_index_equal(res, exp) other = MultiIndex.from_arrays([['x', 'y', 'z'], ['x', 'y', 'z'], ['x', 'y', 'z'], ['x', 'y', 'z'], ['x', 'y', 'z'], ['x', 'y', 'z']]) res = mi.append(other) exp = MultiIndex.from_arrays([[1, 2, 3, 'x', 'y', 'z'], [1.1, np.nan, 3.3, 'x', 'y', 'z'], ['a', 'b', 'c', 'x', 'y', 'z'], dti.append(pd.Index(['x', 'y', 'z'])), dti_tz.append(pd.Index(['x', 'y', 'z'])), pi.append(pd.Index(['x', 'y', 'z']))]) tm.assert_index_equal(res, exp) def test_get_level_values(self): result = self.index.get_level_values(0) expected = Index(['foo', 'foo', 'bar', 'baz', 'qux', 'qux'], name='first') tm.assert_index_equal(result, expected) assert result.name == 'first' result = self.index.get_level_values('first') expected = self.index.get_level_values(0) tm.assert_index_equal(result, expected) # GH 10460 index = MultiIndex( levels=[CategoricalIndex(['A', 'B']), CategoricalIndex([1, 2, 3])], labels=[np.array([0, 0, 0, 1, 1, 1]), np.array([0, 1, 2, 0, 1, 2])]) exp = CategoricalIndex(['A', 'A', 'A', 'B', 'B', 'B']) tm.assert_index_equal(index.get_level_values(0), exp) exp = CategoricalIndex([1, 2, 3, 1, 2, 3]) tm.assert_index_equal(index.get_level_values(1), exp) def test_get_level_values_int_with_na(self): # GH 17924 arrays = [['a', 'b', 'b'], [1, np.nan, 2]] index = pd.MultiIndex.from_arrays(arrays) result = index.get_level_values(1) expected = Index([1, np.nan, 2]) tm.assert_index_equal(result, expected) arrays = [['a', 'b', 'b'], [np.nan, np.nan, 2]] index = pd.MultiIndex.from_arrays(arrays) result = index.get_level_values(1) expected = Index([np.nan, np.nan, 2]) tm.assert_index_equal(result, expected) def test_get_level_values_na(self): arrays = [[np.nan, np.nan, np.nan], ['a', np.nan, 1]] index = pd.MultiIndex.from_arrays(arrays) result = index.get_level_values(0) expected = pd.Index([np.nan, np.nan, np.nan]) tm.assert_index_equal(result, expected) result = index.get_level_values(1) expected = pd.Index(['a', np.nan, 1]) tm.assert_index_equal(result, expected) arrays = [['a', 'b', 'b'], pd.DatetimeIndex([0, 1, pd.NaT])] index = pd.MultiIndex.from_arrays(arrays) result = index.get_level_values(1) expected = pd.DatetimeIndex([0, 1, pd.NaT]) tm.assert_index_equal(result, expected) arrays = [[], []] index = pd.MultiIndex.from_arrays(arrays) result = index.get_level_values(0) expected = pd.Index([], dtype=object) tm.assert_index_equal(result, expected) def test_get_level_values_all_na(self): # GH 17924 when level entirely consists of nan arrays = [[np.nan, np.nan, np.nan], ['a', np.nan, 1]] index = pd.MultiIndex.from_arrays(arrays) result = index.get_level_values(0) expected = pd.Index([np.nan, np.nan, np.nan], dtype=np.float64) tm.assert_index_equal(result, expected) result = index.get_level_values(1) expected = pd.Index(['a', np.nan, 1], dtype=object) tm.assert_index_equal(result, expected) def test_reorder_levels(self): # this blows up tm.assert_raises_regex(IndexError, '^Too many levels', self.index.reorder_levels, [2, 1, 0]) def test_nlevels(self): assert self.index.nlevels == 2 def test_iter(self): result = list(self.index) expected = [('foo', 'one'), ('foo', 'two'), ('bar', 'one'), ('baz', 'two'), ('qux', 'one'), ('qux', 'two')] assert result == expected def test_legacy_pickle(self): if PY3: pytest.skip("testing for legacy pickles not " "support on py3") path = tm.get_data_path('multiindex_v1.pickle') obj = pd.read_pickle(path) obj2 = MultiIndex.from_tuples(obj.values) assert obj.equals(obj2) res = obj.get_indexer(obj) exp = np.arange(len(obj), dtype=np.intp) assert_almost_equal(res, exp) res = obj.get_indexer(obj2[::-1]) exp = obj.get_indexer(obj[::-1]) exp2 = obj2.get_indexer(obj2[::-1]) assert_almost_equal(res, exp) assert_almost_equal(exp, exp2) def test_legacy_v2_unpickle(self): # 0.7.3 -> 0.8.0 format manage path = tm.get_data_path('mindex_073.pickle') obj = pd.read_pickle(path) obj2 = MultiIndex.from_tuples(obj.values) assert obj.equals(obj2) res = obj.get_indexer(obj) exp = np.arange(len(obj), dtype=np.intp) assert_almost_equal(res, exp) res = obj.get_indexer(obj2[::-1]) exp = obj.get_indexer(obj[::-1]) exp2 = obj2.get_indexer(obj2[::-1]) assert_almost_equal(res, exp) assert_almost_equal(exp, exp2) def test_roundtrip_pickle_with_tz(self): # GH 8367 # round-trip of timezone index = MultiIndex.from_product( [[1, 2], ['a', 'b'], date_range('20130101', periods=3, tz='US/Eastern') ], names=['one', 'two', 'three']) unpickled = tm.round_trip_pickle(index) assert index.equal_levels(unpickled) def test_from_tuples_index_values(self): result = MultiIndex.from_tuples(self.index) assert (result.values == self.index.values).all() def test_contains(self): assert ('foo', 'two') in self.index assert ('bar', 'two') not in self.index assert None not in self.index def test_contains_top_level(self): midx = MultiIndex.from_product([['A', 'B'], [1, 2]]) assert 'A' in midx assert 'A' not in midx._engine def test_contains_with_nat(self): # MI with a NaT mi = MultiIndex(levels=[['C'], pd.date_range('2012-01-01', periods=5)], labels=[[0, 0, 0, 0, 0, 0], [-1, 0, 1, 2, 3, 4]], names=[None, 'B']) assert ('C', pd.Timestamp('2012-01-01')) in mi for val in mi.values: assert val in mi def test_is_all_dates(self): assert not self.index.is_all_dates def test_is_numeric(self): # MultiIndex is never numeric assert not self.index.is_numeric() def test_getitem(self): # scalar assert self.index[2] == ('bar', 'one') # slice result = self.index[2:5] expected = self.index[[2, 3, 4]] assert result.equals(expected) # boolean result = self.index[[True, False, True, False, True, True]] result2 = self.index[np.array([True, False, True, False, True, True])] expected = self.index[[0, 2, 4, 5]] assert result.equals(expected) assert result2.equals(expected) def test_getitem_group_select(self): sorted_idx, _ = self.index.sortlevel(0) assert sorted_idx.get_loc('baz') == slice(3, 4) assert sorted_idx.get_loc('foo') == slice(0, 2) def test_get_loc(self): assert self.index.get_loc(('foo', 'two')) == 1 assert self.index.get_loc(('baz', 'two')) == 3 pytest.raises(KeyError, self.index.get_loc, ('bar', 'two')) pytest.raises(KeyError, self.index.get_loc, 'quux') pytest.raises(NotImplementedError, self.index.get_loc, 'foo', method='nearest') # 3 levels index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index( lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])]) pytest.raises(KeyError, index.get_loc, (1, 1)) assert index.get_loc((2, 0)) == slice(3, 5) def test_get_loc_duplicates(self): index = Index([2, 2, 2, 2]) result = index.get_loc(2) expected = slice(0, 4) assert result == expected # pytest.raises(Exception, index.get_loc, 2) index = Index(['c', 'a', 'a', 'b', 'b']) rs = index.get_loc('c') xp = 0 assert rs == xp def test_get_value_duplicates(self): index = MultiIndex(levels=[['D', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]], labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]], names=['tag', 'day']) assert index.get_loc('D') == slice(0, 3) with pytest.raises(KeyError): index._engine.get_value(np.array([]), 'D') def test_get_loc_level(self): index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index( lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])]) loc, new_index = index.get_loc_level((0, 1)) expected = slice(1, 2) exp_index = index[expected].droplevel(0).droplevel(0) assert loc == expected assert new_index.equals(exp_index) loc, new_index = index.get_loc_level((0, 1, 0)) expected = 1 assert loc == expected assert new_index is None pytest.raises(KeyError, index.get_loc_level, (2, 2)) index = MultiIndex(levels=[[2000], lrange(4)], labels=[np.array( [0, 0, 0, 0]), np.array([0, 1, 2, 3])]) result, new_index = index.get_loc_level((2000, slice(None, None))) expected = slice(None, None) assert result == expected assert new_index.equals(index.droplevel(0)) @pytest.mark.parametrize('level', [0, 1]) @pytest.mark.parametrize('null_val', [np.nan, pd.NaT, None]) def test_get_loc_nan(self, level, null_val): # GH 18485 : NaN in MultiIndex levels = [['a', 'b'], ['c', 'd']] key = ['b', 'd'] levels[level] = np.array([0, null_val], dtype=type(null_val)) key[level] = null_val idx = MultiIndex.from_product(levels) assert idx.get_loc(tuple(key)) == 3 def test_get_loc_missing_nan(self): # GH 8569 idx = MultiIndex.from_arrays([[1.0, 2.0], [3.0, 4.0]]) assert isinstance(idx.get_loc(1), slice) pytest.raises(KeyError, idx.get_loc, 3) pytest.raises(KeyError, idx.get_loc, np.nan) pytest.raises(KeyError, idx.get_loc, [np.nan]) @pytest.mark.parametrize('dtype1', [int, float, bool, str]) @pytest.mark.parametrize('dtype2', [int, float, bool, str]) def test_get_loc_multiple_dtypes(self, dtype1, dtype2): # GH 18520 levels = [np.array([0, 1]).astype(dtype1), np.array([0, 1]).astype(dtype2)] idx = pd.MultiIndex.from_product(levels) assert idx.get_loc(idx[2]) == 2 @pytest.mark.parametrize('level', [0, 1]) @pytest.mark.parametrize('dtypes', [[int, float], [float, int]]) def test_get_loc_implicit_cast(self, level, dtypes): # GH 18818, GH 15994 : as flat index, cast int to float and vice-versa levels = [['a', 'b'], ['c', 'd']] key = ['b', 'd'] lev_dtype, key_dtype = dtypes levels[level] = np.array([0, 1], dtype=lev_dtype) key[level] = key_dtype(1) idx = MultiIndex.from_product(levels) assert idx.get_loc(tuple(key)) == 3 def test_get_loc_cast_bool(self): # GH 19086 : int is casted to bool, but not vice-versa levels = [[False, True], np.arange(2, dtype='int64')] idx = MultiIndex.from_product(levels) assert idx.get_loc((0, 1)) == 1 assert idx.get_loc((1, 0)) == 2 pytest.raises(KeyError, idx.get_loc, (False, True)) pytest.raises(KeyError, idx.get_loc, (True, False)) def test_slice_locs(self): df = tm.makeTimeDataFrame() stacked = df.stack() idx = stacked.index slob = slice(*idx.slice_locs(df.index[5], df.index[15])) sliced = stacked[slob] expected = df[5:16].stack() tm.assert_almost_equal(sliced.values, expected.values) slob = slice(*idx.slice_locs(df.index[5] + timedelta(seconds=30), df.index[15] - timedelta(seconds=30))) sliced = stacked[slob] expected = df[6:15].stack() tm.assert_almost_equal(sliced.values, expected.values) def test_slice_locs_with_type_mismatch(self): df = tm.makeTimeDataFrame() stacked = df.stack() idx = stacked.index tm.assert_raises_regex(TypeError, '^Level type mismatch', idx.slice_locs, (1, 3)) tm.assert_raises_regex(TypeError, '^Level type mismatch', idx.slice_locs, df.index[5] + timedelta( seconds=30), (5, 2)) df = tm.makeCustomDataframe(5, 5) stacked = df.stack() idx = stacked.index with tm.assert_raises_regex(TypeError, '^Level type mismatch'): idx.slice_locs(timedelta(seconds=30)) # TODO: Try creating a UnicodeDecodeError in exception message with tm.assert_raises_regex(TypeError, '^Level type mismatch'): idx.slice_locs(df.index[1], (16, "a")) def test_slice_locs_not_sorted(self): index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index( lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])]) tm.assert_raises_regex(KeyError, "[Kk]ey length.*greater than " "MultiIndex lexsort depth", index.slice_locs, (1, 0, 1), (2, 1, 0)) # works sorted_index, _ = index.sortlevel(0) # should there be a test case here??? sorted_index.slice_locs((1, 0, 1), (2, 1, 0)) def test_slice_locs_partial(self): sorted_idx, _ = self.index.sortlevel(0) result = sorted_idx.slice_locs(('foo', 'two'), ('qux', 'one')) assert result == (1, 5) result = sorted_idx.slice_locs(None, ('qux', 'one')) assert result == (0, 5) result = sorted_idx.slice_locs(('foo', 'two'), None) assert result == (1, len(sorted_idx)) result = sorted_idx.slice_locs('bar', 'baz') assert result == (2, 4) def test_slice_locs_not_contained(self): # some searchsorted action index = MultiIndex(levels=[[0, 2, 4, 6], [0, 2, 4]], labels=[[0, 0, 0, 1, 1, 2, 3, 3, 3], [0, 1, 2, 1, 2, 2, 0, 1, 2]], sortorder=0) result = index.slice_locs((1, 0), (5, 2)) assert result == (3, 6) result = index.slice_locs(1, 5) assert result == (3, 6) result = index.slice_locs((2, 2), (5, 2)) assert result == (3, 6) result = index.slice_locs(2, 5) assert result == (3, 6) result = index.slice_locs((1, 0), (6, 3)) assert result == (3, 8) result = index.slice_locs(-1, 10) assert result == (0, len(index)) def test_consistency(self): # need to construct an overflow major_axis = lrange(70000) minor_axis = lrange(10) major_labels = np.arange(70000) minor_labels = np.repeat(lrange(10), 7000) # the fact that is works means it's consistent index = MultiIndex(levels=[major_axis, minor_axis], labels=[major_labels, minor_labels]) # inconsistent major_labels = np.array([0, 0, 1, 1, 1, 2, 2, 3, 3]) minor_labels = np.array([0, 1, 0, 1, 1, 0, 1, 0, 1]) index = MultiIndex(levels=[major_axis, minor_axis], labels=[major_labels, minor_labels]) assert not index.is_unique def test_truncate(self): major_axis = Index(lrange(4)) minor_axis = Index(lrange(2)) major_labels = np.array([0, 0, 1, 2, 3, 3]) minor_labels = np.array([0, 1, 0, 1, 0, 1]) index = MultiIndex(levels=[major_axis, minor_axis], labels=[major_labels, minor_labels]) result = index.truncate(before=1) assert 'foo' not in result.levels[0] assert 1 in result.levels[0] result = index.truncate(after=1) assert 2 not in result.levels[0] assert 1 in result.levels[0] result = index.truncate(before=1, after=2) assert len(result.levels[0]) == 2 # after < before pytest.raises(ValueError, index.truncate, 3, 1) def test_get_indexer(self): major_axis = Index(lrange(4)) minor_axis = Index(lrange(2)) major_labels = np.array([0, 0, 1, 2, 2, 3, 3], dtype=np.intp) minor_labels = np.array([0, 1, 0, 0, 1, 0, 1], dtype=np.intp) index = MultiIndex(levels=[major_axis, minor_axis], labels=[major_labels, minor_labels]) idx1 = index[:5] idx2 = index[[1, 3, 5]] r1 = idx1.get_indexer(idx2) assert_almost_equal(r1, np.array([1, 3, -1], dtype=np.intp)) r1 = idx2.get_indexer(idx1, method='pad') e1 = np.array([-1, 0, 0, 1, 1], dtype=np.intp) assert_almost_equal(r1, e1) r2 = idx2.get_indexer(idx1[::-1], method='pad') assert_almost_equal(r2, e1[::-1]) rffill1 = idx2.get_indexer(idx1, method='ffill') assert_almost_equal(r1, rffill1) r1 = idx2.get_indexer(idx1, method='backfill') e1 = np.array([0, 0, 1, 1, 2], dtype=np.intp) assert_almost_equal(r1, e1) r2 = idx2.get_indexer(idx1[::-1], method='backfill') assert_almost_equal(r2, e1[::-1]) rbfill1 = idx2.get_indexer(idx1, method='bfill') assert_almost_equal(r1, rbfill1) # pass non-MultiIndex r1 = idx1.get_indexer(idx2.values) rexp1 = idx1.get_indexer(idx2) assert_almost_equal(r1, rexp1) r1 = idx1.get_indexer([1, 2, 3]) assert (r1 == [-1, -1, -1]).all() # create index with duplicates idx1 = Index(lrange(10) + lrange(10)) idx2 = Index(lrange(20)) msg = "Reindexing only valid with uniquely valued Index objects" with tm.assert_raises_regex(InvalidIndexError, msg): idx1.get_indexer(idx2) def test_get_indexer_nearest(self): midx = MultiIndex.from_tuples([('a', 1), ('b', 2)]) with pytest.raises(NotImplementedError): midx.get_indexer(['a'], method='nearest') with pytest.raises(NotImplementedError): midx.get_indexer(['a'], method='pad', tolerance=2) def test_hash_collisions(self): # non-smoke test that we don't get hash collisions index = MultiIndex.from_product([np.arange(1000), np.arange(1000)], names=['one', 'two']) result = index.get_indexer(index.values) tm.assert_numpy_array_equal(result, np.arange( len(index), dtype='intp')) for i in [0, 1, len(index) - 2, len(index) - 1]: result = index.get_loc(index[i]) assert result == i def test_format(self): self.index.format() self.index[:0].format() def test_format_integer_names(self): index = MultiIndex(levels=[[0, 1], [0, 1]], labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[0, 1]) index.format(names=True) def test_format_sparse_display(self): index = MultiIndex(levels=[[0, 1], [0, 1], [0, 1], [0]], labels=[[0, 0, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]]) result = index.format() assert result[3] == '1 0 0 0' def test_format_sparse_config(self): warn_filters = warnings.filters warnings.filterwarnings('ignore', category=FutureWarning, module=".*format") # GH1538 pd.set_option('display.multi_sparse', False) result = self.index.format() assert result[1] == 'foo two' tm.reset_display_options() warnings.filters = warn_filters def test_to_frame(self): tuples = [(1, 'one'), (1, 'two'), (2, 'one'), (2, 'two')] index = MultiIndex.from_tuples(tuples) result = index.to_frame(index=False) expected = DataFrame(tuples) tm.assert_frame_equal(result, expected) result = index.to_frame() expected.index = index tm.assert_frame_equal(result, expected) tuples = [(1, 'one'), (1, 'two'), (2, 'one'), (2, 'two')] index = MultiIndex.from_tuples(tuples, names=['first', 'second']) result = index.to_frame(index=False) expected = DataFrame(tuples) expected.columns = ['first', 'second'] tm.assert_frame_equal(result, expected) result = index.to_frame() expected.index = index tm.assert_frame_equal(result, expected) index = MultiIndex.from_product([range(5), pd.date_range('20130101', periods=3)]) result = index.to_frame(index=False) expected = DataFrame( {0: np.repeat(np.arange(5, dtype='int64'), 3), 1: np.tile(pd.date_range('20130101', periods=3), 5)}) tm.assert_frame_equal(result, expected) index = MultiIndex.from_product([range(5), pd.date_range('20130101', periods=3)]) result = index.to_frame() expected.index = index tm.assert_frame_equal(result, expected) def test_to_hierarchical(self): index = MultiIndex.from_tuples([(1, 'one'), (1, 'two'), (2, 'one'), ( 2, 'two')]) result = index.to_hierarchical(3) expected = MultiIndex(levels=[[1, 2], ['one', 'two']], labels=[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]]) tm.assert_index_equal(result, expected) assert result.names == index.names # K > 1 result = index.to_hierarchical(3, 2) expected = MultiIndex(levels=[[1, 2], ['one', 'two']], labels=[[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]]) tm.assert_index_equal(result, expected) assert result.names == index.names # non-sorted index = MultiIndex.from_tuples([(2, 'c'), (1, 'b'), (2, 'a'), (2, 'b')], names=['N1', 'N2']) result = index.to_hierarchical(2) expected = MultiIndex.from_tuples([(2, 'c'), (2, 'c'), (1, 'b'), (1, 'b'), (2, 'a'), (2, 'a'), (2, 'b'), (2, 'b')], names=['N1', 'N2']) tm.assert_index_equal(result, expected) assert result.names == index.names def test_bounds(self): self.index._bounds def test_equals_multi(self): assert self.index.equals(self.index) assert not self.index.equals(self.index.values) assert self.index.equals(Index(self.index.values)) assert self.index.equal_levels(self.index) assert not self.index.equals(self.index[:-1]) assert not self.index.equals(self.index[-1]) # different number of levels index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index( lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])]) index2 = MultiIndex(levels=index.levels[:-1], labels=index.labels[:-1]) assert not index.equals(index2) assert not index.equal_levels(index2) # levels are different major_axis = Index(lrange(4)) minor_axis = Index(lrange(2)) major_labels = np.array([0, 0, 1, 2, 2, 3]) minor_labels = np.array([0, 1, 0, 0, 1, 0]) index = MultiIndex(levels=[major_axis, minor_axis], labels=[major_labels, minor_labels]) assert not self.index.equals(index) assert not self.index.equal_levels(index) # some of the labels are different major_axis = Index(['foo', 'bar', 'baz', 'qux']) minor_axis = Index(['one', 'two']) major_labels = np.array([0, 0, 2, 2, 3, 3]) minor_labels = np.array([0, 1, 0, 1, 0, 1]) index = MultiIndex(levels=[major_axis, minor_axis], labels=[major_labels, minor_labels]) assert not self.index.equals(index) def test_equals_missing_values(self): # make sure take is not using -1 i = pd.MultiIndex.from_tuples([(0, pd.NaT), (0, pd.Timestamp('20130101'))]) result = i[0:1].equals(i[0]) assert not result result = i[1:2].equals(i[1]) assert not result def test_identical(self): mi = self.index.copy() mi2 = self.index.copy() assert mi.identical(mi2) mi = mi.set_names(['new1', 'new2']) assert mi.equals(mi2) assert not mi.identical(mi2) mi2 = mi2.set_names(['new1', 'new2']) assert mi.identical(mi2) mi3 = Index(mi.tolist(), names=mi.names) mi4 = Index(mi.tolist(), names=mi.names, tupleize_cols=False) assert mi.identical(mi3) assert not mi.identical(mi4) assert mi.equals(mi4) def test_is_(self): mi = MultiIndex.from_tuples(lzip(range(10), range(10))) assert mi.is_(mi) assert mi.is_(mi.view()) assert mi.is_(mi.view().view().view().view()) mi2 = mi.view() # names are metadata, they don't change id mi2.names = ["A", "B"] assert mi2.is_(mi) assert mi.is_(mi2) assert mi.is_(mi.set_names(["C", "D"])) mi2 = mi.view() mi2.set_names(["E", "F"], inplace=True) assert mi.is_(mi2) # levels are inherent properties, they change identity mi3 = mi2.set_levels([lrange(10), lrange(10)]) assert not mi3.is_(mi2) # shouldn't change assert mi2.is_(mi) mi4 = mi3.view() # GH 17464 - Remove duplicate MultiIndex levels mi4.set_levels([lrange(10), lrange(10)], inplace=True) assert not mi4.is_(mi3) mi5 = mi.view() mi5.set_levels(mi5.levels, inplace=True) assert not mi5.is_(mi) def test_union(self): piece1 = self.index[:5][::-1] piece2 = self.index[3:] the_union = piece1 | piece2 tups = sorted(self.index.values) expected = MultiIndex.from_tuples(tups) assert the_union.equals(expected) # corner case, pass self or empty thing: the_union = self.index.union(self.index) assert the_union is self.index the_union = self.index.union(self.index[:0]) assert the_union is self.index # won't work in python 3 # tuples = self.index.values # result = self.index[:4] | tuples[4:] # assert result.equals(tuples) # not valid for python 3 # def test_union_with_regular_index(self): # other = Index(['A', 'B', 'C']) # result = other.union(self.index) # assert ('foo', 'one') in result # assert 'B' in result # result2 = self.index.union(other) # assert result.equals(result2) def test_intersection(self): piece1 = self.index[:5][::-1] piece2 = self.index[3:] the_int = piece1 & piece2 tups = sorted(self.index[3:5].values) expected = MultiIndex.from_tuples(tups) assert the_int.equals(expected) # corner case, pass self the_int = self.index.intersection(self.index) assert the_int is self.index # empty intersection: disjoint empty = self.index[:2] & self.index[2:] expected = self.index[:0] assert empty.equals(expected) # can't do in python 3 # tuples = self.index.values # result = self.index & tuples # assert result.equals(tuples) def test_sub(self): first = self.index # - now raises (previously was set op difference) with pytest.raises(TypeError): first - self.index[-3:] with pytest.raises(TypeError): self.index[-3:] - first with pytest.raises(TypeError): self.index[-3:] - first.tolist() with pytest.raises(TypeError): first.tolist() - self.index[-3:] def test_difference(self): first = self.index result = first.difference(self.index[-3:]) expected = MultiIndex.from_tuples(sorted(self.index[:-3].values), sortorder=0, names=self.index.names) assert isinstance(result, MultiIndex) assert result.equals(expected) assert result.names == self.index.names # empty difference: reflexive result = self.index.difference(self.index) expected = self.index[:0] assert result.equals(expected) assert result.names == self.index.names # empty difference: superset result = self.index[-3:].difference(self.index) expected = self.index[:0] assert result.equals(expected) assert result.names == self.index.names # empty difference: degenerate result = self.index[:0].difference(self.index) expected = self.index[:0] assert result.equals(expected) assert result.names == self.index.names # names not the same chunklet = self.index[-3:] chunklet.names = ['foo', 'baz'] result = first.difference(chunklet) assert result.names == (None, None) # empty, but non-equal result = self.index.difference(self.index.sortlevel(1)[0]) assert len(result) == 0 # raise Exception called with non-MultiIndex result = first.difference(first.values) assert result.equals(first[:0]) # name from empty array result = first.difference([]) assert first.equals(result) assert first.names == result.names # name from non-empty array result = first.difference([('foo', 'one')]) expected = pd.MultiIndex.from_tuples([('bar', 'one'), ('baz', 'two'), ( 'foo', 'two'), ('qux', 'one'), ('qux', 'two')]) expected.names = first.names assert first.names == result.names tm.assert_raises_regex(TypeError, "other must be a MultiIndex " "or a list of tuples", first.difference, [1, 2, 3, 4, 5]) def test_from_tuples(self): tm.assert_raises_regex(TypeError, 'Cannot infer number of levels ' 'from empty list', MultiIndex.from_tuples, []) expected = MultiIndex(levels=[[1, 3], [2, 4]], labels=[[0, 1], [0, 1]], names=['a', 'b']) # input tuples result = MultiIndex.from_tuples(((1, 2), (3, 4)), names=['a', 'b']) tm.assert_index_equal(result, expected) def test_from_tuples_iterator(self): # GH 18434 # input iterator for tuples expected = MultiIndex(levels=[[1, 3], [2, 4]], labels=[[0, 1], [0, 1]], names=['a', 'b']) result = MultiIndex.from_tuples(zip([1, 3], [2, 4]), names=['a', 'b']) tm.assert_index_equal(result, expected) # input non-iterables with tm.assert_raises_regex( TypeError, 'Input must be a list / sequence of tuple-likes.'): MultiIndex.from_tuples(0) def test_from_tuples_empty(self): # GH 16777 result = MultiIndex.from_tuples([], names=['a', 'b']) expected = MultiIndex.from_arrays(arrays=[[], []], names=['a', 'b']) tm.assert_index_equal(result, expected) def test_argsort(self): result = self.index.argsort() expected = self.index.values.argsort() tm.assert_numpy_array_equal(result, expected) def test_sortlevel(self): import random tuples = list(self.index) random.shuffle(tuples) index = MultiIndex.from_tuples(tuples) sorted_idx, _ = index.sortlevel(0) expected = MultiIndex.from_tuples(sorted(tuples)) assert sorted_idx.equals(expected) sorted_idx, _ = index.sortlevel(0, ascending=False) assert sorted_idx.equals(expected[::-1]) sorted_idx, _ = index.sortlevel(1) by1 = sorted(tuples, key=lambda x: (x[1], x[0])) expected = MultiIndex.from_tuples(by1) assert sorted_idx.equals(expected) sorted_idx, _ = index.sortlevel(1, ascending=False) assert sorted_idx.equals(expected[::-1]) def test_sortlevel_not_sort_remaining(self): mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC')) sorted_idx, _ = mi.sortlevel('A', sort_remaining=False) assert sorted_idx.equals(mi) def test_sortlevel_deterministic(self): tuples = [('bar', 'one'), ('foo', 'two'), ('qux', 'two'), ('foo', 'one'), ('baz', 'two'), ('qux', 'one')] index = MultiIndex.from_tuples(tuples) sorted_idx, _ = index.sortlevel(0) expected = MultiIndex.from_tuples(sorted(tuples)) assert sorted_idx.equals(expected) sorted_idx, _ = index.sortlevel(0, ascending=False) assert sorted_idx.equals(expected[::-1]) sorted_idx, _ = index.sortlevel(1) by1 = sorted(tuples, key=lambda x: (x[1], x[0])) expected = MultiIndex.from_tuples(by1) assert sorted_idx.equals(expected) sorted_idx, _ = index.sortlevel(1, ascending=False) assert sorted_idx.equals(expected[::-1]) def test_dims(self): pass def test_drop(self): dropped = self.index.drop([('foo', 'two'), ('qux', 'one')]) index = MultiIndex.from_tuples([('foo', 'two'), ('qux', 'one')]) dropped2 = self.index.drop(index) expected = self.index[[0, 2, 3, 5]] tm.assert_index_equal(dropped, expected) tm.assert_index_equal(dropped2, expected) dropped = self.index.drop(['bar']) expected = self.index[[0, 1, 3, 4, 5]] tm.assert_index_equal(dropped, expected) dropped = self.index.drop('foo') expected = self.index[[2, 3, 4, 5]] tm.assert_index_equal(dropped, expected) index = MultiIndex.from_tuples([('bar', 'two')]) pytest.raises(KeyError, self.index.drop, [('bar', 'two')]) pytest.raises(KeyError, self.index.drop, index) pytest.raises(KeyError, self.index.drop, ['foo', 'two']) # partially correct argument mixed_index = MultiIndex.from_tuples([('qux', 'one'), ('bar', 'two')]) pytest.raises(KeyError, self.index.drop, mixed_index) # error='ignore' dropped = self.index.drop(index, errors='ignore') expected = self.index[[0, 1, 2, 3, 4, 5]] tm.assert_index_equal(dropped, expected) dropped = self.index.drop(mixed_index, errors='ignore') expected = self.index[[0, 1, 2, 3, 5]] tm.assert_index_equal(dropped, expected) dropped = self.index.drop(['foo', 'two'], errors='ignore') expected = self.index[[2, 3, 4, 5]] tm.assert_index_equal(dropped, expected) # mixed partial / full drop dropped = self.index.drop(['foo', ('qux', 'one')]) expected = self.index[[2, 3, 5]] tm.assert_index_equal(dropped, expected) # mixed partial / full drop / error='ignore' mixed_index = ['foo', ('qux', 'one'), 'two'] pytest.raises(KeyError, self.index.drop, mixed_index) dropped = self.index.drop(mixed_index, errors='ignore') expected = self.index[[2, 3, 5]] tm.assert_index_equal(dropped, expected) def test_droplevel_with_names(self): index = self.index[self.index.get_loc('foo')] dropped = index.droplevel(0) assert dropped.name == 'second' index = MultiIndex( levels=[Index(lrange(4)), Index(lrange(4)), Index(lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])], names=['one', 'two', 'three']) dropped = index.droplevel(0) assert dropped.names == ('two', 'three') dropped = index.droplevel('two') expected = index.droplevel(1) assert dropped.equals(expected) def test_droplevel_list(self): index = MultiIndex( levels=[Index(lrange(4)), Index(lrange(4)), Index(lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])], names=['one', 'two', 'three']) dropped = index[:2].droplevel(['three', 'one']) expected = index[:2].droplevel(2).droplevel(0) assert dropped.equals(expected) dropped = index[:2].droplevel([]) expected = index[:2] assert dropped.equals(expected) with pytest.raises(ValueError): index[:2].droplevel(['one', 'two', 'three']) with pytest.raises(KeyError): index[:2].droplevel(['one', 'four']) def test_drop_not_lexsorted(self): # GH 12078 # define the lexsorted version of the multi-index tuples = [('a', ''), ('b1', 'c1'), ('b2', 'c2')] lexsorted_mi = MultiIndex.from_tuples(tuples, names=['b', 'c']) assert lexsorted_mi.is_lexsorted() # and the not-lexsorted version df = pd.DataFrame(columns=['a', 'b', 'c', 'd'], data=[[1, 'b1', 'c1', 3], [1, 'b2', 'c2', 4]]) df = df.pivot_table(index='a', columns=['b', 'c'], values='d') df = df.reset_index() not_lexsorted_mi = df.columns assert not not_lexsorted_mi.is_lexsorted() # compare the results tm.assert_index_equal(lexsorted_mi, not_lexsorted_mi) with tm.assert_produces_warning(PerformanceWarning): tm.assert_index_equal(lexsorted_mi.drop('a'), not_lexsorted_mi.drop('a')) def test_insert(self): # key contained in all levels new_index = self.index.insert(0, ('bar', 'two')) assert new_index.equal_levels(self.index) assert new_index[0] == ('bar', 'two') # key not contained in all levels new_index = self.index.insert(0, ('abc', 'three')) exp0 = Index(list(self.index.levels[0]) + ['abc'], name='first') tm.assert_index_equal(new_index.levels[0], exp0) exp1 = Index(list(self.index.levels[1]) + ['three'], name='second') tm.assert_index_equal(new_index.levels[1], exp1) assert new_index[0] == ('abc', 'three') # key wrong length msg = "Item must have length equal to number of levels" with tm.assert_raises_regex(ValueError, msg): self.index.insert(0, ('foo2',)) left = pd.DataFrame([['a', 'b', 0], ['b', 'd', 1]], columns=['1st', '2nd', '3rd']) left.set_index(['1st', '2nd'], inplace=True) ts = left['3rd'].copy(deep=True) left.loc[('b', 'x'), '3rd'] = 2 left.loc[('b', 'a'), '3rd'] = -1 left.loc[('b', 'b'), '3rd'] = 3 left.loc[('a', 'x'), '3rd'] = 4 left.loc[('a', 'w'), '3rd'] = 5 left.loc[('a', 'a'), '3rd'] = 6 ts.loc[('b', 'x')] = 2 ts.loc['b', 'a'] = -1 ts.loc[('b', 'b')] = 3 ts.loc['a', 'x'] = 4 ts.loc[('a', 'w')] = 5 ts.loc['a', 'a'] = 6 right = pd.DataFrame([['a', 'b', 0], ['b', 'd', 1], ['b', 'x', 2], ['b', 'a', -1], ['b', 'b', 3], ['a', 'x', 4], ['a', 'w', 5], ['a', 'a', 6]], columns=['1st', '2nd', '3rd']) right.set_index(['1st', '2nd'], inplace=True) # FIXME data types changes to float because # of intermediate nan insertion; tm.assert_frame_equal(left, right, check_dtype=False) tm.assert_series_equal(ts, right['3rd']) # GH9250 idx = [('test1', i) for i in range(5)] + \ [('test2', i) for i in range(6)] + \ [('test', 17), ('test', 18)] left = pd.Series(np.linspace(0, 10, 11), pd.MultiIndex.from_tuples(idx[:-2])) left.loc[('test', 17)] = 11 left.loc[('test', 18)] = 12 right = pd.Series(np.linspace(0, 12, 13), pd.MultiIndex.from_tuples(idx)) tm.assert_series_equal(left, right) def test_take_preserve_name(self): taken = self.index.take([3, 0, 1]) assert taken.names == self.index.names def test_take_fill_value(self): # GH 12631 vals = [['A', 'B'], [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02')]] idx = pd.MultiIndex.from_product(vals, names=['str', 'dt']) result = idx.take(np.array([1, 0, -1])) exp_vals = [('A', pd.Timestamp('2011-01-02')), ('A', pd.Timestamp('2011-01-01')), ('B', pd.Timestamp('2011-01-02'))] expected = pd.MultiIndex.from_tuples(exp_vals, names=['str', 'dt']) tm.assert_index_equal(result, expected) # fill_value result = idx.take(np.array([1, 0, -1]), fill_value=True) exp_vals = [('A', pd.Timestamp('2011-01-02')), ('A', pd.Timestamp('2011-01-01')), (np.nan, pd.NaT)] expected = pd.MultiIndex.from_tuples(exp_vals, names=['str', 'dt']) tm.assert_index_equal(result, expected) # allow_fill=False result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) exp_vals = [('A', pd.Timestamp('2011-01-02')), ('A', pd.Timestamp('2011-01-01')), ('B', pd.Timestamp('2011-01-02'))] expected = pd.MultiIndex.from_tuples(exp_vals, names=['str', 'dt']) tm.assert_index_equal(result, expected) msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): idx.take(np.array([1, -5])) def take_invalid_kwargs(self): vals = [['A', 'B'], [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02')]] idx = pd.MultiIndex.from_product(vals, names=['str', 'dt']) indices = [1, 2] msg = r"take\(\) got an unexpected keyword argument 'foo'" tm.assert_raises_regex(TypeError, msg, idx.take, indices, foo=2) msg = "the 'out' parameter is not supported" tm.assert_raises_regex(ValueError, msg, idx.take, indices, out=indices) msg = "the 'mode' parameter is not supported" tm.assert_raises_regex(ValueError, msg, idx.take, indices, mode='clip') @pytest.mark.parametrize('other', [Index(['three', 'one', 'two']), Index(['one']), Index(['one', 'three'])]) def test_join_level(self, other, join_type): join_index, lidx, ridx = other.join(self.index, how=join_type, level='second', return_indexers=True) exp_level = other.join(self.index.levels[1], how=join_type) assert join_index.levels[0].equals(self.index.levels[0]) assert join_index.levels[1].equals(exp_level) # pare down levels mask = np.array( [x[1] in exp_level for x in self.index], dtype=bool) exp_values = self.index.values[mask] tm.assert_numpy_array_equal(join_index.values, exp_values) if join_type in ('outer', 'inner'): join_index2, ridx2, lidx2 = \ self.index.join(other, how=join_type, level='second', return_indexers=True) assert join_index.equals(join_index2) tm.assert_numpy_array_equal(lidx, lidx2) tm.assert_numpy_array_equal(ridx, ridx2) tm.assert_numpy_array_equal(join_index2.values, exp_values) def test_join_level_corner_case(self): # some corner cases idx = Index(['three', 'one', 'two']) result = idx.join(self.index, level='second') assert isinstance(result, MultiIndex) tm.assert_raises_regex(TypeError, "Join.*MultiIndex.*ambiguous", self.index.join, self.index, level=1) def test_join_self(self, join_type): res = self.index joined = res.join(res, how=join_type) assert res is joined def test_join_multi(self): # GH 10665 midx = pd.MultiIndex.from_product( [np.arange(4), np.arange(4)], names=['a', 'b']) idx = pd.Index([1, 2, 5], name='b') # inner jidx, lidx, ridx = midx.join(idx, how='inner', return_indexers=True) exp_idx = pd.MultiIndex.from_product( [np.arange(4), [1, 2]], names=['a', 'b']) exp_lidx = np.array([1, 2, 5, 6, 9, 10, 13, 14], dtype=np.intp) exp_ridx = np.array([0, 1, 0, 1, 0, 1, 0, 1], dtype=np.intp) tm.assert_index_equal(jidx, exp_idx) tm.assert_numpy_array_equal(lidx, exp_lidx) tm.assert_numpy_array_equal(ridx, exp_ridx) # flip jidx, ridx, lidx = idx.join(midx, how='inner', return_indexers=True) tm.assert_index_equal(jidx, exp_idx) tm.assert_numpy_array_equal(lidx, exp_lidx) tm.assert_numpy_array_equal(ridx, exp_ridx) # keep MultiIndex jidx, lidx, ridx = midx.join(idx, how='left', return_indexers=True) exp_ridx = np.array([-1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1], dtype=np.intp) tm.assert_index_equal(jidx, midx) assert lidx is None tm.assert_numpy_array_equal(ridx, exp_ridx) # flip jidx, ridx, lidx = idx.join(midx, how='right', return_indexers=True) tm.assert_index_equal(jidx, midx) assert lidx is None tm.assert_numpy_array_equal(ridx, exp_ridx) def test_reindex(self): result, indexer = self.index.reindex(list(self.index[:4])) assert isinstance(result, MultiIndex) self.check_level_names(result, self.index[:4].names) result, indexer = self.index.reindex(list(self.index)) assert isinstance(result, MultiIndex) assert indexer is None self.check_level_names(result, self.index.names) def test_reindex_level(self): idx = Index(['one']) target, indexer = self.index.reindex(idx, level='second') target2, indexer2 = idx.reindex(self.index, level='second') exp_index = self.index.join(idx, level='second', how='right') exp_index2 = self.index.join(idx, level='second', how='left') assert target.equals(exp_index) exp_indexer = np.array([0, 2, 4]) tm.assert_numpy_array_equal(indexer, exp_indexer, check_dtype=False) assert target2.equals(exp_index2) exp_indexer2 = np.array([0, -1, 0, -1, 0, -1]) tm.assert_numpy_array_equal(indexer2, exp_indexer2, check_dtype=False) tm.assert_raises_regex(TypeError, "Fill method not supported", self.index.reindex, self.index, method='pad', level='second') tm.assert_raises_regex(TypeError, "Fill method not supported", idx.reindex, idx, method='bfill', level='first') def test_duplicates(self): assert not self.index.has_duplicates assert self.index.append(self.index).has_duplicates index = MultiIndex(levels=[[0, 1], [0, 1, 2]], labels=[ [0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]]) assert index.has_duplicates # GH 9075 t = [(u('x'), u('out'), u('z'), 5, u('y'), u('in'), u('z'), 169), (u('x'), u('out'), u('z'), 7, u('y'), u('in'), u('z'), 119), (u('x'), u('out'), u('z'), 9, u('y'), u('in'), u('z'), 135), (u('x'), u('out'), u('z'), 13, u('y'), u('in'), u('z'), 145), (u('x'), u('out'), u('z'), 14, u('y'), u('in'), u('z'), 158), (u('x'), u('out'), u('z'), 16, u('y'), u('in'), u('z'), 122), (u('x'), u('out'), u('z'), 17, u('y'), u('in'), u('z'), 160), (u('x'), u('out'), u('z'), 18, u('y'), u('in'), u('z'), 180), (u('x'), u('out'), u('z'), 20, u('y'), u('in'), u('z'), 143), (u('x'), u('out'), u('z'), 21, u('y'), u('in'), u('z'), 128), (u('x'), u('out'), u('z'), 22, u('y'), u('in'), u('z'), 129), (u('x'), u('out'), u('z'), 25, u('y'), u('in'), u('z'), 111), (u('x'), u('out'), u('z'), 28, u('y'), u('in'), u('z'), 114), (u('x'), u('out'), u('z'), 29, u('y'), u('in'), u('z'), 121), (u('x'), u('out'), u('z'), 31, u('y'), u('in'), u('z'), 126), (u('x'), u('out'), u('z'), 32, u('y'), u('in'), u('z'), 155), (u('x'), u('out'), u('z'), 33, u('y'), u('in'), u('z'), 123), (u('x'), u('out'), u('z'), 12, u('y'), u('in'), u('z'), 144)] index = pd.MultiIndex.from_tuples(t) assert not index.has_duplicates # handle int64 overflow if possible def check(nlevels, with_nulls): labels = np.tile(np.arange(500), 2) level = np.arange(500) if with_nulls: # inject some null values labels[500] = -1 # common nan value labels = [labels.copy() for i in range(nlevels)] for i in range(nlevels): labels[i][500 + i - nlevels // 2] = -1 labels += [np.array([-1, 1]).repeat(500)] else: labels = [labels] * nlevels + [np.arange(2).repeat(500)] levels = [level] * nlevels + [[0, 1]] # no dups index = MultiIndex(levels=levels, labels=labels) assert not index.has_duplicates # with a dup if with_nulls: def f(a): return np.insert(a, 1000, a[0]) labels = list(map(f, labels)) index = MultiIndex(levels=levels, labels=labels) else: values = index.values.tolist() index = MultiIndex.from_tuples(values + [values[0]]) assert index.has_duplicates # no overflow check(4, False) check(4, True) # overflow possible check(8, False) check(8, True) # GH 9125 n, k = 200, 5000 levels = [np.arange(n), tm.makeStringIndex(n), 1000 + np.arange(n)] labels = [np.random.choice(n, k * n) for lev in levels] mi = MultiIndex(levels=levels, labels=labels) for keep in ['first', 'last', False]: left = mi.duplicated(keep=keep) right = pd._libs.hashtable.duplicated_object(mi.values, keep=keep) tm.assert_numpy_array_equal(left, right) # GH5873 for a in [101, 102]: mi = MultiIndex.from_arrays([[101, a], [3.5, np.nan]]) assert not mi.has_duplicates with warnings.catch_warnings(record=True): # Deprecated - see GH20239 assert mi.get_duplicates().equals(MultiIndex.from_arrays( [[], []])) tm.assert_numpy_array_equal(mi.duplicated(), np.zeros( 2, dtype='bool')) for n in range(1, 6): # 1st level shape for m in range(1, 5): # 2nd level shape # all possible unique combinations, including nan lab = product(range(-1, n), range(-1, m)) mi = MultiIndex(levels=[list('abcde')[:n], list('WXYZ')[:m]], labels=np.random.permutation(list(lab)).T) assert len(mi) == (n + 1) * (m + 1) assert not mi.has_duplicates with warnings.catch_warnings(record=True): # Deprecated - see GH20239 assert mi.get_duplicates().equals(MultiIndex.from_arrays( [[], []])) tm.assert_numpy_array_equal(mi.duplicated(), np.zeros( len(mi), dtype='bool')) def test_duplicate_meta_data(self): # GH 10115 index = MultiIndex( levels=[[0, 1], [0, 1, 2]], labels=[[0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]]) for idx in [index, index.set_names([None, None]), index.set_names([None, 'Num']), index.set_names(['Upper', 'Num']), ]: assert idx.has_duplicates assert idx.drop_duplicates().names == idx.names def test_get_unique_index(self): idx = self.index[[0, 1, 0, 1, 1, 0, 0]] expected = self.index._shallow_copy(idx[[0, 1]]) for dropna in [False, True]: result = idx._get_unique_index(dropna=dropna) assert result.unique tm.assert_index_equal(result, expected) @pytest.mark.parametrize('names', [None, ['first', 'second']]) def test_unique(self, names): mi = pd.MultiIndex.from_arrays([[1, 2, 1, 2], [1, 1, 1, 2]], names=names) res = mi.unique() exp = pd.MultiIndex.from_arrays([[1, 2, 2], [1, 1, 2]], names=mi.names) tm.assert_index_equal(res, exp) mi = pd.MultiIndex.from_arrays([list('aaaa'), list('abab')], names=names) res = mi.unique() exp = pd.MultiIndex.from_arrays([list('aa'), list('ab')], names=mi.names) tm.assert_index_equal(res, exp) mi = pd.MultiIndex.from_arrays([list('aaaa'), list('aaaa')], names=names) res = mi.unique() exp = pd.MultiIndex.from_arrays([['a'], ['a']], names=mi.names) tm.assert_index_equal(res, exp) # GH #20568 - empty MI mi = pd.MultiIndex.from_arrays([[], []], names=names) res = mi.unique() tm.assert_index_equal(mi, res) @pytest.mark.parametrize('level', [0, 'first', 1, 'second']) def test_unique_level(self, level): # GH #17896 - with level= argument result = self.index.unique(level=level) expected = self.index.get_level_values(level).unique() tm.assert_index_equal(result, expected) # With already unique level mi = pd.MultiIndex.from_arrays([[1, 3, 2, 4], [1, 3, 2, 5]], names=['first', 'second']) result = mi.unique(level=level) expected = mi.get_level_values(level) tm.assert_index_equal(result, expected) # With empty MI mi = pd.MultiIndex.from_arrays([[], []], names=['first', 'second']) result = mi.unique(level=level) expected = mi.get_level_values(level) def test_unique_datetimelike(self): idx1 = pd.DatetimeIndex(['2015-01-01', '2015-01-01', '2015-01-01', '2015-01-01', 'NaT', 'NaT']) idx2 = pd.DatetimeIndex(['2015-01-01', '2015-01-01', '2015-01-02', '2015-01-02', 'NaT', '2015-01-01'], tz='Asia/Tokyo') result = pd.MultiIndex.from_arrays([idx1, idx2]).unique() eidx1 = pd.DatetimeIndex(['2015-01-01', '2015-01-01', 'NaT', 'NaT']) eidx2 = pd.DatetimeIndex(['2015-01-01', '2015-01-02', 'NaT', '2015-01-01'], tz='Asia/Tokyo') exp =
pd.MultiIndex.from_arrays([eidx1, eidx2])
pandas.MultiIndex.from_arrays
""" Market Data Presenter. This module contains implementations of the DataPresenter abstract class, which is responsible for presenting data in the form of mxnet tensors. Each implementation presents a different subset of the available data, allowing different models to make use of similar data. """ from typing import Dict, List, Optional, Tuple from abc import abstractmethod import pandas as pd import numpy as np from mxnet import ndarray as nd from . import providers, utils class DataPresenter: """ Abstract class defining the DataProvider API. """ @abstractmethod def get_training_batch(self, size: int): """ Returns a batch of training data, partitioned from the validation data, of size +size+. """ @abstractmethod def get_validation_batch(self, size: int): """ Returns a batch of validation data, partitioned from the training data, of size +size+. """ @abstractmethod def data_array(self, timestamp: pd.Timestamp): """ Returns the data associated with a single +timestamp+ in mxnet form """ @abstractmethod def data_frame(self, timestamp: pd.Timestamp): """ Returns the data associated with a single +timestamp+ in pandas form. """ @abstractmethod def data_features(self) -> List[str]: """ Returns a list of data features in the same order as presented in the frames. """ class IntradayPresenter: """ Loads data consisting only of intraday information, guaranteed to keep all within market hours. """ # All it does is load data - no other calls necessary # pylint: disable=too-few-public-methods def __init__(self, provider: providers.DataProvider, *, window: int = 45, valid_seed: int = 0, lookahead: int = 10, normalize: bool = True, features: Dict[str, bool] = {}, **kwargs): """ Init function. Takes a +provider+ from which it extracts data and a variety of other arguments. See info files for examples. """ # pylint: disable=too-many-instance-attributes # Store basic setup parameters self.provider = provider self._window = window self._valid_seed = valid_seed self._lookahead = lookahead self._normalize = normalize self._features = [feat for feat in features if features[feat]] self._outputs = [] # Collect and decide features for feature in self._features: # First handle special features if feature == 'macd': self._outputs.append('macd_signal') if feature == 'vortex': self._outputs.extend(['vortex+', 'vortex-']) continue if feature == 'stochastic': self._outputs.extend(['%K', '%D']) continue if feature == 'williams': self._outputs.append('%R') continue if feature == 'dysart': self._outputs.extend(['pvi', 'nvi']) continue if feature == 'bollinger': self._outputs.extend(['bollinger+', 'bollinger=', 'bollinger-']) continue # Then add all others self._outputs.append(feature) # Decide range of possible dates in advance self._first = provider.first() # TODO don't limit this anymore self._latest = provider.latest() - pd.to_timedelta(2, unit='day') # Cache for already processed data to cut down on disk usage self._train_cache = {} self._val_cache = {} # Cache of holidays to prevent continuously recalculating them self._holidays = utils.trading_holidays(self._first - pd.to_timedelta(1, unit='day'), self._latest) self._half_days = utils.trading_half_days(self._first - pd.to_timedelta(1, unit='day'), self._latest) def get_training_batch(self, size: int) -> Tuple[nd.NDArray, nd.NDArray]: """ Returns a batch of training data, partitioned from the validation data, of size +size+. """ return self._get_batch(size, validation=False) def get_validation_batch(self, size: int) -> Tuple[nd.NDArray, nd.NDArray]: """ Returns a batch of validation data, partitioned from the training data, of size +size+. """ return self._get_batch(size, validation=True) def data_array(self, timestamp: pd.Timestamp) -> nd.NDArray: """ Returns the data associated with a single +timestamp+ in mxnet form """ start_time = timestamp - pd.to_timedelta(self._window, unit='min') return self._get_data(start_time, False)[0] @abstractmethod def data_frame(self, timestamp: pd.Timestamp): """ Returns the data associated with a single +timestamp+ in pandas form. """ data = self._extract_daily_data(timestamp) if data is None: return None return data.loc[timestamp, :] def _get_data(self, time: pd.Timestamp, validation: bool) \ -> Tuple[nd.NDArray, nd.NDArray]: """ Returns a simgle data sample starting at a given +time+. Uses +validation+ to distinguish between training and validation sets. NOTE: This function assumes that the entire data window is available. If a time provided is too late to obtain a full window, behavior is UNPREDICTABLE. """ # Check if the sample has already been cached. day = time.floor('D') start_index = (time.hour - 9) * 60 + (time.minute - 30) end_index = start_index + self._window if validation and day in self._val_cache: data, target = self._val_cache[day] return data[start_index: end_index], target[start_index: end_index] if not validation and day in self._train_cache: data, target = self._train_cache[day] return data[start_index: end_index], target[start_index: end_index] # Otherwase generate, cache, and return it data, target = self._to_daily_input_data(day) if validation: self._val_cache[day] = (data, target) else: self._train_cache[day] = (data, target) return data[start_index: end_index], target[start_index: end_index] def _to_daily_input_data(self, date: pd.Timestamp) \ -> Tuple[nd.NDArray, nd.NDArray]: """ Transforms a set of intraday data for a +date+ to an array appropriate for input to the model, and a target set of predictions against which to compare outputs. """ # Gather data requested data components. Note that this seemingly # over-complicated method guarantees that they remain in the order # prescribed by the feature list. datas = [] for feat in self._outputs: if feat == "high": datas.append(_to_intraday_high(date, self.provider, normalize=self._normalize)) elif feat == "low": datas.append(_to_intraday_low(date, self.provider, normalize=self._normalize)) elif feat == "change": datas.append(_to_intraday_change(date, self.provider, normalize=self._normalize)) elif feat == "open": datas.append(_to_intraday_open(date, self.provider, normalize=self._normalize)) elif feat == "volume": datas.append(_to_intraday_volume(date, self.provider, normalize=self._normalize)) elif feat == "time": datas.append(_to_intraday_time(date, self.provider, normalize=self._normalize)) elif feat == "macd": # For MACD, include both MACD and its signal macd, macd_signal = _to_intraday_macd(date, self.provider, normalize=self._normalize) datas.extend([macd_signal, macd]) elif feat == "mass_index": datas.append(_to_intraday_mass_index(date, self.provider)) elif feat == "trix15": datas.append(_to_intraday_trix(date, self.provider, 15)) elif feat == "vortex+": vortex_up, vortex_down = _to_intraday_vortex(date, self.provider, 25) datas.extend([vortex_up, vortex_down]) elif feat == "%K": pK, pD = _to_intraday_stochastic(date, self.provider, 30) datas.extend([pK, pD]) elif feat == "rsi": datas.append(_to_intraday_rsi(date, self.provider, 14)) elif feat == "%R": # The Williams %R is mathematically equivalent to (1 - %K). It # is duplicated here to obtain a shorter period. pK, _ = _to_intraday_stochastic(date, self.provider, 10) datas.append(pK - 1) elif feat == "accdist": datas.append(_to_intraday_accdist(date, self.provider)) elif feat == "mfi": datas.append(_to_intraday_mfi(date, self.provider, 30)) elif feat == "vpt": datas.append(_to_intraday_vpt(date, self.provider)) elif feat == "obv": datas.append(_to_intraday_obv(date, self.provider)) elif feat == "pvi": pvi, nvi = _to_intraday_dysart(date, self.provider) datas.extend([pvi, nvi]) elif feat == "bollinger+": b_top, b_mid, b_bottom = _to_intraday_bollinger(date, self.provider, 30, 2) datas.extend([b_top, b_mid, b_bottom]) elif feat == "ultimate": datas.append(_to_intraday_ultimate(date, self.provider)) elif feat == "cci": datas.append(_to_intraday_cci(date, self.provider)) elif feat == "target": datas.append(_to_intraday_target(date, self.provider, self._lookahead, normalize=self._normalize)) # Gather target data and return data/target arrays target = _to_intraday_target(date, self.provider, self._lookahead, normalize=self._normalize) return nd.stack(*datas, axis=1), target.reshape(-1, 1) def _extract_daily_data(self, date: pd.Timestamp) -> Optional[pd.DataFrame]: """ Gets the market data for a given day, restricted to market hours. """ data = self.provider.intraday(date) if data is None or data.empty: return None return data def _get_batch(self, batch_size: int, validation: bool = False) \ -> Tuple[nd.NDArray, nd.NDArray]: """ Gets a random batch of data of size +batch_size+. Returns a tuple of data and target predictions. If +validation+ is set, prevents these dates from being drawn for non-validation batches. """ # Define a Callable for testing appropriate dates def _is_suitable_time(time: pd.Timestamp) -> bool: """ Returns whether the market is open at a given +time+ for the required window. """ # First, confirm that this date matches the right type day = time.floor(freq='D') is_validation_date = (day.dayofyear % 10 == self._valid_seed) if validation != is_validation_date: return False # Ensure it's on weekdays and during market hours. Note that we # discard the last 10 minutes of trading because they are both # dangerous for day trading and provide no good way to train the # 10 minute output for the model. if time.weekday() > 4: return False if (time.hour * 60 + time.minute) < 9 * 60 + 30: return False if (time.hour * 60 + time.minute + self._window) > 15 * 60 - self._lookahead: return False # Check aginst holidays. Note that for the sake of sanity, we # don't include half days. if day in self._holidays or day in self._half_days: return False return True # Next, generate arrays of random dates within the last two years, # recording appropriate ones to form an array of size +batch_size+ timestamps = pd.Series() while True: random_times = pd.to_datetime(np.random.randint(low=self._first.value, high=self._latest.value, size=(100), dtype='int64')).to_series() suitable_mask = random_times.apply(_is_suitable_time) timestamps = pd.concat([timestamps, random_times.loc[suitable_mask]]) if len(timestamps) >= batch_size: timestamps = timestamps[0 : batch_size] break index_array = pd.to_datetime(timestamps) # Next, gather all data into batches with axes (batch, window, data...) datas, targets = [], [] for timestamp in index_array: data, target = self._get_data(timestamp, validation) datas.append(data) targets.append(target) data_array, target_array = nd.stack(*datas), nd.stack(*targets) # Return the data return data_array, target_array def data_features(self) -> List[str]: """ Returns a list of data features in the same order as presented in the frames. """ return self._outputs def _get_intraday_data(date: pd.Timestamp, provider: providers.DataProvider) \ -> pd.DataFrame: """ Gets the intraday datafrome limited to market hours for a given +date+ and +provider+. """ # First, get data and limit it to market hours data = provider.intraday(date) if data is None or data.empty: raise RuntimeError(f"Something went wrong - empty data array for {date}!") start = data.index[0].replace(hour=9, minute=30) end = data.index[0].replace(hour=16, minute=0) # Next, resample the data by the minute and interpolate missing values data = data.loc[data.index.isin(pd.date_range(start=start, end=end, freq='min'))] data = data.resample('min') data = data.interpolate(method='time').copy() return data def _to_intraday_high(date: pd.Timestamp, provider: providers.DataProvider, normalize: bool = True) -> nd.NDArray: """ Returns an ndarray consisting of the per-minute high of a data series for a given +date+ and +provider+. If +normalize+, it is divided by the open price. """ data = _get_intraday_data(date, provider) high = ((data.high - data.open) / data.open) if normalize else data.high return nd.array(high.values, utils.try_gpu(0)) def _to_intraday_low(date: pd.Timestamp, provider: providers.DataProvider, normalize: bool = True) -> nd.NDArray: """ Returns an ndarray consisting of the per-minute high of a data series for a given +date+ and +provider+. If +normalize+, it is divided by the open price. """ data = _get_intraday_data(date, provider) low = ((data.low - data.open) / data.open) if normalize else data.low return nd.array(low.values, utils.try_gpu(0)) def _to_intraday_change(date: pd.Timestamp, provider: providers.DataProvider, normalize: bool = True) -> nd.NDArray: """ Returns an ndarray consisting of the per-minute close of a data series for a given +date+ and +provider+. If +normalize+, it is divided by the previous close """ data = _get_intraday_data(date, provider) close_prev = data.close.shift(periods=1, fill_value=data.close[0]) close = ((data.close - close_prev) / close_prev) if normalize else data.close return nd.array(close.values, utils.try_gpu(0)) def _to_intraday_open(date: pd.Timestamp, provider: providers.DataProvider, normalize: bool = True) -> nd.NDArray: """ Returns an ndarray consisting of the per-minute open of a data series for a given +date+ and +provider+. If +normalize+, it is divided by the daily open price. """ data = _get_intraday_data(date, provider) open = (data.open / data.open.iloc[0]) if normalize else data.open return nd.array(open.values, utils.try_gpu(0)) def _to_intraday_volume(date: pd.Timestamp, provider: providers.DataProvider, normalize: bool = True) -> nd.NDArray: """ Returns an ndarray consisting of the per-minute high of a data series for a given +date+ and +provider+. If +normalize+, it is divided by the average volume. """ data = _get_intraday_data(date, provider) vol = data.volume / data.volume.mean() if normalize else data.volume return nd.array(vol.values, utils.try_gpu(0)) def _to_intraday_time(date: pd.Timestamp, provider: providers.DataProvider, normalize: bool = True) -> nd.NDArray: """ Returns an ndarray consisting of the trading minute of a data series for a given +date+ and +provider+. If +normalize+, it is normalized so that 9:30 is 0 and 16:00 is 1 """ data = _get_intraday_data(date, provider) minute = data.index.hour * 60 + data.index.minute - (9 * 60 + 30) tempus = (minute / (60 * 7 + 30)) if normalize else minute return nd.array(tempus.values, utils.try_gpu(0)) def _to_intraday_macd(date: pd.Timestamp, provider: providers.DataProvider, normalize: bool = True) -> Tuple[nd.NDArray, nd.NDArray]: """ Returns a pair of ndarrays consisting of the per-minute MACD of a data series for a given +date+ and +provider+, and a signal for the same. If normalize+, both are divided by the daily open price. """ # First, calculate the MACD via exponential moving averages data = _get_intraday_data(date, provider) ewm12 =
pd.Series.ewm(data['close'], span=12)
pandas.Series.ewm
#!/usr/bin/env python3 __author__ = "<EMAIL>" import os import os.path import sys import subprocess import argparse import datetime import epiweeks import pandas as pd import numpy as np def load_data(assemblies_tsv, collab_tsv, min_unambig, min_date, max_date): df_assemblies = pd.read_csv(assemblies_tsv, sep='\t').dropna(how='all') if collab_tsv and os.path.isfile(collab_tsv) and os.path.getsize(collab_tsv): collab_ids = pd.read_csv(collab_tsv, sep='\t').dropna(how='all')[list(['external_id', 'collaborator_id'])] collab_ids.columns = ['sample', 'collaborator_id'] else: collab_ids = None # format dates properly df_assemblies = df_assemblies.loc[ ~df_assemblies['run_date'].isna() & ~df_assemblies['collection_date'].isna() & (df_assemblies['run_date'] != 'missing') & (df_assemblies['collection_date'] != 'missing')] df_assemblies = df_assemblies.astype({'collection_date':'datetime64[D]','run_date':'datetime64[D]'}) # fix vadr_num_alerts df_assemblies = df_assemblies.astype({'vadr_num_alerts':'Int64'}) # remove columns with File URIs cols_unwanted = [ 'assembly_fasta','coverage_plot','aligned_bam','replicate_discordant_vcf', 'variants_from_ref_vcf','nextclade_tsv','nextclade_json', 'pangolin_csv','vadr_tgz','vadr_alerts', ] cols_unwanted = list(c for c in cols_unwanted if c in df_assemblies.columns) df_assemblies.drop(columns=cols_unwanted, inplace=True) # subset by date range if min_date: df_assemblies = df_assemblies.loc[~df_assemblies['run_date'].isna() & (np.datetime64(min_date) <= df_assemblies['run_date'])] if max_date: df_assemblies = df_assemblies.loc[~df_assemblies['run_date'].isna() & (df_assemblies['run_date'] <= np.datetime64(max_date))] # fix missing data in purpose_of_sequencing df_assemblies.loc[:,'purpose_of_sequencing'] = df_assemblies.loc[:,'purpose_of_sequencing'].fillna('Missing').replace('', 'Missing') # derived column: genome_status if 'genome_status' not in df_assemblies.columns: df_assemblies.loc[:,'genome_status'] = list( 'failed_sequencing' if df_assemblies.loc[id, 'assembly_length_unambiguous'] < min_unambig else 'failed_annotation' if df_assemblies.loc[id, 'vadr_num_alerts'] > 0 else 'submittable' for id in df_assemblies.index) # derived columns: geo_country, geo_state, geo_locality if 'geo_country' not in df_assemblies.columns: df_assemblies.loc[:,'geo_country'] = list(g.split(': ')[0] if not pd.isna(g) else '' for g in df_assemblies.loc[:,'geo_loc_name']) if 'geo_state' not in df_assemblies.columns: df_assemblies.loc[:,'geo_state'] = list(g.split(': ')[1].split(', ')[0] if not pd.isna(g) else '' for g in df_assemblies.loc[:,'geo_loc_name']) if 'geo_locality' not in df_assemblies.columns: df_assemblies.loc[:,'geo_locality'] = list(g.split(': ')[1].split(', ')[1] if not pd.isna(g) and ', ' in g else '' for g in df_assemblies.loc[:,'geo_loc_name']) # derived columns: collection_epiweek, run_epiweek if 'collection_epiweek' not in df_assemblies.columns: df_assemblies.loc[:,'collection_epiweek'] = list(epiweeks.Week.fromdate(x) if not pd.isna(x) else x for x in df_assemblies.loc[:,'collection_date']) if 'run_epiweek' not in df_assemblies.columns: df_assemblies.loc[:,'run_epiweek'] = list(epiweeks.Week.fromdate(x) if not pd.isna(x) else x for x in df_assemblies.loc[:,'run_date']) if 'collection_epiweek_end' not in df_assemblies.columns: df_assemblies.loc[:,'collection_epiweek_end'] = list(x.enddate().strftime('%Y-%m-%d') if not pd.isna(x) else '' for x in df_assemblies.loc[:,'collection_epiweek']) if 'run_epiweek_end' not in df_assemblies.columns: df_assemblies.loc[:,'run_epiweek_end'] = list(x.enddate().strftime('%Y-%m-%d') if not pd.isna(x) else '' for x in df_assemblies.loc[:,'run_epiweek']) # derived column: sample_age_at_runtime if 'sample_age_at_runtime' not in df_assemblies.columns: df_assemblies.loc[:,'sample_age_at_runtime'] = list(x.days for x in df_assemblies.loc[:,'run_date'] - df_assemblies.loc[:,'collection_date']) # join column: collaborator_id if collab_ids is not None: df_assemblies = df_assemblies.merge(collab_ids, on='sample', how='left', validate='one_to_one') return df_assemblies def main(args): df_assemblies = load_data(args.assemblies_tsv, args.collab_tsv, args.min_unambig, args.min_date, args.max_date) states_all = list(str(x) for x in df_assemblies['geo_state'].unique() if x and not pd.isna(x)) collaborators_all = list(str(x) for x in df_assemblies['collected_by'].unique() if x and not
pd.isna(x)
pandas.isna
# -*- coding: utf-8 -*- import codecs import re import pandas as pd import argparse from collections import defaultdict import sys import os # gather arguments parser = argparse.ArgumentParser( description="Extract tabular paradigms from annotated templates." ) parser.add_argument( "-candidates_dir", action="store", dest="candidates_dir", help="Location of candidate html pages.", ) parser.add_argument( "-annotation_dir", action="store", dest="annotation_dir", help="Location of raw/annotated table templates.", ) parser.add_argument( "-language", action="store", dest="language", help="Language to grab." ) args = parser.parse_args() # regular expressions lempat = r"<h1.*?>(.*?)</h1>" locpat1 = r"</h2>.*?</h2>" locpat2 = r"</h2>.*?</body>" pospat = r">(.*?)</h3>" # input tables orig_dir = os.path.join( args.annotation_dir, "raw_tables/" ) # original example tables for comparison #CHANGE done_dir = os.path.join( args.annotation_dir, "annotated_tables/" ) # annotated example tables #CHANGE # output directory out_dir = "./tabular_results/" # output data goes here if not os.path.exists(out_dir): os.makedirs(out_dir) # language language = args.language # output file fout_name = out_dir + language + "_tabular_paradigms.txt" fout = codecs.open(fout_name, "wb", "utf-8") # get the table patterns n_tables = {} v_tables = {} adj_tables = {} # loop through annotated directory for n in os.listdir(done_dir + language): if n.endswith("example.csv"): mod_set = {} try: odata = pd.read_csv(orig_dir + language + "/" + n, dtype="unicode").fillna( "" ) ddata = pd.read_csv(done_dir + language + "/" + n, dtype="unicode").fillna( "" ) except: print(n) raise try: assert odata.shape == ddata.shape # make sure we really got the same table except: print(n) print(odata) print(ddata) print(odata.shape) print(ddata.shape) raise for i in range(odata.shape[0]): for j in range(odata.shape[1]): if odata.iloc[i, j] != ddata.iloc[i, j]: mod_set[(i, j)] = ddata.iloc[i, j] # if there were some actual annotations store them if len(mod_set) > 0: if n.startswith("N_"): n_tables[odata.shape] = mod_set if n.startswith("ADJ_"): adj_tables[odata.shape] = mod_set if n.startswith("V_"): v_tables[odata.shape] = mod_set # #loop through languages lnames = os.listdir(args.candidates_dir) # CHANGE for ln in lnames: if ln == language: names = os.listdir(os.path.join(args.candidates_dir, ln)) # CHANGE # loop through language pages # count = 0 for n in names: # if n.startswith('candidate_33623.html'): if n.startswith("candidate"): fin = codecs.open( os.path.join(args.candidates_dir, ln, n), "rb", "utf-8" ) # CHANGE page = fin.read().replace("<br>", "|") fin.close() # get the lemma from the page match = re.search(lempat, page, flags=re.U | re.DOTALL) if match: lemma = match.group(1) # print lemma # adjectives match = re.search(ln + locpat1, page, flags=re.U | re.DOTALL) if not match: match = re.search(ln + locpat2, page, flags=re.U | re.DOTALL) if match: text = match.group() if u"Adjective</h3" in text: try: data = pd.read_html(text) if len(data) >= 1: data = pd.concat(data) shape = data.shape if shape in adj_tables: for mod, feats in adj_tables[shape].items(): word = data.iloc[mod[0], mod[1]] if not pd.isnull(word): fout.write( lemma + "\t" + word + "\t" + feats + "\n" ) fout.write("\n") except: # if data.shape == (6,8): # print data # raise fout.write("----\t----\t----\n") fout.write("\n") pass # nouns match = re.search(ln + locpat1, page, flags=re.U | re.DOTALL) if not match: match = re.search(ln + locpat2, page, flags=re.U | re.DOTALL) if match: text = match.group() if u"Noun</h3>" in text: try: data = pd.read_html(text) if len(data) >= 1: data = pd.concat(data) shape = data.shape # SOME RUSSIAN HACKING if language == "Russian" and lemma == u"дом": print(data) print(shape) print(n) # END RUSSIAN HACKING # SOME ARMENIAN HACKING if language == "Armenian" and shape == (22, 3): if data.iloc[1, 1] == "singular": shape = (23, 3) # if 'Audio' in data.iloc[] # SOME HUNGARIAN HACKING if language == "Hungarian": if data.iloc[2, 1] == "singular": shape = (30, 3) # END ARMENIAN HACKING if shape in n_tables: for mod, feats in n_tables[shape].items(): word = data.iloc[mod[0], mod[1]] # TEMPORARY ARMENIAN HACK # if word == 'plural': # print data.iloc[1,1] # print data.shape # END TEMPORARY ARMENIAN HACK # data.to_csv('armenian_tmp.csv',encoding='utf-8',index=False) if not pd.isnull(word): fout.write( lemma + "\t" + word + "\t" + feats + "\n" ) fout.write("\n") except: # raise fout.write("----\t----\t----\n") fout.write("\n") # raise pass # verbs match = re.search(ln + locpat1, page, flags=re.U | re.DOTALL) if not match: match = re.search(ln + locpat2, page, flags=re.U | re.DOTALL) if match: text = match.group() if u"Verb</h3>" in text: try: data = pd.read_html(text) if len(data) >= 1: data = pd.concat(data) shape = data.shape # SOME RUSSIAN HACKING if language == "Russian" and lemma == u"дом": print(data) print(shape) print(n) # END RUSSIAN HACKING # SPANISH HACK START if language == "Spanish" and lemma == "hablar": shape = (23, 8) # SPANISH HACK END if shape in v_tables: for mod, feats in v_tables[shape].items(): word = data.iloc[mod[0], mod[1]] if not
pd.isnull(word)
pandas.isnull
""" test partial slicing on Series/Frame """ import pytest from datetime import datetime, date import numpy as np import pandas as pd import operator as op from pandas import (DatetimeIndex, Series, DataFrame, date_range, Index, Timedelta, Timestamp) from pandas.util import testing as tm class TestSlicing(object): def test_slice_year(self): dti = DatetimeIndex(freq='B', start=datetime(2005, 1, 1), periods=500) s = Series(np.arange(len(dti)), index=dti) result = s['2005'] expected = s[s.index.year == 2005] tm.assert_series_equal(result, expected) df = DataFrame(np.random.rand(len(dti), 5), index=dti) result = df.loc['2005'] expected = df[df.index.year == 2005] tm.assert_frame_equal(result, expected) rng = date_range('1/1/2000', '1/1/2010') result = rng.get_loc('2009') expected = slice(3288, 3653) assert result == expected def test_slice_quarter(self): dti = DatetimeIndex(freq='D', start=datetime(2000, 6, 1), periods=500) s = Series(np.arange(len(dti)), index=dti) assert len(s['2001Q1']) == 90 df = DataFrame(np.random.rand(len(dti), 5), index=dti) assert len(df.loc['1Q01']) == 90 def test_slice_month(self): dti = DatetimeIndex(freq='D', start=datetime(2005, 1, 1), periods=500) s = Series(np.arange(len(dti)), index=dti) assert len(s['2005-11']) == 30 df = DataFrame(np.random.rand(len(dti), 5), index=dti) assert len(df.loc['2005-11']) == 30 tm.assert_series_equal(s['2005-11'], s['11-2005']) def test_partial_slice(self): rng = DatetimeIndex(freq='D', start=datetime(2005, 1, 1), periods=500) s = Series(np.arange(len(rng)), index=rng) result = s['2005-05':'2006-02'] expected = s['20050501':'20060228']
tm.assert_series_equal(result, expected)
pandas.util.testing.assert_series_equal
from pathlib import Path import fiona # noqa from geopandas import GeoDataFrame import pandas as pd from pandas import DataFrame import pytest from shapely import wkt @pytest.fixture(scope='session') def fixtures_path(): return Path(__file__).parent / 'fixtures' @pytest.fixture(scope='session') def counties(fixtures_path: Path) -> DataFrame: dataframe = pd.read_csv(fixtures_path / 'counties.csv', parse_dates=['date']) dataframe['annotation'] = dataframe['annotation'].astype('object') return dataframe @pytest.fixture(scope='session') def counties_points(fixtures_path: Path) -> DataFrame: dataframe = pd.read_csv(fixtures_path / 'counties_points.csv', parse_dates=['date']) dataframe['annotation'] = dataframe['annotation'].astype('object') dataframe['geometry'] = dataframe['geometry'].map(wkt.loads) geodataframe = GeoDataFrame(dataframe, geometry='geometry') dataframe = DataFrame(geodataframe) return dataframe @pytest.fixture(scope='session') def counties_polygons(fixtures_path: Path) -> DataFrame: dataframe =
pd.read_csv(fixtures_path / 'counties_polygons.csv', parse_dates=['date'])
pandas.read_csv
## Functions to support SPEI drought index analysis ## Code: EHU | SPEI data: SC ## 12 Sept 2019 import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import cm from datetime import date import collections ## Constants associated with this analysis yrs = np.linspace(1900, 2101, num=2412) model_names = ['CanESM2', 'CCSM4', 'CNRM-CM5', 'CSIRO-Mk3-6-0', 'GISS-E2-R', 'INMCM4', 'MIROC-ESM', 'NorESM1-M'] # all models used in comparison scenarios = ['Rcp4p5', 'Rcp8p5'] # climate scenarios basin_names = ['INDUS','TARIM','BRAHMAPUTRA','ARAL SEA','COPPER','GANGES','YUKON','ALSEK','SUSITNA','BALKHASH','STIKINE','SANTA CRUZ', 'FRASER','BAKER','YANGTZE','SALWEEN','COLUMBIA','ISSYK-KUL','AMAZON','COLORADO','TAKU','MACKENZIE','NASS','THJORSA','JOEKULSA A F.', 'KUSKOKWIM','RHONE','SKEENA','OB','OELFUSA','MEKONG','DANUBE','NELSON RIVER','PO','KAMCHATKA','RHINE','GLOMA','HUANG HE','INDIGIRKA', 'LULE','RAPEL','SANTA','SKAGIT','KUBAN','TITICACA','NUSHAGAK','BIOBIO','IRRAWADDY','NEGRO','MAJES','CLUTHA','DAULE-VINCES', 'KALIXAELVEN','MAGDALENA','DRAMSELV','COLVILLE'] def plot_basin_runmean(basin_id, permodel_dict, which='diff', window_yrs=30, cmap_name='viridis', show_labels=True, show_plot=True, save_plot=False, output_tag=None, ax=None, shade_axis=True): """Make a plot of running mean difference in SPEI for a given basin, comparing across models. Arguments: basin_id: integer, index of basin in the standard list "basin_names" permodel_dict: dictionary storing SPEI per model, with the structure dict[modelname]['diff'/'WRunoff'/'NRunoff'][basinname] = basin difference in SPEI for this model which: string identifying 'WRunoff' (with glacial runoff), 'NRunoff' (no runoff), or 'diff' (their difference) window_yrs: number of years to consider in running average. Default 30 cmap_name: name of matplotlib colormap from which to select line colors. Default 'viridis' show_plot: Boolean, whether to show the resulting plot. Default True save_plot: Boolean, whether to save the plot in the working directory. Default False output_tag: anything special to note in output filename, e.g. global settings applied. Default None will label 'default' ax: Axes instance on which to plot. Default None will set up a new instance shade_axis: Boolean, whether to shade regions for which the running window includes years before the glacier model switch-on """ window_size = 12 * window_yrs # size of window given monthly data basin_runavg_bymodel = [np.convolve(permodel_dict[m][which][basin_id], np.ones((window_size,))/window_size, mode='valid') for m in model_names] #compute running means colors = cm.get_cmap(cmap_name)(np.linspace(0, 1, num=len(model_names))) styles = ('-',':') if ax is None: fig, ax = plt.subplots() # create Axes instance if needed if shade_axis: cutoff_year = 1980 + window_yrs/2 ax.axvspan(1900, cutoff_year, color='Grey', alpha=0.3) for k,m in enumerate(model_names): ax.plot(yrs[(window_size/2):-(window_size/2 -1)], basin_runavg_bymodel[k], label=m, color=colors[k], ls=styles[np.mod(k, len(styles))], linewidth=2.0) ax.tick_params(axis='both', labelsize=14) ax.set(xlim=(1900,2100), xticks=[1900,1950, 2000, 2050, 2100]) if show_labels: ax.set_xlabel('Years', fontsize=16) ax.set_ylabel('Mean SPEI {}'.format(which), fontsize=16) ax.set_title('{} year running mean, {} case, {} basin'.format(window_yrs, which, basin_names[basin_id]), fontsize=18) ax.legend(loc='best') plt.tight_layout() if save_plot: if output_tag is None: output_tag='default' plt.savefig(fname='{}yr_runmean-{}-{}_basin-{}-{}.png'.format(window_yrs, which, basin_names[basin_id], output_tag, date.today())) if show_plot: plt.show() def plot_runmean_comparison(basin_id, permodel_dict, window_yrs=30, cmaps=('Blues', 'Wistia'), show_labels=True, show_plot=True, save_plot=False, output_tag=None, ax=None): """Make a plot comparing running-average model projections of SPEI with and without glacial runoff. Arguments: basin_id: integer, index of basin in the standard list "basin_names" permodel_dict: dictionary storing SPEI per model, with the structure dict[modelname]['diff'/'WRunoff'/'NRunoff'][basinname] = basin difference in SPEI for this model window_yrs: number of years to consider in running average. Default 30 cmaps: tuple (str, str) of matplotlib colormap names from which to select line colors for each case. Default ('Blues', 'Greys') show_plot: Boolean, whether to show the resulting plot. Default True save_plot: Boolean, whether to save the plot in the working directory. Default False output_tag: anything special to note, e.g. global settings applied. Default None will label 'default' ax: Axes instance on which to plot. Default None will set up a new instance """ window_size = 12 * window_yrs # size of window given monthly data basin_runavg_w = [np.convolve(permodel_dict[m]['WRunoff'][basin_id], np.ones((window_size,))/window_size, mode='valid') for m in model_names] #compute running means basin_runavg_n = [np.convolve(permodel_dict[m]['NRunoff'][basin_id], np.ones((window_size,))/window_size, mode='valid') for m in model_names] #compute running means colors_w = cm.get_cmap(cmaps[0])(np.linspace(0.2, 1, num=len(model_names))) colors_n = cm.get_cmap(cmaps[1])(np.linspace(0.2, 1, num=len(model_names))) if ax is None: fig, ax = plt.subplots() ax.axhline(y=0, color='Gainsboro', linewidth=2.0) for k,m in enumerate(model_names): ax.plot(yrs[(window_size/2):-(window_size/2 -1)], basin_runavg_w[k], label=m, color=colors_w[k], linewidth=2.0) ax.plot(yrs[(window_size/2):-(window_size/2 -1)], basin_runavg_n[k], ls='-.', color=colors_n[k], linewidth=2.0) ax.tick_params(axis='both', labelsize=14) ax.set(xlim=(1900,2100), xticks=[1900,1950, 2000, 2050, 2100]) if show_labels: ax.set_xlabel('Years', fontsize=16) ax.set_ylabel('SPEI', fontsize=16) ax.set_title('{} year running average trajectories, {} basin'.format(window_yrs, basin_names[basin_id]), fontsize=18) ax.legend(loc='best') plt.tight_layout() if save_plot: if output_tag is None: output_tag='default' plt.savefig(fname='{}yr_runmean_comp-{}_basin-{}-{}.png'.format(window_yrs, basin_names[basin_id], output_tag, date.today())) if show_plot: plt.show() def plot_basin_runvar(basin_id, permodel_dict, which='diff', window_yrs=30, cmaps='viridis', show_labels=True, show_plot=True, save_plot=False, output_tag=None, ax=None, shade_axis=True): """Make a plot comparing running-average model projections of SPEI with and without glacial runoff. Arguments: basin_id: integer, index of basin in the standard list "basin_names" permodel_dict: dictionary storing SPEI per model, with the structure dict[modelname]['diff'/'WRunoff'/'NRunoff'][basinname] = basin difference in SPEI for this model window_yrs: number of years to consider in running average. Default 30 cmaps: tuple (str, str) of matplotlib colormap names from which to select line colors for each case. Default ('Blues', 'Greys') show_plot: Boolean, whether to show the resulting plot. Default True save_plot: Boolean, whether to save the plot in the working directory. Default False output_tag: anything special to note, e.g. global settings applied. Default None will label 'default' ax: Axes instance on which to plot. Default None will set up a new instance shade_axis: Boolean, whether to shade regions for which the running window includes years before the glacier model switch-on """ basin_dict = {m: {'NRunoff': [], 'WRunoff': [], 'diff': []} for m in model_names} varwindow = 12*window_yrs # number of months to window in rolling variance for m in model_names: nr = pd.Series(permodel_dict[m]['NRunoff'][basin_id]) wr = pd.Series(permodel_dict[m]['WRunoff'][basin_id]) basin_dict[m]['NRunoff'] = nr.rolling(window=varwindow).var() basin_dict[m]['WRunoff'] = wr.rolling(window=varwindow).var() basin_dict[m]['diff'] = basin_dict[m]['WRunoff'] - basin_dict[m]['NRunoff'] colors = cm.get_cmap(cmaps)(np.linspace(0.2, 1, num=len(model_names))) styles = ('-',':') if ax is None: fig, ax = plt.subplots() ax.axhline(y=0, color='Gainsboro', linewidth=2.0) if shade_axis: cutoff_year = 1980 + window_yrs/2 ax.axvspan(1900, cutoff_year, color='Grey', alpha=0.3) for k,m in enumerate(model_names): ax.plot(yrs, basin_dict[m][which], label=m, color=colors[k], ls=styles[np.mod(k, len(styles))], linewidth=2.0) ax.tick_params(axis='both', labelsize=14) ax.set(xlim=(1900,2100), xticks=[1900,1950, 2000, 2050, 2100]) if show_labels: ax.set_xlabel('Years', fontsize=16) ax.set_ylabel('SPEI variance {}'.format(which), fontsize=16) ax.set_title('{} year running variance by model, {} case, {} basin'.format(window_yrs, which, basin_names[basin_id]), fontsize=18) ax.legend(loc='best') plt.tight_layout() if save_plot: if output_tag is None: output_tag='default' plt.savefig(fname='{}yr_runvar-{}-{}_basin-{}-{}.png'.format(window_yrs, which, basin_names[basin_id], output_tag, date.today())) if show_plot: plt.show() def glacial_meandiff(permodel_dict, years=(2070, 2100), return_range=True): """Calculate the difference in 30-yr mean SPEI with vs. without runoff Arguments: permodel_dict: dictionary storing SPEI per model, with the structure dict[modelname]['WRunoff'/'NRunoff'][basinname] = basin difference in SPEI for this model years: what years of scenario to examine. Default (2070, 2100) return_range: whether to return low/high multi-model range. Default True Outputs: median difference in mean(WRunoff)-mean(NRunoff) range in mean difference, expressed as 2xN array of (median-low, high-meadian) for errorbar plotting """ idx_i, idx_f = 12*np.array((years[0]-1900, years[1]-1899)) #add 12 months to last year so that calculation goes for all 12 months bas_glac_meanmed = [] bas_glac_lowmeans = [] bas_glac_highmeans = [] for i in range(len(basin_names)): bmeans_n = [np.nanmean(permodel_dict[m]['NRunoff'][i][idx_i:idx_f]) for m in model_names] bmeans_g = [np.nanmean(permodel_dict[m]['WRunoff'][i][idx_i:idx_f]) for m in model_names] basin_glacial_meanshift = np.array(bmeans_g) - np.array(bmeans_n) bas_glac_meanmed.append(np.nanmedian(basin_glacial_meanshift)) bas_glac_lowmeans.append(np.nanmedian(basin_glacial_meanshift) - np.nanmin(basin_glacial_meanshift)) bas_glac_highmeans.append(np.nanmax(basin_glacial_meanshift) - np.nanmedian(basin_glacial_meanshift)) mean_spread = np.stack((bas_glac_lowmeans, bas_glac_highmeans)) if return_range: return bas_glac_meanmed, mean_spread else: return bas_glac_meanmed def glacial_vardiff(permodel_dict, years=(2070, 2100), return_range=True): """Calculate the difference in 30-yr SPEI variance with vs. without runoff Arguments: permodel_dict: dictionary storing SPEI per model, with the structure dict[modelname]['WRunoff'/'NRunoff'][basinname] = basin difference in SPEI for this model years: what years of scenario to examine. Default (2070, 2100) return_range: whether to return low/high multi-model range. Default True Outputs: median difference in var(WRunoff)-var(NRunoff) range in variance difference, expressed as 2xN array of (median-low, high-meadian) for errorbar plotting """ idx_i, idx_f = 12*np.array((years[0]-1900, years[1]-1899)) #add 12 months to last year so that calculation goes for all 12 months bas_glac_varmed = [] bas_glac_lowvars = [] bas_glac_highvars = [] for i in range(len(basin_names)): bvar_n = [np.nanvar(permodel_dict[m]['NRunoff'][i][idx_i:idx_f]) for m in model_names] bvar_g = [np.nanvar(permodel_dict[m]['WRunoff'][i][idx_i:idx_f]) for m in model_names] basin_glacial_varshift = np.array(bvar_g) - np.array(bvar_n) bas_glac_varmed.append(np.nanmedian(basin_glacial_varshift)) bas_glac_lowvars.append(np.nanmedian(basin_glacial_varshift) - np.nanmin(basin_glacial_varshift)) bas_glac_highvars.append(np.nanmax(basin_glacial_varshift) - np.nanmedian(basin_glacial_varshift)) var_spread = np.stack((bas_glac_lowvars, bas_glac_highvars)) if return_range: return bas_glac_varmed, var_spread else: return bas_glac_varmed ## New functions to produce multi-GCM ensemble plots -- added 27 Apr 2020 def sort_models_to_basins(permodel_dict, cases_included=['NRunoff', 'WRunoff', 'diff']): """Re-format a dictionary loaded in by GCM to be sorted by basin name first. Facilitates multi-GCM ensemble estimates for each basin. Parameters ---------- permodel_dict : DICT Stores SPEI per model, with the structure dict[modelname]['WRunoff'/'NRunoff'][basinname] = basin SPEI for this model and case cases_included : LIST of STR Names cases 'WRunoff' (with glacial runoff), 'NRunoff' (no glacial runoff), 'diff' (their difference) included in input/output Returns ------- perbasin_dict: DICT Stores SPEI per basin """ cases = cases_included # inclusion of glacier runoff SPEI_by_basin = {b: {} for b in basin_names} # create dictionary indexed by basin name for i, b in enumerate(basin_names): SPEI_by_basin[b] = {case: {} for case in cases} for case in cases: tempdict = {} for m in model_names: tempdict[m] = permodel_dict[m][case][i] # pull data from SPEI_by_model into this new dict SPEI_by_basin[b][case] =
pd.DataFrame.from_dict(tempdict)
pandas.DataFrame.from_dict
import os, datetime import csv import pycurl import sys import shutil from openpyxl import load_workbook import pandas as pd import download.box from io import BytesIO import numpy as np from download.box import LifespanBox verbose = True snapshotdate = datetime.datetime.today().strftime('%m_%d_%Y') box_temp='/home/petra/UbWinSharedSpace1/boxtemp' #location of local copy of curated data box = LifespanBox(cache=box_temp) redcapconfigfile="/home/petra/UbWinSharedSpace1/ccf-nda-behavioral/PycharmToolbox/.boxApp/redcapconfig.csv" studyids=box.getredcapids() hcpa=box.getredcapfields(fieldlist=['misscat','data_status'],study='hcpa') ssaga=box.getredcapfields(fieldlist=[],study='ssaga') check=pd.merge(hcpa[['flagged','gender','site','study','subject','misscat___8','data_status']],ssaga[['hcpa_id','subject']],on='subject',how='outer',indicator=True) check.loc[(check._merge=='left_only') & (check.flagged.isnull()==True) & (check.misscat___8=='0')][['site','subject','data_status']] #SEE SSAGA TRACKING EMAIL FROM CINDY 3/31/20 ########################## #nothing new in corrected this round. #stopped here -- keeping code below to pick up where left off...which is ...not at all #figure out the ids we have and see what we need to pull from elsewhere #These are the subjects we're expecting (misscat___3=1 for perm missing toolb0x) hcpa=box.getredcapfields(fieldlist=['misscat', 'data_status'], study='hcpa') hcpa=hcpa.loc[hcpa.flagged.isnull()==True].copy() hcpa=hcpa.loc[(hcpa.data_status.isin(['1','2'])) & (~(hcpa.misscat___3=='1'))].copy() hcpd=box.getredcapfields(fieldlist=['misscat', 'data_status'], study='hcpdchild') hcpd18=box.getredcapfields(fieldlist=['misscat', 'data_status'], study='hcpd18') hcpdparent=box.getredcapfields(fieldlist=[], study='hcpdparent') hcpdparent=hcpdparent[['parent_id','subject','study']].rename(columns={'subject':'child_id'}) hcpd=pd.concat([hcpd,hcpd18],axis=0) hcpd=hcpd.loc[hcpd.flagged.isnull()==True].copy() hcpd=hcpd.loc[(hcpd.data_status.isin(['1','2'])) & (~(hcpd.misscat___3=='1'))].copy() #Harvard Harv=82803734267 Harvattn=96013516511 Harvcorr=84800505740 harvcleandata,harvcleanscores=box2dataframe(fileid=Harv) len(harvcleandata.PIN.unique()) #551 len(harvcleanscores.PIN.unique()) #551 H=pd.DataFrame(harvcleanscores.PIN.unique(),columns={"PIN"}) H['site']='Harvard' MGH2=82761770877 MGHattn=96148925420 MHGcorr=84799213727 mghdata,mghscores=box2dataframe(fileid=MGH2) len(mghdata.PIN.unique()) len(mghscores.PIN.unique()) #230 in each now M=pd.DataFrame(mghscores.PIN.unique(),columns={"PIN"}) M['site']='MGH' WashUD=82804015457 WashUDattn=96147128675 WUDcorr=84801037257 wuddata,wudscores=box2dataframe(fileid=WashUD) #301 in each now len(wuddata.PIN.unique()) len(wudscores.PIN.unique()) WD=pd.DataFrame(wudscores.PIN.unique(),columns={"PIN"}) WD['site']='WashUD' WashUA=82804729845 WashUAattn=96149947498 WUAcorr=84799623206 wuadata,wuascores=box2dataframe(fileid=WashUA) len(wuadata.PIN.unique()) #238 in each now len(wuascores.PIN.unique()) #238 in each now WA=pd.DataFrame(wuascores.PIN.unique(),columns={"PIN"}) WA['site']='WashUA' UMNA=82803665867 UMNAattn=96153923311 UMNAcorr=84799599800 umnadata,umnascores=box2dataframe(fileid=UMNA) len(umnadata.PIN.unique()) #288 in each now len(umnascores.PIN.unique()) #288 in each now UMA=pd.DataFrame(umnascores.PIN.unique(),columns={"PIN"}) UMA['site']='UMNA' UMND=82805151056 UMNDattn=96155708581 UMNDcorr=84799525828 umnddata,umndscores=box2dataframe(fileid=UMND) len(umnddata.PIN.unique()) #270 in each now len(umndscores.PIN.unique()) #270 in each now UMD=pd.DataFrame(umndscores.PIN.unique(),columns={"PIN"}) UMD['site']='UMND' UCLAA=82807223120 UCLAAattn=96154919803 UCLAAcorr=84799075673 uclaadata,uclaascores=box2dataframe(fileid=UCLAA) len(uclaadata.PIN.unique()) #207 len(uclaascores.PIN.unique()) UCA=pd.DataFrame(uclaascores.PIN.unique(),columns={"PIN"}) UCA['site']='UCLAA' UCLAD=82805124019 UCLADattn=96162759127 UCLADcorr=84800272537 ucladdata,ucladscores=box2dataframe(fileid=UCLAD) len(ucladdata.PIN.unique()) #350 len(ucladscores.PIN.unique()) UCD=pd.DataFrame(ucladscores.PIN.unique(),columns={"PIN"}) UCD['site']='UCLAD' allcurated=pd.concat([H,M,WD,WA,UMA,UMD,UCA,UCD],axis=0) ########################################### ucladdata,ucladscores uclaadata,uclaascores umnddata,umndscores umnadata,umnascores wuadata,wuascores wuddata,wudscores mghdata,mghscores harvcleandata,harvcleanscores #concatenate cleandata for snapshotdate - putting read_csv here in case not loaded into memory #raw: allrawdataHCAorBoth=pd.concat([uclaadata,umnadata,wuadata,mghdata],axis=0) allrawdataHCD=pd.concat([ucladdata,umnddata,wuddata,harvcleandata],axis=0) #scores: allscoresHCAorBoth=pd.concat([uclaascores,umnascores,wuascores,mghscores],axis=0) allscoresHCD=pd.concat([ucladscores,umndscores,wudscores,harvcleanscores],axis=0) ###################### #make csv allrawdataHCAorBoth.to_csv(box_temp+'/HCAorBoth_Toolbox_Raw_Combined_'+snapshotdate+'.csv') allrawdataHCD.to_csv(box_temp+'/HCD_Toolbox_Raw_Combined_'+snapshotdate+'.csv') allscoresHCAorBoth.to_csv(box_temp+'/HCAorBoth_Toolbox_Scored_Combined_'+snapshotdate+'.csv') allscoresHCD.to_csv(box_temp+'/HCD_Toolbox_Scored_Combined_'+snapshotdate+'.csv') ############################## def box2dataframe(fileid): harvardfiles, harvardfolders = foldercontents(fileid) data4process = harvardfiles.loc[~(harvardfiles.filename.str.upper().str.contains('SCORE') == True)] scores4process = harvardfiles.loc[harvardfiles.filename.str.upper().str.contains('SCORE') == True] data4process=data4process.reset_index() scores4process = scores4process.reset_index() box.download_files(data4process.file_id) box.download_files(scores4process.file_id) harvcleandata = pd.read_csv(box_temp+'/'+ data4process.filename[0], header=0, low_memory=False) harvcleanscores = pd.read_csv(box_temp+'/'+ scores4process.filename[0], header=0, low_memory=False) return harvcleandata,harvcleanscores def inventory(hdata,hscores,study,site,v): curated = findpairs(hdata, hscores) # this is the list of ids in both scored and raw corrected data curatedDF = pd.DataFrame(curated, columns={'PIN'}) curatedDF[['subject','visit']]=curatedDF.PIN.str.split("_",1,expand=True) curatedvisit=curatedDF.loc[curatedDF.visit==v] curatedvisit=pd.merge(curatedvisit,study.loc[study.site==site],on='subject',how='outer',indicator=True) findelsewhere=curatedvisit.loc[curatedvisit._merge=='right_only'] #these are the ones that I need to get from endpoint return findelsewhere[['subject','visit','site','study']] def grabfromallsites(pdfind,pdscores,pddata,pairs): catscores=pd.DataFrame() catdata=pd.DataFrame() pdfind['PIN']=pdfind['subject']+'_V1' grablist=pdfind.PIN.unique() for pinno in grablist: if pinno in pairs: print("Found PIN:" + pinno) catscores=pd.concat([catscores,pdscores.loc[pdscores.PIN==pinno]],axis=0) catdata = pd.concat([catdata,pddata.loc[pddata.PIN == pinno]],axis=0) return catscores,catdata def sendtocorrected(scoresfound,datafound,fname,fnumber): scoresfound.to_csv(box_temp+'/'+fname+'_scores_'+snapshotdate+'.csv',index=False) box.upload_file(box_temp+'/'+fname+'_scores_'+snapshotdate+'.csv',fnumber) datafound.to_csv(box_temp+'/'+fname+'_data_'+snapshotdate+'.csv',index=False) box.upload_file(box_temp+'/'+fname+'_data_'+snapshotdate+'.csv',fnumber) def curatedandcorrected(curatedfolderid,needsattnfolder): harvardfiles, harvardfolders=foldercontents(curatedfolderid) #dont grab files that need attention harvardfolders=harvardfolders.loc[~(harvardfolders.foldername.str.contains('needs_attention'))] harvardfiles2, harvardfolders2=folderlistcontents(harvardfolders.foldername,harvardfolders.folder_id) harvardfiles=pd.concat([harvardfiles,harvardfiles2],axis=0,sort=True) data4process=harvardfiles.loc[~(harvardfiles.filename.str.upper().str.contains('SCORE')==True)] scores4process=harvardfiles.loc[harvardfiles.filename.str.upper().str.contains('SCORE')==True] box.download_files(data4process.file_id) box.download_files(scores4process.file_id) #trick the catcontents macro to create catable dataset, but dont actually cat until you remove the #PINS in the corrected file from the curated file #step1 - separate data4process/scores4process into corrected and old curated data cdata=data4process.loc[data4process.filename.str.contains('corrected')] cscores=scores4process.loc[scores4process.filename.str.contains('corrected')] olddata=data4process.loc[~(data4process.filename.str.contains('corrected'))] oldscores=scores4process.loc[~(scores4process.filename.str.contains('corrected'))] #create catable dataset for corrected data hdatainitcorr=catcontents(cdata,box_temp) hscoreinitcorr=catcontents(cscores,box_temp) #get list of ids in this corrected data #60 for Harvard corrl=findpairs(hdatainitcorr,hscoreinitcorr) #this is the list of ids in both scored and raw corrected data #create catable dataset for old curated data hdatainitold=catcontents(olddata,box_temp) hscoreinitold=catcontents(oldscores,box_temp) #remove the data with PINS from corrected hdatainitoldsub=hdatainitold[~(hdatainitold.PIN.isin(corrl))] hscoreinitoldsub=hscoreinitold[~(hscoreinitold.PIN.isin(corrl))] #now cat the two datasets together hdatainit=pd.concat([hdatainitcorr,hdatainitoldsub],axis=0,sort=True) #these have 60 more unique pins than before...good hscoreinit=pd.concat([hscoreinitcorr,hscoreinitoldsub],axis=0,sort=True) #these have 60 more than before...good l=findpairs(hdatainit,hscoreinit) #this is the list of ids in both scored and raw data #set aside those who arebnt in both and those that are in dlist or slist notbothdatalist=hdatainit[~(hdatainit.PIN.isin(l))] notbothscorelist=hscoreinit[~(hscoreinit.PIN.isin(l))] nbs=list(notbothscorelist.PIN.unique()) nbd=list(notbothdatalist.PIN.unique()) hdatainit2=hdatainit[hdatainit.PIN.isin(l)] hscoreinit2=hscoreinit[hscoreinit.PIN.isin(l)] #check that this is same as above -- it is #hdatainit2qc=hdatainit[~(hdatainit.PIN.isin(nbs+nbd))] #hscoreinit2qc=hscoreinit[~(hscoreinit.PIN.isin(nbs+nbd))] #find instrument duplications that are not identical dlist,slist=findwierdos(hdatainit2,hscoreinit2) dslist=pd.concat([dlist,slist],axis=0) wierdlist=list(dslist.PIN.unique()) #set aside those who are in the wierdlist nonidenticaldupdata=hdatainit2.loc[hdatainit2.PIN.isin(wierdlist)] nonidenticaldupscore=hscoreinit2.loc[hscoreinit2.PIN.isin(wierdlist)] wierdd=list(dlist.PIN.unique()) wierds=list(slist.PIN.unique()) #so we have the notinboth lists and the wierdlists #Already set aside the notinbothlists #if we exclude any wierdlist PINs from both, this should get rid of everything that isnt one-to-one hdatainit3=hdatainit2.loc[~(hdatainit2.PIN.isin(wierdlist))] hscoreinit3=hscoreinit2.loc[~(hscoreinit2.PIN.isin(wierdlist))] #both have 580 unique ids - make them into a list l3=findpairs(hdatainit3,hscoreinit3) #this is the list of ids in both scored and raw data dlist,slist=findwierdos(hdatainit3,hscoreinit3) #now delete any identical duplicates check for issues finding wierdos if dlist.empty and slist.empty: hdatainit3=hdatainit3.drop_duplicates(subset={'PIN','Inst','ItemID','Position'},keep='first') hscoreinit3=hscoreinit3.drop_duplicates(subset={'PIN','Inst'}) else: print('Found Non-Identical Duplications') print(dlist) print(slist) #export scores and data for all pins in dslist or nbs or nbd with flags notbothdatalist.to_csv(box_temp+'/Toolbox_notinboth_Data_'+snapshotdate+'.csv') notbothscorelist.to_csv(box_temp+'/Toolbox_notinboth_Scores_'+snapshotdate+'.csv') box.upload_file(box_temp+'/Toolbox_notinboth_Data_'+snapshotdate+'.csv',needsattnfolder) box.upload_file(box_temp+'/Toolbox_notinboth_Scores_'+snapshotdate+'.csv',needsattnfolder) nonidenticaldupdata.to_csv(box_temp+'/Toolbox_NonidentDups_Data_'+snapshotdate+'.csv') nonidenticaldupscore.to_csv(box_temp+'/Toolbox_NonidentDups_Scores_'+snapshotdate+'.csv') box.upload_file(box_temp+'/Toolbox_NonidentDups_Data_'+snapshotdate+'.csv',needsattnfolder) box.upload_file(box_temp+'/Toolbox_NonidentDups_Scores_'+snapshotdate+'.csv',needsattnfolder) #last but not least...set aside ids not in REDCap, and IDs that need visit numbers #get reds from hdatatinit3 (should be same as list from hscoreinit3) #generate hdatainit4 and hscoreinit4 which is relieved of these ids hdatainit4=subjectsvisits(hdatainit3) hscoreinit4=subjectsvisits(hscoreinit3) mv=hscoreinit4.loc[~(hscoreinit4.visit.isin(['V1','V2','V3','X1','X2','X3']))].copy() mvs=list(mv.subject.unique()) #list of PINs without visit numbers check=subjectpairs(hdatainit4,hscoreinit4) #this number will be fewer because V1 and V2 PINs for same subject only counted once) redids=box.getredcapids() dfcheck=pd.DataFrame(check,columns=['subject']) boxids=pd.merge(dfcheck,redids,how='left',on='subject',indicator=True) reds=list(boxids.loc[boxids._merge=='left_only'].subject) #subjects not in redcap boxandredcap=boxids.loc[boxids._merge=='both'].subject #export the otherwise cleanest data ready for snapshotting as the new updated curated file -- then run this for all sites befo #write code here - has only ids with visit numbers and one to one scores and data correspondence and no wierd duplications #but check one last time that hdatainit5 and hscoreinit5 is super clean hdatainit5=hdatainit4.loc[~(hdatainit4.subject.isin(mvs+reds))] hscoreinit5=hscoreinit4.loc[~(hscoreinit4.subject.isin(mvs+reds))] #export the lists of ids and reasons they were excluded df=pd.DataFrame(columns=['reason','affectedIDs']) df=df.append({'reason': 'PIN In Scores but not Data', 'affectedIDs': nbs}, ignore_index=True) df=df.append({'reason': 'PIN In Data but not Scores', 'affectedIDs': nbd}, ignore_index=True) df=df.append({'reason': 'PIN/Instrument Non-identical Duplication in Data', 'affectedIDs': wierdd}, ignore_index=True) df=df.append({'reason': 'PIN/Instrument Non-identical Duplication in Scores', 'affectedIDs': wierds}, ignore_index=True) df=df.append({'reason': 'PIN/subject in Scores and Data but missing visit', 'affectedIDs': mvs}, ignore_index=True) df=df.append({'reason': 'subject in Scores and Data but not REDCap ', 'affectedIDs': reds}, ignore_index=True) df.to_csv(box_temp+'/List_of_IDs_and_Reasons_they_in_these_files_'+snapshotdate+'.csv') box.upload_file(box_temp+'/List_of_IDs_and_Reasons_they_in_these_files_'+snapshotdate+'.csv',needsattnfolder) return hdatainit5,hscoreinit5 #get subject and visit from a PIN in a dataframe def subjectsvisits(hdatainit3): hdatainit3['subject']=hdatainit3.PIN.str.strip().str[:10] hdatainit3['visit']='' hdatainit3.loc[hdatainit3.PIN.str.contains('v1',case=False),'visit']='V1' hdatainit3.loc[hdatainit3.PIN.str.contains('v2',case=False),'visit']='V2' hdatainit3.loc[hdatainit3.PIN.str.contains('v3',case=False),'visit']='V3' hdatainit3.loc[hdatainit3.PIN.str.contains('x1',case=False),'visit']='X1' hdatainit3.loc[hdatainit3.PIN.str.contains('x2',case=False),'visit']='X2' hdatainit3.loc[hdatainit3.PIN.str.contains('x3',case=False),'visit']='X3' return hdatainit3 #pull id visit combos that arent in both scores and data files def findpairs(hdatainit,hscoreinit): pinsinboth=[] for i in hscoreinit.PIN.unique(): if i in hdatainit.PIN.unique() and isinstance(i,str): pinsinboth=pinsinboth+[i] else: print('the following PINs in scores but not data:') print(i) for i in hdatainit.PIN.unique(): if i in hscoreinit.PIN.unique(): pass else: print('the following PINs in data but not scores:') print(i) return pinsinboth def subjectpairs(hdatainit,hscoreinit): pinsinboth=[] for i in hscoreinit.subject.unique(): if i in hdatainit.subject.unique() and isinstance(i,str): pinsinboth=pinsinboth+[i] else: print('the following subjects in scores but not data:') print(i) for i in hdatainit.subject.unique(): if i in hscoreinit.subject.unique(): pass else: print('the following subjectss in data but not scores:') print(i) return pinsinboth def findwierdos(hdatainit,hscoreinit): #compare the two types of sort to identify which files have non-identical duplications sort1data=hdatainit.drop_duplicates(subset={'PIN','Inst','ItemID','Position'},keep='first') sort1score=hscoreinit.drop_duplicates(subset={'PIN','Inst'}) sort2data=hdatainit.drop_duplicates(subset=set(hdatainit.columns).difference({'filename','file_id'})) sort2score=hscoreinit.drop_duplicates(subset=set(hscoreinit.columns).difference({'filename','file_id'})) s1d=sort1data.groupby('PIN').count() s2d=sort2data.groupby('PIN').count() databoth=pd.merge(s1d.reset_index()[['PIN','DeviceID']], s2d.reset_index()[['PIN','DeviceID']],on=['PIN','DeviceID'],how='outer',indicator=True) wierd_data=databoth.loc[databoth._merge!='both'].rename(columns={'DeviceID':'Number of Rows'}) s1s=sort1score.groupby('PIN').count() s2s=sort2score.groupby('PIN').count() scoreboth=pd.merge(s1s.reset_index()[['PIN','DeviceID']], s2s.reset_index()[['PIN','DeviceID']],on=['PIN','DeviceID'],how='outer',indicator=True) wierd_score=scoreboth.loc[scoreboth._merge!='both'].rename(columns={'DeviceID':'Number of Rows'}) return wierd_data,wierd_score def catcontents(files,cache_space): #dataframe that has filename and file_id as columns scoresfiles=files.copy() scoresinit=pd.DataFrame() for i in scoresfiles.filename: filepath=os.path.join(cache_space,i) filenum=scoresfiles.loc[scoresfiles.filename==i,'file_id'] try: temp=pd.read_csv(filepath,header=0,low_memory=False) temp['filename']=i temp['file_id']=pd.Series(int(filenum.values[0]),index=temp.index) temp['raw_cat_date']=snapshotdate scoresinit=pd.concat([scoresinit,temp],axis=0,sort=False) except: print(filepath+' wouldnt import') temp=pd.DataFrame() temp['filename']=pd.Series(i,index=[0]) temp['file_id']=pd.Series(int(filenum.values[0]),index=[0]) temp['raw_cat_date']=snapshotdate scoresinit=pd.concat([scoresinit,temp],axis=0,sort=False) return scoresinit def catfromlocal(endpoint_temp,scores2cat): #dataframe that has filenames scoresfiles=scores2cat.copy() scoresinit=pd.DataFrame() for i in scoresfiles.fname: filepath=os.path.join(endpoint_temp,i) try: temp=pd.read_csv(filepath,header=0,low_memory=False) temp['filename']="endpointmachine/"+i temp['raw_cat_date']=snapshotdate scoresinit=pd.concat([scoresinit,temp],axis=0,sort=False) except: print(filepath+' wouldnt import') temp=pd.DataFrame() temp['filename']=pd.Series("endpointmachine/"+i,index=[0]) temp['raw_cat_date']=snapshotdate scoresinit=pd.concat([scoresinit,temp],axis=0,sort=False) return scoresinit def folderlistcontents(folderslabels,folderslist): bdasfilelist=pd.DataFrame() bdasfolderlist=
pd.DataFrame()
pandas.DataFrame
''' Created on Jun 8, 2017 @author: husensofteng ''' import matplotlib matplotlib.use('Agg') from matplotlib.backends.backend_pdf import PdfPages import pybedtools from pybedtools.bedtool import BedTool from matplotlib.pyplot import tight_layout import matplotlib.pyplot as plt from pylab import gca import pandas as pd import math import numpy as np from decimal import Decimal import os, sys import seaborn as sns import operator import argparse sns.set(style="ticks") #plt.style.use('ggplot') sns.set_style("white") sns.set_context("paper")#talk from utils import * def get_mut_df(input='', x_col_index=5, y_col_index=8, x_col_name = 'Cancer types', y_col_name='Mutation Frequency (log10)'): if os.path.isfile(str(input)): names = [x_col_name, y_col_name] if x_col_index>y_col_index: names = [y_col_name, x_col_name] df =
pd.read_table(input, sep='\t', header=None, usecols=[x_col_index, y_col_index], names=names)
pandas.read_table
import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import plotly.express as px from lib.unsupervised.dimension import Pca_vectors class Anomaly_nature(): def __init__(self, model, X_full, y_full, left_axes_limit, right_axes_limit, reduce_dim=False): """ params : model = Anomalies models IsolationForest, OneClassSVM X_full = dataframe or np.array(2d) y_full = target data as vector or dataframe left_axes_limit = left_axes value of fig right_axes_limit = right_axes value of fig reduce_dim : if true apply pca 2d and standardscaler on x_full """ self.model = model self.X_full = X_full self.y_full = y_full self.reduce_dim = reduce_dim self.left_axes_limit = left_axes_limit self.right_axes_limit = right_axes_limit def build_anomalies_model(self, X_input=None, in_color='#FF0017', out_color='#BEBEBE'): """ params : X_input = for consume model, pass input data as x_vec (for app usage) in_color, out_color = colors for scatters points return matplolib figure and self.model """ if self.reduce_dim: pca_job = Pca_vectors(self.X_full) reduced_features = pca_job.reduce_dimension_train() else: reduced_features = self.X_full self.model.fit(reduced_features) y_pred = self.model.predict(reduced_features) xx, yy = np.meshgrid(np.linspace(self.left_axes_limit, self.right_axes_limit, 100), np.linspace(self.left_axes_limit, self.right_axes_limit, 100)) Z = self.model.predict(np.c_[xx.ravel(), yy.ravel()]) ## Love Z = Z.reshape(xx.shape) fig = plt.figure() plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='black') colors = np.array([in_color, out_color]) plt.scatter(reduced_features[:, 0], reduced_features[:, 1], s=3, color=colors[(y_pred + 1) // 2]) model_name = type(self.model).__name__ if model_name =='OneClassSVM': kernel_name = self.model.kernel plt.title(f"{model_name} : {kernel_name}") else: plt.title(f"{model_name}") if X_input is not None: if self.reduce_dim: X_input = pca_job.reduce_dimension_prod(X_input) plt.scatter(X_input[:, 0], X_input[:, 1]) anomalie_prediction = self.model.predict(X_input) return self.model, fig, anomalie_prediction return self.model, fig def build_3dim(self, X_input=None, X_info=None): """ params : X_input = for consume model, pass input data as x_vec (for app usage) X_info = ad information to data as Id or categories return plotly 3d figure """ pca_job = Pca_vectors(self.X_full) reduced_features = pca_job.reduce_dimension_train(number_of_dim=3) df = pd.DataFrame(data=reduced_features, columns=["Axe1", "Axe2", "Axe3"]) if X_info is not None: for c in X_info.columns: df[f'{c}'] = X_info[f'{c}'] df['target'] = self.y_full if X_input is not None: X_input = pca_job.reduce_dimension_prod(X_input) df_inp = pd.DataFrame(data=X_input, columns=["Axe1", "Axe2", "Axe3"]) df_inp['target'] = 2 prod_df =
pd.concat([df, df_inp], ignore_index=True)
pandas.concat
import pandas as pd import numpy as np import re from law.utils import * import jieba.posseg as pseg import datetime import mysql.connector class case_reader: def __init__(self, user, password, n=1000, preprocessing=False): ''' n is total types, preprocessing: whether needs preprocessing ''' # old version: use file_path # self.file_path = file_path # self.data = pd.read_csv(self.file_path, encoding='utf-8', engine='python') # new version: directly reading data # connect database self.n = n self.preprocessing = preprocessing print("Connecting to Server...") cnx = mysql.connector.connect(user=user, password=password, host="cdb-74dx1ytr.gz.tencentcdb.com", port=10008, database='law') cursor = cnx.cursor(buffered=True) print("Server Connected.") # read database if n>=0: query = 'SELECT * FROM Civil LIMIT ' + str(self.n) + ';' else: query = 'SELECT * FROM Civil;' print("Start Reading Data...") self.data = pd.read_sql(query,con=cnx) print("Read Data Successful...") self.data_len = len(self.data) print("This dataset has ", self.data_len, "rows of data.") # np.nan replace missing value self.data = self.data.fillna(np.nan) def return_data(self): if self.preprocessing: self.preprocess() return self.data def number2(self): ''' This function change '庭审程序' into one hot encodings -- Klaus ''' xingfabiangeng = np.zeros(self.data_len) yishen = np.zeros(self.data_len) ershen = np.zeros(self.data_len) fushen = np.zeros(self.data_len) qita = np.zeros(self.data_len) for i in range(self.data_len): if self.data['proc'][i] == "刑罚变更": xingfabiangeng[i] += 1 if self.data['proc'][i] == "一审": yishen[i] += 1 if self.data['proc'][i] == "二审": ershen[i] += 1 if self.data['proc'][i] == "复核": fushen[i] += 1 if self.data['proc'][i] == "其他" : qita[i] += 1 self.data['proc_是否_刑罚变更'] = xingfabiangeng self.data['proc_是否_一审'] = yishen self.data['proc_是否_二审'] = ershen self.data['proc_是否_复核'] = fushen self.data['proc_是否_其他'] = qita #print(xingfabiangeng) #print(yishen) #print(ershen) #print(qita) del xingfabiangeng, yishen, ershen, fushen, qita def number3(self): ''' This function change '案由' into one hot encodings ''' reasons = ['机动车交通事故责任纠纷' ,'物件损害责任纠纷' ,'侵权责任纠纷', '产品责任纠纷', '提供劳务者受害责任纠纷' ,'医疗损害责任纠纷', '地面施工、地下设施损害责任纠纷', '饲养动物损害责任纠纷' ,'产品销售者责任纠纷', '因申请诉中财产保全损害责任纠纷', '教育机构责任纠纷', '违反安全保障义务责任纠纷' , '网络侵权责任纠纷' ,'因申请诉前财产保全损害责任纠纷' ,'物件脱落、坠落损害责任纠纷', '因申请诉中证据保全损害责任纠纷' ,'建筑物、构筑物倒塌损害责任纠纷' ,'提供劳务者致害责任纠纷' ,'产品生产者责任纠纷', '公共场所管理人责任纠纷', '公证损害责任纠纷', '用人单位责任纠纷' ,'触电人身损害责任纠纷', '义务帮工人受害责任纠纷', '高度危险活动损害责任纠纷', '噪声污染责任纠纷' ,'堆放物倒塌致害责任纠纷', '公共道路妨碍通行损害责任纠纷' ,'见义勇为人受害责任纠纷', '医疗产品责任纠纷' ,'监护人责任纠纷', '水上运输人身损害责任纠纷', '环境污染责任纠纷', '因申请先予执行损害责任纠纷', '铁路运输人身损害责任纠纷' ,'水污染责任纠纷', '林木折断损害责任纠纷', '侵害患者知情同意权责任纠纷' ,'群众性活动组织者责任纠纷', '土壤污染责任纠纷'] mreason = np.zeros(self.data_len) for i in range(self.data_len): for j,reason in enumerate(reasons): if self.data['class'][i] == reasons[j]: mreason[i] +=j+1 self.data['class_index'] = mreason del mreason def number4(self): ''' This function change '文书类型' into one hot encodings ''' panjueshu = np.zeros(self.data_len) caidingshu = np.zeros(self.data_len) for i in range(self.data_len): if self.data['doc_type'][i] == "判决书": panjueshu[i] += 1 if self.data['doc_type'][i] == "裁定书": caidingshu[i] += 1 self.data['doc_type'] = panjueshu self.data['doc_type'] = caidingshu del panjueshu, caidingshu def number5(self): ''' court → province、city、level -- <NAME> ''' level = [] # court level distinct = [] # province block = [] # city for x in self.data['court_name']: if pd.isna(x):#if empty level.append(None) distinct.append(None) block.append(None) else: # search “省”(province) a = re.compile(r'.*省') b = a.search(x) if b == None: distinct.append(None) else: distinct.append(b.group(0)) x = re.sub(b.group(0), '', x) # search "市"(city) a = re.compile(r'.*市') b = a.search(x) if b == None: block.append(None) else: block.append(b.group(0)) # search“级”(level) a = re.compile(r'.级') b = a.search(x) if b == None: level.append(None) else: level.append(b.group(0)) newdict = { '法院所在省': distinct, '法院所在市': block, '法院等级': level } # DataFrame newdata = pd.DataFrame(newdict) self.data = pd.concat([self.data, newdata], axis=1) del newdata, level, distinct, block def number6(self): ''' 分成年月日 :return: ''' year = [] month = [] day = [] for x in self.data['date']: # year a = re.compile(r'.*年') b = a.search(str(x)) if b == None: year.append(None) else: year.append(b.group(0)) x = re.sub(b.group(0), '', x) # month a1 = re.compile(r'.*月') b1 = a1.search(str(x)) if b1 == None: month.append(None) else: month.append(b1.group(0)) x = re.sub(b1.group(0), '', x) # day a2 = re.compile(r'.*日') b2 = a2.search(str(x)) if b2 == None: day.append(None) else: day.append(b2.group(0)) newdict = { '判决年份': year, '判决月份': month, '判决日期': day } # DataFrame newdata = pd.DataFrame(newdict) self.data = pd.concat([self.data, newdata], axis=1) del year, month, day def number7(self): # 四列 one hot 检察院,法人,自然人,其他 ''' --<NAME> ''' self.data['原告_是否_检察院'] = 0 self.data['原告_是否_法人'] = 0 self.data['原告_是否_自然人'] = 0 self.data['原告_是否_其他'] = 0 pattern = r'(?::|:|。|、|\s|,|,)\s*' jcy_pattern = re.compile(r'.*检察院') gs_pattern = re.compile(r'.*公司') for i in range(len(self.data['plantiff'])): if pd.isna(self.data['plantiff'][i]): continue self.data['plantiff'][i] = re.sub(' ', '', self.data['plantiff'][i]) result_list = re.split(pattern, self.data['plantiff'][i]) for x in result_list: temp1 = jcy_pattern.findall(x) temp2 = gs_pattern.findall(x) if len(temp1) != 0: self.data['原告_是否_检察院'][i] = 1 if (0 < len(x) <= 4): self.data['原告_是否_自然人'][i] = 1 if ((len(temp1) != 0) or len(temp2) != 0): self.data['原告_是否_法人'][i] = 1 if (len(x) > 4 and len(temp1) == 0 and len(temp2) == 0): self.data['原告_是否_其他'][i] = 1 def number8(self): # http://www.sohu.com/a/249531167_656612 company = re.compile(r'.*?公司') natural_person = np.zeros(self.data_len) legal_person = np.zeros(self.data_len) other_person = np.zeros(self.data_len) for i in range(self.data_len): # 显示进度 #if i % 100 == 0: # print(i) if pd.isna(self.data['defendant'][i]): continue if re.search(company, self.data['defendant'][i]) is not None: legal_person[i] = 1 l = re.split('、', self.data['defendant'][i]) l1 = list(filter(lambda s: len(s) <= 4, l)) l2 = list(filter(lambda s: (re.search(company, s)) is None, l1)) if len(l2) > 0: natural_person[i] = 1 l3 = list(filter(lambda s: len(s) > 4, l)) l4 = list(filter(lambda s: (re.search(company, s)) is None, l3)) if len(l4) > 0: other_person[i] = 1 for mes in l4: words = pseg.cut(mes) #verbs = [] for word, flag in words: if flag == 'v': other_person[i] = 0 break self.data['被告_是否_自然人'] = natural_person self.data['被告_是否_法人'] = legal_person self.data['被告_是否_其他'] = other_person del natural_person, legal_person, other_person def number9(self): ''' --<NAME>''' self.data['第三人_有无自然人'] = 0 pattern = r'(?::|:|。|、|\s|,|,)\s*' for i in range(len(self.data['third_party'])): if pd.isna(self.data['third_party'][i]): continue result_list = re.split(pattern, self.data['third_party'][i]) for x in result_list: if (0 < len(x) <= 4): self.data['第三人_有无自然人'][i] = 1 break def number10(self): information = [] for i in range(self.data_len): #if i % 100 == 0: #print(i) info = {} if pd.isna(self.data['party'][i]): information.append({}) continue information.append(ADBinfo(self.data, i)) self.data['party_one_hot'] = information del information, info def number11(self): types = [] money = [] for x in self.data['procedure']: #print(x) if str(x)=='nan' or re.search('[0-9]+元',x)==None: money.append(0) else: money.append(1) if str(x)=='nan': types.append('空白') elif not(re.search('不宜在互联网公布|涉及国家秘密的|未成年人犯罪的',x)==None): types.append('不公开') elif not(re.search('以调解方式结案的',x)==None): types.append('调解结案') elif not(re.search('一案.*本院.*简易程序.*(因|转为)',x)==None): types.append('已审理(简易转普通)') elif not(re.search('一案.*(小额诉讼程序|简易程序).*审理(。$|终结。$|.*到庭参加诉讼|.*到庭应诉|.*参加诉讼)',x)==None): types.append('已审理(简易)') elif not(re.search('(一案.*本院.*(审理。$|审理终结。$|公开开庭进行了审理。$|公开开庭进行.?审理.*到庭参加.?诉讼))',x)==None): types.append('已审理') #elif not(re.search('一案.*本院.*(受理|立案).*简易程序.*(因|转为)',x)==None): #types.append('已受理/立案(简易转普通)') #这种情况出现的太少,暂不单独分类 elif not(re.search('一案.*本院.*(受理|立案).*(小额诉讼程序|简易程序)(。$|.*由.*审判。$)',x)==None): types.append('已受理/立案(简易)') elif not(re.search('一案.*本院.*(立案。$|立案受理。$|立案后。$)',x)==None): types.append('已受理/立案') elif not(re.search('一案.*(调解.*原告|原告.*调解).*撤',x)==None): types.append('调解撤诉') elif (re.search('调解',x)==None) and not(re.search('一案.*原告.*撤',x)==None): types.append('其他撤诉') elif not(re.search('一案.*原告.*((未|不).*(受理|诉讼)费|(受理|诉讼)费.*(未|不))',x)==None): types.append('未交费') elif not(re.search('一案.*本院.*依法追加.*被告',x)==None): types.append('追加被告') elif not(re.search('上诉人.*不服.*上诉。$',x)==None): types.append('上诉') elif not(re.search('再审.*一案.*不服.*再审。$',x)==None): types.append('要求再审') elif not(re.search('一案.*申请财产保全.*符合法律规定。$',x)==None): types.append('同意诉前财产保全') elif not(re.search('申请.*(请求|要求).*(查封|冻结|扣押|保全措施)',x)==None): types.append('申请财产保全') elif not(re.search('一案.*(缺席|拒不到庭|未到庭)',x)==None): types.append('缺席审判') elif not(re.search('一案.*申请.*解除(查封|冻结|扣押|保全措施).*符合法律规定。$',x)==None): types.append('同意解除冻结') else: types.append('其他/错误') #newdict={'庭审程序分类':types,'money':money} newdict={'庭审程序分类':types} newdata = pd.DataFrame(newdict) self.data = pd.concat([self.data, newdata], axis=1) del types def number12(self): #if cancel repeal_pattern = re.compile(r'撤诉') yes = np.zeros(self.data_len) no = np.zeros(self.data_len) dk = np.zeros(self.data_len) al = np.zeros(self.data_len) for i in range(self.data_len): if not pd.isna(self.data['process'][i]): temp = repeal_pattern.findall(str(self.data['process'][i])) if len(temp) == 0: no[i] += 1 al[i] = 0 else: yes[i] += 1 al[i] = 1 else: dk[i] += 1 al[i] = -1 self.data['庭审过程_是否撤诉_是'] = yes self.data['庭审过程_是否撤诉_未知'] = dk self.data['庭审过程_是否撤诉_否'] = no self.data['庭审过程_是否撤诉_汇总'] = al del yes, no, dk, al #if hurt situation_pattern = re.compile(r'受伤|死亡|伤残|残疾|致残') yes = np.zeros(self.data_len) no = np.zeros(self.data_len) dk = np.zeros(self.data_len) al = np.zeros(self.data_len) for i in range(self.data_len): if not pd.isna(self.data['process'][i]): temp = situation_pattern.findall(str(self.data['process'][i])) if len(temp) == 0: no[i] += 1 al[i] = 0 else: yes[i] += 1 al[i] = 1 else: dk[i] += 1 al[i] = -1 self.data['庭审过程_是否受伤_是'] = yes self.data['庭审过程_是否受伤_否'] = no self.data['庭审过程_是否受伤_未知'] = dk self.data['庭审过程_是否受伤_汇总'] = al del yes, no, dk, al #if money money_pattern = re.compile(r'[0-9]+元|[0-9]+万元|[0-9]+万+[0-9]+千元|[0-9]+千+[0-9]+百元' r'[0-9]+万+[0-9]+千+[0-9]+百元|[0-9]+,+[0-9]+元|[0-9]+,+[0-9]+,+[0-9]+元') ''' 包含xxx元 xxx万元 xxx万xxx千元 xxx万xxx千xxx百元 xxx千xxx百元 xxx,xxx元 xxx,xxx,xxx元 ''' yes = np.zeros(self.data_len) no = np.zeros(self.data_len) dk = np.zeros(self.data_len) al = np.zeros(self.data_len) for i in range(self.data_len): if not pd.isna(self.data['process'][i]): temp = money_pattern.findall(str(self.data['process'][i])) if len(temp) == 0: no[i] += 1 al[i] = 0 else: yes[i] += 1 al[i] = 1 else: dk[i] += 1 al[i] = -1 self.data['庭审过程_是否涉及金钱_是'] = yes self.data['庭审过程_是否涉及金钱_否'] = no self.data['庭审过程_是否涉及金钱_未知'] = dk self.data['庭审过程_是否涉及金钱_汇总'] = al del yes, no, dk, al #if on purpose intent_pattern = re.compile(r'有意|故意') yes = np.zeros(self.data_len) no = np.zeros(self.data_len) dk = np.zeros(self.data_len) al = np.zeros(self.data_len) for i in range(self.data_len): if not pd.isna(self.data['process'][i]): temp = intent_pattern.findall(str(self.data['process'][i])) if len(temp) == 0: no[i] += 1 al[i] = 0 else: yes[i] += 1 al[i] = 1 else: dk[i] += 1 al[i] = -1 self.data['庭审过程_是否故意_是'] = yes self.data['庭审过程_是否故意_否'] = no self.data['庭审过程_是否故意_未知'] = dk self.data['庭审过程_是否故意_汇总'] = al del yes, no, dk, al #if moral reparation mental_pattern = re.compile(r'精神损失|精神赔偿|精神抚慰') yes = np.zeros(self.data_len) no = np.zeros(self.data_len) dk = np.zeros(self.data_len) al = np.zeros(self.data_len) for i in range(self.data_len): if not pd.isna(self.data['process'][i]): temp = mental_pattern.findall(str(self.data['process'][i])) if len(temp) == 0: no[i] += 1 al[i] = 0 else: yes[i] += 1 al[i] = 1 else: dk[i] += 1 al[i] = -1 self.data['庭审过程_是否要求精神赔偿_是'] = yes self.data['庭审过程_是否要求精神赔偿_否'] = no self.data['庭审过程_是否要求精神赔偿_未知'] = dk self.data['庭审过程_是否要求精神赔偿_汇总'] = al del yes, no, dk, al #if rejection absent_pattern = re.compile(r'拒不到庭') yes = np.zeros(self.data_len) no = np.zeros(self.data_len) dk = np.zeros(self.data_len) al = np.zeros(self.data_len) for i in range(self.data_len): if not pd.isna(self.data['process'][i]): temp = absent_pattern.findall(str(self.data['process'][i])) if len(temp) == 0: no[i] += 1 al[i] = 0 else: yes[i] += 1 al[i] = 1 else: dk[i] += 1 al[i] = -1 self.data['庭审过程_是否拒不到庭_是'] = yes self.data['庭审过程_是否拒不到庭_否'] = no self.data['庭审过程_是否拒不到庭_未知'] = dk self.data['庭审过程_是否拒不到庭_汇总'] = al del yes, no, dk, al #if argument objection_pattern = re.compile(r'有异议|重新鉴定|判决异议|') yes = np.zeros(self.data_len) no = np.zeros(self.data_len) dk = np.zeros(self.data_len) al = np.zeros(self.data_len) for i in range(self.data_len): if not pd.isna(self.data['process'][i]): temp = objection_pattern.findall(str(self.data['process'][i])) if len(temp) == 0: no[i] += 1 al[i] = 0 else: yes[i] += 1 al[i] = 1 else: dk[i] += 1 al[i] = -1 self.data['庭审过程_是否有异议_是'] = yes self.data['庭审过程_是否有异议_否'] = no self.data['庭审过程_是否有异议_未知'] = dk self.data['庭审过程_是否有异议_汇总'] = al del yes, no, dk, al #length length = np.zeros(self.data_len) for i in range(self.data_len): if type(self.data['process'][i]) == str: length[i] = len(self.data['process'][i]) else: length[i] = 0 self.data['庭审过程_长度'] = length del length def number13(self): '''“法院意见”(court comments) -money -number of law -number of pieces -number of clause --<NAME>''' self.data['法院意见_是否涉及金额'] = 0 self.data['法院意见_涉及的法数'] = 0 self.data['法院意见_涉及的条数'] = 0 self.data['法院意见_涉及的款数'] = 0 money_pattern = re.compile(r'[0-9]+元') for i in range(len(self.data['opinion'])): if not pd.isna(self.data['opinion'][i]): try: temp = find_law_tiao_kuan_in_text(self.data['opinion'][i]) except: print('法院意见无法处理的案件案号:'+self.data['id'][i]) else: if len(temp) > 0: self.data['法院意见_涉及的法数'][i] = len(temp) sum_tiao = 0 sum_kuan = 0 for j in range(len(temp)): sum_tiao += len(temp[j][1]) sum_kuan += len(temp[j][2]) self.data['法院意见_涉及的条数'][i] = sum_tiao self.data['法院意见_涉及的款数'][i] = sum_kuan # money for i in range(len(self.data['opinion'])): if not pd.isna(self.data['opinion'][i]): temp1 = money_pattern.findall(self.data['opinion'][i]) if len(temp1) == 0: continue self.data['法院意见_是否涉及金额'][i] = 1 def number14(self): selected_data = self.data["result"] data_len = len(selected_data) basis = [] # clause result = ["N/A"] * data_len charge = ["N/A"] * data_len sentence = ["N/A"] * data_len for i in range(data_len): if pd.isnull(selected_data.iloc[i]): basis.append([]) continue basis.append(find_law_tiao_kuan_in_text(selected_data.iloc[i])) # result for i in range(selected_data.shape[0]): if type(selected_data[i]) is not float: for j in range(len(selected_data[i])): if ("判决" in selected_data[i][j - 4:j + 4] or "裁定" in selected_data[i][j - 4:j + 4]) and ( "法院" not in selected_data[i][j - 10:j + 4]): if selected_data[i][j] == ':': if selected_data[i][j + 1] == '、': result[i] = selected_data[i][j + 2:-1] else: result[i] = selected_data[i][j + 1:-1] else: result[i] = "N/A" for i in range(selected_data.shape[0]): if type(selected_data[i]) is not float: for j in range(len(selected_data[i])): if "费" in selected_data[i][j + 1:j + 10]: if selected_data[i][j - 1] == '、': if selected_data[i][j] == '。': charge[i] = selected_data[i][j + 1:-1] else: charge[i] = selected_data[i][j:-1] else: charge[i] = "N/A" for i in range(selected_data.shape[0]): if type(result[i]) is not float: for j in range(len(result[i])): if result[i][j - 1] == '、': if result[i][j] == '。': sentence[i] = result[i][0:j - 2] else: sentence[i] = result[i][0:j - 1] else: sentence[i] = "N/A" newdict = { '判决法条': basis, '赔偿结果': charge } # DataFrame newdata =
pd.DataFrame(newdict)
pandas.DataFrame
import numpy as np import pytest from pandas.errors import UnsupportedFunctionCall from pandas import ( DataFrame, DatetimeIndex, Series, date_range, ) import pandas._testing as tm from pandas.core.window import ExponentialMovingWindow def test_doc_string(): df = DataFrame({"B": [0, 1, 2, np.nan, 4]}) df df.ewm(com=0.5).mean() def test_constructor(frame_or_series): c = frame_or_series(range(5)).ewm # valid c(com=0.5) c(span=1.5) c(alpha=0.5) c(halflife=0.75) c(com=0.5, span=None) c(alpha=0.5, com=None) c(halflife=0.75, alpha=None) # not valid: mutually exclusive msg = "comass, span, halflife, and alpha are mutually exclusive" with pytest.raises(ValueError, match=msg): c(com=0.5, alpha=0.5) with pytest.raises(ValueError, match=msg): c(span=1.5, halflife=0.75) with pytest.raises(ValueError, match=msg): c(alpha=0.5, span=1.5) # not valid: com < 0 msg = "comass must satisfy: comass >= 0" with pytest.raises(ValueError, match=msg): c(com=-0.5) # not valid: span < 1 msg = "span must satisfy: span >= 1" with pytest.raises(ValueError, match=msg): c(span=0.5) # not valid: halflife <= 0 msg = "halflife must satisfy: halflife > 0" with pytest.raises(ValueError, match=msg): c(halflife=0) # not valid: alpha <= 0 or alpha > 1 msg = "alpha must satisfy: 0 < alpha <= 1" for alpha in (-0.5, 1.5): with pytest.raises(ValueError, match=msg): c(alpha=alpha) @pytest.mark.parametrize("method", ["std", "mean", "var"]) def test_numpy_compat(method): # see gh-12811 e = ExponentialMovingWindow(Series([2, 4, 6]), alpha=0.5) msg = "numpy operations are not valid with window objects" with pytest.raises(UnsupportedFunctionCall, match=msg): getattr(e, method)(1, 2, 3) with pytest.raises(UnsupportedFunctionCall, match=msg): getattr(e, method)(dtype=np.float64) def test_ewma_times_not_datetime_type(): msg = r"times must be datetime64\[ns\] dtype." with pytest.raises(ValueError, match=msg): Series(range(5)).ewm(times=np.arange(5)) def test_ewma_times_not_same_length(): msg = "times must be the same length as the object." with pytest.raises(ValueError, match=msg): Series(range(5)).ewm(times=np.arange(4).astype("datetime64[ns]")) def test_ewma_halflife_not_correct_type(): msg = "halflife must be a timedelta convertible object" with pytest.raises(ValueError, match=msg): Series(range(5)).ewm(halflife=1, times=np.arange(5).astype("datetime64[ns]")) def test_ewma_halflife_without_times(halflife_with_times): msg = "halflife can only be a timedelta convertible argument if times is not None." with pytest.raises(ValueError, match=msg): Series(range(5)).ewm(halflife=halflife_with_times) @pytest.mark.parametrize( "times", [ np.arange(10).astype("datetime64[D]").astype("datetime64[ns]"), date_range("2000", freq="D", periods=10), date_range("2000", freq="D", periods=10).tz_localize("UTC"), ], ) @pytest.mark.parametrize("min_periods", [0, 2]) def test_ewma_with_times_equal_spacing(halflife_with_times, times, min_periods): halflife = halflife_with_times data = np.arange(10.0) data[::2] = np.nan df = DataFrame({"A": data, "time_col": date_range("2000", freq="D", periods=10)}) with tm.assert_produces_warning(FutureWarning, match="nuisance columns"): # GH#42738 result = df.ewm(halflife=halflife, min_periods=min_periods, times=times).mean() expected = df.ewm(halflife=1.0, min_periods=min_periods).mean() tm.assert_frame_equal(result, expected) def test_ewma_with_times_variable_spacing(tz_aware_fixture): tz = tz_aware_fixture halflife = "23 days" times = DatetimeIndex( ["2020-01-01", "2020-01-10T00:04:05", "2020-02-23T05:00:23"] ).tz_localize(tz) data = np.arange(3) df = DataFrame(data) result = df.ewm(halflife=halflife, times=times).mean() expected = DataFrame([0.0, 0.5674161888241773, 1.545239952073459]) tm.assert_frame_equal(result, expected) def test_ewm_with_nat_raises(halflife_with_times): # GH#38535 ser = Series(range(1)) times = DatetimeIndex(["NaT"]) with pytest.raises(ValueError, match="Cannot convert NaT values to integer"): ser.ewm(com=0.1, halflife=halflife_with_times, times=times) def test_ewm_with_times_getitem(halflife_with_times): # GH 40164 halflife = halflife_with_times data = np.arange(10.0) data[::2] = np.nan times = date_range("2000", freq="D", periods=10) df = DataFrame({"A": data, "B": data}) result = df.ewm(halflife=halflife, times=times)["A"].mean() expected = df.ewm(halflife=1.0)["A"].mean() tm.assert_series_equal(result, expected) @pytest.mark.parametrize("arg", ["com", "halflife", "span", "alpha"]) def test_ewm_getitem_attributes_retained(arg, adjust, ignore_na): # GH 40164 kwargs = {arg: 1, "adjust": adjust, "ignore_na": ignore_na} ewm = DataFrame({"A": range(1), "B": range(1)}).ewm(**kwargs) expected = {attr: getattr(ewm, attr) for attr in ewm._attributes} ewm_slice = ewm["A"] result = {attr: getattr(ewm, attr) for attr in ewm_slice._attributes} assert result == expected def test_ewm_vol_deprecated(): ser = Series(range(1)) with tm.assert_produces_warning(FutureWarning): result = ser.ewm(com=0.1).vol() expected = ser.ewm(com=0.1).std() tm.assert_series_equal(result, expected) def test_ewma_times_adjust_false_raises(): # GH 40098 with pytest.raises( NotImplementedError, match="times is not supported with adjust=False." ): Series(range(1)).ewm( 0.1, adjust=False, times=date_range("2000", freq="D", periods=1) ) @pytest.mark.parametrize( "func, expected", [ [ "mean", DataFrame( { 0: range(5), 1: range(4, 9), 2: [7.428571, 9, 10.571429, 12.142857, 13.714286], }, dtype=float, ), ], [ "std", DataFrame( { 0: [np.nan] * 5, 1: [4.242641] * 5, 2: [4.6291, 5.196152, 5.781745, 6.380775, 6.989788], } ), ], [ "var", DataFrame( { 0: [np.nan] * 5, 1: [18.0] * 5, 2: [21.428571, 27, 33.428571, 40.714286, 48.857143], } ), ], ], ) def test_float_dtype_ewma(func, expected, float_numpy_dtype): # GH#42452 df = DataFrame( {0: range(5), 1: range(6, 11), 2: range(10, 20, 2)}, dtype=float_numpy_dtype ) e = df.ewm(alpha=0.5, axis=1) result = getattr(e, func)() tm.assert_frame_equal(result, expected) def test_times_string_col_deprecated(): # GH 43265 data = np.arange(10.0) data[::2] = np.nan df = DataFrame({"A": data, "time_col": date_range("2000", freq="D", periods=10)}) with tm.assert_produces_warning(FutureWarning, match="Specifying times"): result = df.ewm(halflife="1 day", min_periods=0, times="time_col").mean() expected = df.ewm(halflife=1.0, min_periods=0).mean() tm.assert_frame_equal(result, expected) def test_ewm_sum_adjust_false_notimplemented(): data = Series(range(1)).ewm(com=1, adjust=False) with pytest.raises(NotImplementedError, match="sum is not"): data.sum() @pytest.mark.parametrize( "expected_data, ignore", [[[10.0, 5.0, 2.5, 11.25], False], [[10.0, 5.0, 5.0, 12.5], True]], ) def test_ewm_sum(expected_data, ignore): # xref from Numbagg tests # https://github.com/numbagg/numbagg/blob/v0.2.1/numbagg/test/test_moving.py#L50 data = Series([10, 0, np.nan, 10]) result = data.ewm(alpha=0.5, ignore_na=ignore).sum() expected = Series(expected_data) tm.assert_series_equal(result, expected) def test_ewma_adjust(): vals = Series(np.zeros(1000)) vals[5] = 1 result = vals.ewm(span=100, adjust=False).mean().sum() assert np.abs(result - 1) < 1e-2 def test_ewma_cases(adjust, ignore_na): # try adjust/ignore_na args matrix s = Series([1.0, 2.0, 4.0, 8.0]) if adjust: expected = Series([1.0, 1.6, 2.736842, 4.923077]) else: expected = Series([1.0, 1.333333, 2.222222, 4.148148]) result = s.ewm(com=2.0, adjust=adjust, ignore_na=ignore_na).mean() tm.assert_series_equal(result, expected) def test_ewma_nan_handling(): s = Series([1.0] + [np.nan] * 5 + [1.0]) result = s.ewm(com=5).mean() tm.assert_series_equal(result, Series([1.0] * len(s))) s = Series([np.nan] * 2 + [1.0] + [np.nan] * 2 + [1.0]) result = s.ewm(com=5).mean() tm.assert_series_equal(result, Series([np.nan] * 2 + [1.0] * 4)) @pytest.mark.parametrize( "s, adjust, ignore_na, w", [ ( Series([np.nan, 1.0, 101.0]), True, False, [np.nan, (1.0 - (1.0 / (1.0 + 2.0))), 1.0], ), ( Series([np.nan, 1.0, 101.0]), True, True, [np.nan, (1.0 - (1.0 / (1.0 + 2.0))), 1.0], ), ( Series([np.nan, 1.0, 101.0]), False, False, [np.nan, (1.0 - (1.0 / (1.0 + 2.0))), (1.0 / (1.0 + 2.0))], ), ( Series([np.nan, 1.0, 101.0]), False, True, [np.nan, (1.0 - (1.0 / (1.0 + 2.0))), (1.0 / (1.0 + 2.0))], ), ( Series([1.0, np.nan, 101.0]), True, False, [(1.0 - (1.0 / (1.0 + 2.0))) ** 2, np.nan, 1.0], ), ( Series([1.0, np.nan, 101.0]), True, True, [(1.0 - (1.0 / (1.0 + 2.0))), np.nan, 1.0], ), ( Series([1.0, np.nan, 101.0]), False, False, [(1.0 - (1.0 / (1.0 + 2.0))) ** 2, np.nan, (1.0 / (1.0 + 2.0))], ), ( Series([1.0, np.nan, 101.0]), False, True, [(1.0 - (1.0 / (1.0 + 2.0))), np.nan, (1.0 / (1.0 + 2.0))], ), ( Series([np.nan, 1.0, np.nan, np.nan, 101.0, np.nan]), True, False, [np.nan, (1.0 - (1.0 / (1.0 + 2.0))) ** 3, np.nan, np.nan, 1.0, np.nan], ), ( Series([np.nan, 1.0, np.nan, np.nan, 101.0, np.nan]), True, True, [np.nan, (1.0 - (1.0 / (1.0 + 2.0))), np.nan, np.nan, 1.0, np.nan], ), ( Series([np.nan, 1.0, np.nan, np.nan, 101.0, np.nan]), False, False, [ np.nan, (1.0 - (1.0 / (1.0 + 2.0))) ** 3, np.nan, np.nan, (1.0 / (1.0 + 2.0)), np.nan, ], ), ( Series([np.nan, 1.0, np.nan, np.nan, 101.0, np.nan]), False, True, [ np.nan, (1.0 - (1.0 / (1.0 + 2.0))), np.nan, np.nan, (1.0 / (1.0 + 2.0)), np.nan, ], ), ( Series([1.0, np.nan, 101.0, 50.0]), True, False, [ (1.0 - (1.0 / (1.0 + 2.0))) ** 3, np.nan, (1.0 - (1.0 / (1.0 + 2.0))), 1.0, ], ), ( Series([1.0, np.nan, 101.0, 50.0]), True, True, [ (1.0 - (1.0 / (1.0 + 2.0))) ** 2, np.nan, (1.0 - (1.0 / (1.0 + 2.0))), 1.0, ], ), ( Series([1.0, np.nan, 101.0, 50.0]), False, False, [ (1.0 - (1.0 / (1.0 + 2.0))) ** 3, np.nan, (1.0 - (1.0 / (1.0 + 2.0))) * (1.0 / (1.0 + 2.0)), (1.0 / (1.0 + 2.0)) * ((1.0 - (1.0 / (1.0 + 2.0))) ** 2 + (1.0 / (1.0 + 2.0))), ], ), ( Series([1.0, np.nan, 101.0, 50.0]), False, True, [ (1.0 - (1.0 / (1.0 + 2.0))) ** 2, np.nan, (1.0 - (1.0 / (1.0 + 2.0))) * (1.0 / (1.0 + 2.0)), (1.0 / (1.0 + 2.0)), ], ), ], ) def test_ewma_nan_handling_cases(s, adjust, ignore_na, w): # GH 7603 expected = (s.multiply(w).cumsum() / Series(w).cumsum()).fillna(method="ffill") result = s.ewm(com=2.0, adjust=adjust, ignore_na=ignore_na).mean()
tm.assert_series_equal(result, expected)
pandas._testing.assert_series_equal
'''Module for ML algorithm''' import pandas as pd import numpy as np from joblib import load df = pd.read_csv('./data/working_ratings.csv', index_col=0) nmf = load('./models/nmf.joblib') def simple_recommender(): pass def nmf_recommender(user_input, rating_data=df, model=nmf, n_movies:int =5): user =
pd.DataFrame(user_input, columns=rating_data.columns, index=[rating_data.shape[0]+1])
pandas.DataFrame
import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns pd.set_option('display.max_columns', 500) def clean_features(data, type): df = pd.DataFrame(data) # df = df.drop("PassengerId", axis=1) df.set_index("PassengerId") df = df.drop(columns=['Cabin', 'Name', 'Ticket']) print((df.Fare == 0).sum()) if type == True: analyse_data(df) return df def analyse_data(df): print(df.Survived.value_counts(normalize=True)) fig, axes = plt.subplots(2, 4, figsize=(16, 10)) df["Faily_count"] = df.SibSp + df.Parch df["Faily_count"] =
pd.cut(df["Faily_count"], bins=[-1, 0, 3, 7, 16], labels=["Alone", "Small Family", "Medium Family", "Big Family"])
pandas.cut
import tensorflow as tf import numpy as np import scipy.io as sio import pandas as pd import os import csv from feature_encoding import * from keras.models import load_model from keras.utils import to_categorical import Efficient_CapsNet_sORF150 import Efficient_CapsNet_sORF250 import lightgbm as lgb from sklearn.metrics import roc_auc_score import sys from optparse import OptionParser ##read Fasta sequence def readFasta(file): if os.path.exists(file) == False: print('Error: "' + file + '" does not exist.') sys.exit(1) with open(file) as f: records = f.read() if re.search('>', records) == None: print('The input file seems not in fasta format.') sys.exit(1) records = records.split('>')[1:] myFasta = [] for fasta in records: array = fasta.split('\n') name, sequence = array[0].split()[0], re.sub('[^ARNDCQEGHILKMFPSTWYV-]', '-', ''.join(array[1:]).upper()) myFasta.append([name, sequence]) return myFasta ##extract sORF sequence def get_sORF(fastas): sORF_seq = [] for i in fastas: name, seq = i[0], re.sub('-', '', i[1]) g = 0 if len(seq) > 303: for j in range(len(seq)-2): seg_start = seq[j:j+3] if seg_start == 'ATG': for k in range(j+3, len(seq)-2, 3): seg_end = seq[k:k+3] if seg_end == 'TAA': sequence = seq[j:k+3] if np.mod(len(sequence), 3) == 0 and 12 <= len(sequence) <= 303: g+=1 sequence_name = '>' + name + '_sORF' + str(g) sORF_seq.append([sequence_name, sequence]) break if seg_end == 'TAG': sequence = seq[j:k+3] if np.mod(len(sequence), 3) == 0 and 12 <= len(sequence) <= 303: g+=1 sequence_name = '>' + name + '_sORF' + str(g) sORF_seq.append([sequence_name, sequence]) break if seg_end == 'TGA': sequence = seq[j:k+3] if np.mod(len(sequence), 3) == 0 and 12 <= len(sequence) <= 303: g+=1 sequence_name = '>' + name + '_sORF' + str(g) sORF_seq.append([sequence_name, sequence]) break elif len(seq) <= 303 and np.mod(len(seq), 3) != 0: for j in range(len(seq)-2): seg_start = seq[j:j+3] if seg_start == 'ATG': for k in range(j+3, len(seq)-2, 3): seg_end = seq[k:k+3] if seg_end == 'TAA': sequence = seq[j:k+3] if np.mod(len(sequence), 3) == 0 and 12 <= len(sequence) <= 303: g+=1 sequence_name = '>' + name + '_sORF' + str(g) sORF_seq.append([sequence_name, sequence]) break if seg_end == 'TAG': sequence = seq[j:k+3] if np.mod(len(sequence), 3) == 0 and 12 <= len(sequence) <= 303: g+=1 sequence_name = '>' + name + '_sORF' + str(g) sORF_seq.append([sequence_name, sequence]) break if seg_end == 'TGA': sequence = seq[j:k+3] if np.mod(len(sequence), 3) == 0 and 12 <= len(sequence) <= 303: g+=1 sequence_name = '>' + name + '_sORF' + str(g) sORF_seq.append([sequence_name, sequence]) break elif seq[0:3] == 'ATG' and seq[len(seq)-3:len(seq)] == 'TAA' and np.mod(len(seq), 3) == 0 and 12 <= len(seq) <= 303: sORF_seq.append([name, seq]) elif seq[0:3] == 'ATG' and seq[len(seq)-3:len(seq)] == 'TAG' and np.mod(len(seq), 3) == 0 and 12 <= len(seq) <= 303: sORF_seq.append([name, seq]) elif seq[0:3] == 'ATG' and seq[len(seq)-3:len(seq)] == 'TGA' and np.mod(len(seq), 3) == 0 and 12 <= len(seq) <= 303: sORF_seq.append([name, seq]) return sORF_seq ##get protein sequence def get_protein(fastas): protein_seq=[] start_codon = 'ATG' codon_table = { 'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M', 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T', 'AAC': 'N', 'AAT': 'N', 'AAA': 'K', 'AAG': 'K', 'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R', 'CTA': 'L', 'CTC': 'L', 'CTG': 'L', 'CTT': 'L', 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P', 'CAC': 'H', 'CAT': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R', 'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V', 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A', 'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E', 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGT': 'G', 'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S', 'TTC': 'F', 'TTT': 'F', 'TTA': 'L', 'TTG': 'L', 'TAC': 'Y', 'TAT': 'Y', 'TAA': '', 'TAG': '', 'TGC': 'C', 'TGT': 'C', 'TGA': '', 'TGG': 'W'} for i in fastas: name, seq = i[0], re.sub('-', '', i[1]) start_site = re.search(start_codon, seq) protein = '' for site in range(start_site.start(), len(seq), 3): protein = protein + codon_table[seq[site:site+3]] protein_name = '>Micropeptide_' + name protein_seq.append([protein_name, protein]) return protein_seq ##extract features def feature_encode(datapath, dna_seq, protein_seq, s_type, d_type): if s_type == 'H.sapiens': if d_type == 'CDS': c_m = pd.read_csv(datapath + 'human_cds_trainp_6mermean.csv', header=None, delimiter=',') nc_m = pd.read_csv(datapath + 'human_cds_trainn_6mermean.csv', header=None, delimiter=',') Tc_pos1 = pd.read_csv(datapath + 'human_cds_trainp_framed_3mer_1.csv', header=None, delimiter=',') Tc_neg1 = pd.read_csv(datapath + 'human_cds_trainn_framed_3mer_1.csv', header=None, delimiter=',') Tc_pos2 = pd.read_csv(datapath + 'human_cds_trainp_framed_3mer_2.csv', header=None, delimiter=',') Tc_neg2 = pd.read_csv(datapath + 'human_cds_trainn_framed_3mer_2.csv', header=None, delimiter=',') Tc_pos3 = pd.read_csv(datapath + 'human_cds_trainp_framed_3mer_3.csv', header=None, delimiter=',') Tc_neg3 = pd.read_csv(datapath + 'human_cds_trainn_framed_3mer_3.csv', header=None, delimiter=',') fea1_1 = np.array(ratio_ORFlength_hcds(dna_seq)) dna_fea = np.array(extract_DNAfeatures(dna_seq, c_m, nc_m, Tc_pos1, Tc_neg1, Tc_pos2, Tc_neg2, Tc_pos3, Tc_neg3, fea1_1)) elif d_type == 'non-CDS': c_m = pd.read_csv(datapath + 'human_noncds_trainp_6mermean.csv', header=None, delimiter=',') nc_m = pd.read_csv(datapath + 'human_noncds_trainn_6mermean.csv', header=None, delimiter=',') Tc_pos1 = pd.read_csv(datapath + 'human_noncds_trainp_framed_3mer_1.csv', header=None, delimiter=',') Tc_neg1 = pd.read_csv(datapath + 'human_noncds_trainn_framed_3mer_1.csv', header=None, delimiter=',') Tc_pos2 = pd.read_csv(datapath + 'human_noncds_trainp_framed_3mer_2.csv', header=None, delimiter=',') Tc_neg2 = pd.read_csv(datapath + 'human_noncds_trainn_framed_3mer_2.csv', header=None, delimiter=',') Tc_pos3 = pd.read_csv(datapath + 'human_noncds_trainp_framed_3mer_3.csv', header=None, delimiter=',') Tc_neg3 = pd.read_csv(datapath + 'human_noncds_trainn_framed_3mer_3.csv', header=None, delimiter=',') fea1_1 = np.array(ratio_ORFlength_hnoncds(dna_seq)) dna_fea = np.array(extract_DNAfeatures(dna_seq, c_m, nc_m, Tc_pos1, Tc_neg1, Tc_pos2, Tc_neg2, Tc_pos3, Tc_neg3, fea1_1)) else: print("Type error") elif s_type == 'M.musculus': if d_type == 'CDS': c_m = pd.read_csv(datapath + 'mouse_cds_trainp_6mermean.csv', header=None, delimiter=',') nc_m = pd.read_csv(datapath + 'mouse_cds_trainn_6mermean.csv', header=None, delimiter=',') Tc_pos1 = pd.read_csv(datapath + 'mouse_cds_trainp_framed_3mer_1.csv', header=None, delimiter=',') Tc_neg1 = pd.read_csv(datapath + 'mouse_cds_trainn_framed_3mer_1.csv', header=None, delimiter=',') Tc_pos2 = pd.read_csv(datapath + 'mouse_cds_trainp_framed_3mer_2.csv', header=None, delimiter=',') Tc_neg2 = pd.read_csv(datapath + 'mouse_cds_trainn_framed_3mer_2.csv', header=None, delimiter=',') Tc_pos3 = pd.read_csv(datapath + 'mouse_cds_trainp_framed_3mer_3.csv', header=None, delimiter=',') Tc_neg3 = pd.read_csv(datapath + 'mouse_cds_trainn_framed_3mer_3.csv', header=None, delimiter=',') fea1_1 = np.array(ratio_ORFlength_mcds(dna_seq)) dna_fea = np.array(extract_DNAfeatures(dna_seq, c_m, nc_m, Tc_pos1, Tc_neg1, Tc_pos2, Tc_neg2, Tc_pos3, Tc_neg3, fea1_1)) elif d_type == 'non-CDS': c_m = pd.read_csv(datapath + 'mouse_noncds_trainp_6mermean.csv', header=None, delimiter=',') nc_m = pd.read_csv(datapath + 'mouse_noncds_trainn_6mermean.csv', header=None, delimiter=',') Tc_pos1 = pd.read_csv(datapath + 'mouse_noncds_trainp_framed_3mer_1.csv', header=None, delimiter=',') Tc_neg1 = pd.read_csv(datapath + 'mouse_noncds_trainn_framed_3mer_1.csv', header=None, delimiter=',') Tc_pos2 = pd.read_csv(datapath + 'mouse_noncds_trainp_framed_3mer_2.csv', header=None, delimiter=',') Tc_neg2 = pd.read_csv(datapath + 'mouse_noncds_trainn_framed_3mer_2.csv', header=None, delimiter=',') Tc_pos3 = pd.read_csv(datapath + 'mouse_noncds_trainp_framed_3mer_3.csv', header=None, delimiter=',') Tc_neg3 = pd.read_csv(datapath + 'mouse_noncds_trainn_framed_3mer_3.csv', header=None, delimiter=',') fea1_1 = np.array(ratio_ORFlength_mnoncds(dna_seq)) dna_fea = np.array(extract_DNAfeatures(dna_seq, c_m, nc_m, Tc_pos1, Tc_neg1, Tc_pos2, Tc_neg2, Tc_pos3, Tc_neg3, fea1_1)) else: print("Type error") elif s_type == 'D.melanogaster': if d_type == 'CDS': c_m = pd.read_csv(datapath + 'fruitfly_cds_trainp_6mermean.csv', header=None, delimiter=',') nc_m = pd.read_csv(datapath + 'fruitfly_cds_trainn_6mermean.csv', header=None, delimiter=',') Tc_pos1 =
pd.read_csv(datapath + 'fruitfly_cds_trainp_framed_3mer_1.csv', header=None, delimiter=',')
pandas.read_csv
import pandas as pd import numpy as np import os import errno import re, arrow import warnings, glob ''' time_to_numeric: convert time to excel numeric format read_tecplot: read single zone multi columns tecplot file read_csv: load csv and change time to numeric on the fly colum_match: find the common row or merge data.frame ''' def time_to_numeric(t, format='%Y-%m-%d %H:%M'): ''' convert time from ISO8601 format to numeric in days since 1900 The format is default as %Y%m%d, however YYYYMMDD format also work YYYYMMDD is convinience for arrow object ''' ## reference date: exel numeric date format counts number of days after 1900-01-01 ref_date = '1900-01-01 00:00' date_format = format ## %Y%m%d format try: a = pd.to_datetime(t, format = date_format) - pd.to_datetime(ref_date, format ='%Y-%m-%d %H:%M') a = a/np.timedelta64(1, 'D') + 2 return(a) except: pass ## YYYYMMDD format try: start_date = arrow.get(ref_date, 'YYYY-MM-DD HH:mm') # a = t.map(lambda x: ((arrow.get(str(x), date_format) - start_date).days) +2) a = [((arrow.get(str(x), date_format) - start_date).days) +2 for x in t] return(a) except: raise ValueError('Not able to convert dataframe to format {}. \n {}'.format(date_format, t)) def read_tecplot(file_directory, file_name, sep='\t', ldebug=False): ''' read tecplot as data frame sep: set equal to \s for space delimited ''' file_path = os.path.join(file_directory, file_name) # Load column names if not os.path.exists(file_path): raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), file_path) with open(file_path, 'r') as handl: for num,line in enumerate(handl): if line.lower().startswith ("variable"): header = line.strip() [11:] if re.match(r"^\d+.*$",line): skip_num = num if ldebug: print('number of row to skip: {}'.format(skip_num)) break if ldebug: print(header) # replace "" and seperate string to list of names column_names = header.replace('"'," ").replace(','," ").split(' ') column_names = [x for x in column_names if x] if ldebug: print(column_names) # column_names = list(map(str.strip, column_names)) try: df= pd.read_table (file_path, header=None, sep= sep, skiprows = skip_num, engine='python' ) if ldebug: print(df.shape) except: print('ERROR: unable to open file {}'.format(file_path)) if not len(df.columns) == len(column_names): print('ERROR: number of columns in the data does not match with Tecplot header: {}'.format(column_names)) df.columns = column_names return(df) def read_csv(file_directory, file_name, to_exceldate= False, Date_col= 'Date', format='%Y-%m-%d'): file_path = os.path.join(file_directory, file_name) header= 'infer' # Load column names if not os.path.exists(file_path): raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), file_path) with open(file_path, 'r') as handl: line = handl.readline() if re.match(r"^\d+.*$",line): warnings.warn('File has no header. First line:' + line) header=None try: df= pd.read_csv (file_path, header=header) except: print('ERROR: unable to open file {}'.format(file_path)) if to_exceldate: try: df[Date_col] = time_to_numeric(df[Date_col], format=format) except: print('ERROR: unable to open file {}'.format(file_path)) return(df) def colum_match(left, right, left_on = 'Date', right_on = 'Date'): ''' find the the rows in dataframe which value match with numpy array m_value ''' if not isinstance(left, pd.DataFrame): raise TypeError('ERROR: input df not instance of pd.DataFrame') if isinstance(right, (np.ndarray, np.generic, pd.core.series.Series)): left = left.loc[~left[left_on].isin(right)] df_merge = left.reset_index(drop=True) elif isinstance(right, pd.DataFrame): df_merge =
pd.merge(left=left, how='inner', right=right, left_on=left_on, right_on=right_on)
pandas.merge
from SPARQLWrapper import SPARQLWrapper, JSON import pandas as pd import pickle, hashlib class QTLSEARCH: def __init__(self, search, qtls, go_annotations): self.qtls = qtls self.search = search self.go_annotations = go_annotations self.p_uniprot_reviewed = 1.00 self.p_uniprot_unreviewed = 0.95 self.loss_up_ortholog = 0.85 self.loss_down_ortholog = 0.85 self.loss_up_paralog = 0.7225 self.loss_down_paralog = 0.7225 #actions print("\033[1m" + "=== GET DATA ===" + "\033[0m") self.qtl_gene_roots, self.qtl_gene_protein, self.hog_group_trees, self.hog_group_genes = self.__collect_data() print("\033[1m" + "=== COMPUTATIONS ===" + "\033[0m") self.__do_computations() print("\033[1m" + "=== CREATED QTLSEARCH OBJECT ===" + "\033[0m") def report(self): reports = [] for i in range(0,len(self.qtls)): report = [] for gene in self.qtls[i]: if gene in self.qtl_gene_roots.keys(): if self.qtl_gene_protein[gene] in self.hog_group_genes[self.qtl_gene_roots[gene]].index : p_initial = self.hog_group_genes[self.qtl_gene_roots[gene]].loc[self.qtl_gene_protein[gene],"p_initial"] p_final = self.hog_group_genes[self.qtl_gene_roots[gene]].loc[self.qtl_gene_protein[gene],"p_final"] report.append([gene, p_initial, p_final, self.qtl_gene_protein[gene]]) df = pd.DataFrame(report) df.columns = ["gene", "p_initial", "p_final", "protein" ] df = df.set_index("gene") df.sort_values(by=["p_final","p_initial","gene"], ascending=[0, 0, 1], inplace=True) reports.append(df) return(reports) def __collect_data(self): #define variables hog_group_trees = pd.Series() hog_group_genes = pd.Series() #root in hog tree for each gene qtl_gene_roots = pd.Series() qtl_gene_protein = pd.Series() gene_p_initial = pd.Series() #start collecting for qtl in self.qtls: for gene in qtl: if not(gene in qtl_gene_protein.keys()): p_qtl_initial = 1.0/len(qtl) #start searching print("\033[1m"+"Search for "+gene+"\033[0m") #first, go up in the hog-tree parent_groups = self.search.get_parent_groups(gene) if len(parent_groups)>0: #define the root of the tree qtl_gene_roots[gene] = parent_groups.index[0] qtl_gene_protein[gene] = parent_groups.loc[parent_groups.index[0]].protein print("- root is "+qtl_gene_roots[gene]) if qtl_gene_roots[gene] in hog_group_trees.index: print("- tree already created") if qtl_gene_protein[gene] in gene_p_initial.index: hog_group_genes[qtl_gene_roots[gene]].loc[qtl_gene_protein[gene],"p_initial"] = max(gene_p_initial[qtl_gene_protein[gene]], p_qtl_initial) else: hog_group_genes[qtl_gene_roots[gene]].loc[qtl_gene_protein[gene],"p_initial"] = p_qtl_initial else: #go down the hog-tree, just to find tree structure hog_group_trees[qtl_gene_roots[gene]] = self.search.get_child_groups(qtl_gene_roots[gene]) hog_group_trees[qtl_gene_roots[gene]].loc[:,"p_initial"] = pd.Series(0.0, index=hog_group_trees[qtl_gene_roots[gene]].index) hog_group_trees[qtl_gene_roots[gene]].loc[:,"p_up"] = pd.Series(0.0, index=hog_group_trees[qtl_gene_roots[gene]].index) hog_group_trees[qtl_gene_roots[gene]].loc[:,"p_down"] = pd.Series(0.0, index=hog_group_trees[qtl_gene_roots[gene]].index) print("- tree of groups fetched: "+str(len(hog_group_trees[qtl_gene_roots[gene]]))) #go down again, now to find proteins tree_proteins = self.search.get_child_proteins(qtl_gene_roots[gene]) tree_proteins_uniprot = self.search.get_child_proteins_uniprot(qtl_gene_roots[gene]) print("- proteins within tree fetched: "+str(len(tree_proteins))) print("- uniprot proteins within tree fetched: "+str(len(tree_proteins_uniprot))) #create final list of checked proteins hog_group_genes[qtl_gene_roots[gene]] = tree_proteins hog_group_genes[qtl_gene_roots[gene]].loc[:,"reviewed"] = pd.Series("unknown", index=hog_group_genes[qtl_gene_roots[gene]].index) hog_group_genes[qtl_gene_roots[gene]].loc[:,"p_initial"] = pd.Series(0.0, index=hog_group_genes[qtl_gene_roots[gene]].index) hog_group_genes[qtl_gene_roots[gene]].loc[:,"p_up"] = pd.Series(0.0, index=hog_group_genes[qtl_gene_roots[gene]].index) hog_group_genes[qtl_gene_roots[gene]].loc[:,"p_final"] = pd.Series(0.0, index=hog_group_genes[qtl_gene_roots[gene]].index) #create uniprot list for checking list_proteins = list(tree_proteins_uniprot.index) #divide proteins into chunks (sparql endpoint doesn't allow huge lists) n=10000 lists_proteins = [list_proteins[i * n:(i + 1) * n] for i in range((len(list_proteins) + n - 1) // n )] checked_proteins_list = [] #check chunks of proteins in uniprot for i in range(0,len(lists_proteins)): checked_proteins_sublist = self.search.check_uniprot_annotations(lists_proteins[i], list(self.go_annotations.index)) print(" * check proteins ("+str((i*n)+1)+"-"+str(min((i+1)*n,len(tree_proteins)))+"): "+ str(len(checked_proteins_sublist))+" with required annotation") #collect group labels to give some indication of origin mask = list(tree_proteins_uniprot.loc[checked_proteins_sublist.index].protein.unique()) mask = list(set(tree_proteins.index).intersection(mask)) sublist_labels = list(tree_proteins.loc[mask].label.dropna().unique()) if len(sublist_labels)>0: print(" -> "+", ".join(sublist_labels)) #add checked proteins from chunk to the collective list checked_proteins_list.append(checked_proteins_sublist) if len(checked_proteins_list)>0: checked_proteins = pd.concat(checked_proteins_list) else: checked_proteins = [] #update reviewed hog_group_genes[qtl_gene_roots[gene]].reviewed = None if qtl_gene_protein[gene] in gene_p_initial.index: hog_group_genes[qtl_gene_roots[gene]].loc[qtl_gene_protein[gene],"p_initial"] = max(gene_p_initial[qtl_gene_protein[gene]], p_qtl_initial) else: hog_group_genes[qtl_gene_roots[gene]].loc[qtl_gene_protein[gene],"p_initial"] = p_qtl_initial if len(checked_proteins)>0: maskUnreviewed = list(set(tree_proteins_uniprot.index).intersection(checked_proteins.loc[checked_proteins.reviewed=="false"].index)) maskUnreviewed = list(set(hog_group_genes[qtl_gene_roots[gene]].index).intersection(tree_proteins_uniprot.loc[maskUnreviewed].protein.unique())) maskUnreviewed = hog_group_genes[qtl_gene_roots[gene]].loc[maskUnreviewed] maskReviewed = list(set(tree_proteins_uniprot.index).intersection(checked_proteins.loc[checked_proteins.reviewed=="true"].index)) maskReviewed = list(set(hog_group_genes[qtl_gene_roots[gene]].index).intersection(tree_proteins_uniprot.loc[maskReviewed].protein.unique())) maskReviewed = hog_group_genes[qtl_gene_roots[gene]].loc[maskReviewed] hog_group_genes[qtl_gene_roots[gene]].loc[maskUnreviewed.index,"reviewed"] = False hog_group_genes[qtl_gene_roots[gene]].loc[maskReviewed.index,"reviewed"] = True #update probability for reviewedProtein in hog_group_genes[qtl_gene_roots[gene]][hog_group_genes[qtl_gene_roots[gene]].reviewed==True].index: hog_group_genes[qtl_gene_roots[gene]].loc[reviewedProtein,"p_initial"] = max(hog_group_genes[qtl_gene_roots[gene]].loc[reviewedProtein,"p_initial"],self.p_uniprot_reviewed) for unreviewedProtein in hog_group_genes[qtl_gene_roots[gene]][hog_group_genes[qtl_gene_roots[gene]].reviewed==False].index: hog_group_genes[qtl_gene_roots[gene]].loc[unreviewedProtein,"p_initial"] = max(hog_group_genes[qtl_gene_roots[gene]].loc[unreviewedProtein,"p_initial"],self.p_uniprot_unreviewed) for positiveProbablilityProtein in hog_group_genes[qtl_gene_roots[gene]].loc[hog_group_genes[qtl_gene_roots[gene]]["p_initial"]>0].index: if positiveProbablilityProtein in gene_p_initial.index: gene_p_initial[positiveProbablilityProtein] = max(hog_group_genes[qtl_gene_roots[gene]].loc[positiveProbablilityProtein,"p_initial"],gene_p_initial[positiveProbablilityProtein]) else: gene_p_initial[positiveProbablilityProtein] = hog_group_genes[qtl_gene_roots[gene]].loc[positiveProbablilityProtein,"p_initial"] #report results print("- checked "+str(len(list_proteins))+" uniprot proteins: "+str(len(checked_proteins))+" with required annotation") #including details about reviewed status if len(checked_proteins)>0: reviewedList = checked_proteins.groupby("reviewed") if len(reviewedList)>0: for label,number in reviewedList.size().items(): print(" -> for "+str(number)+" of these "+str(len(list_proteins))+" items, reviewed is "+str(label)) print("- checked "+str(len(tree_proteins))+" proteins: "+str(len(hog_group_genes[qtl_gene_roots[gene]]["reviewed"].dropna()))+" linked to uniprot with required annotation") if len(hog_group_genes[qtl_gene_roots[gene]])>0: reviewedList = hog_group_genes[qtl_gene_roots[gene]].groupby("reviewed") if len(reviewedList)>0: for label,number in reviewedList.size().items(): print(" -> for "+str(number)+" of these "+str(len(hog_group_genes[qtl_gene_roots[gene]]))+" items reviewed is marked as "+str(label)) else: #no hog groups, can't do anything with this... print("- no groups found") #update initial probabilities from other genes and qtls for gene in qtl_gene_protein.keys(): for protein in hog_group_genes[qtl_gene_roots[gene]].keys(): if protein in gene_p_initial.keys(): hog_group_genes[qtl_gene_roots[gene]].loc[protein,"p_initial"] = gene_p_initial[protein]; return(qtl_gene_roots, qtl_gene_protein, hog_group_trees, hog_group_genes); def __do_computations(self): def get_p_up(gene, group): if group in self.hog_group_trees[self.qtl_gene_roots[gene]].index: p = self.hog_group_trees[self.qtl_gene_roots[gene]].loc[group,"p_initial"] if "type" in self.hog_group_trees[self.qtl_gene_roots[gene]].keys(): type = self.hog_group_trees[self.qtl_gene_roots[gene]].loc[group,"type"] if "group" in self.hog_group_trees[self.qtl_gene_roots[gene]].keys(): proteins = self.hog_group_genes[self.qtl_gene_roots[gene]].loc[self.hog_group_genes[self.qtl_gene_roots[gene]].group==group] for protein in proteins.index: if type=="ortholog": p += self.loss_up_ortholog * self.hog_group_genes[self.qtl_gene_roots[gene]].loc[protein,"p_initial"] elif type=="paralog": p += self.loss_up_paralog * self.hog_group_genes[self.qtl_gene_roots[gene]].loc[protein,"p_initial"] if "parent" in self.hog_group_trees[self.qtl_gene_roots[gene]].keys(): children = self.hog_group_trees[self.qtl_gene_roots[gene]].loc[self.hog_group_trees[self.qtl_gene_roots[gene]].parent==group] for child in children.index: if type=="ortholog": p += self.loss_up_ortholog * get_p_up(gene, child) elif type=="paralog": p += self.loss_up_paralog * get_p_up(gene, child) self.hog_group_trees[self.qtl_gene_roots[gene]].loc[group,"p_up"] = p return p else: return 0 def set_p_down(gene, group): if group in self.hog_group_trees[self.qtl_gene_roots[gene]].index: p = self.hog_group_trees[self.qtl_gene_roots[gene]].loc[group,"p_up"] if "type" in self.hog_group_trees[self.qtl_gene_roots[gene]].keys(): type = self.hog_group_trees[self.qtl_gene_roots[gene]].loc[group,"type"] children = self.hog_group_trees[self.qtl_gene_roots[gene]].loc[self.hog_group_trees[self.qtl_gene_roots[gene]].parent==group] proteins = self.hog_group_genes[self.qtl_gene_roots[gene]].loc[self.hog_group_genes[self.qtl_gene_roots[gene]].group==group] parent = self.hog_group_trees[self.qtl_gene_roots[gene]].loc[group,"parent"] if not(parent==None): parent_type = self.hog_group_trees[self.qtl_gene_roots[gene]].loc[group,"type"] parent_p = self.hog_group_trees[self.qtl_gene_roots[gene]].loc[parent,"p_down"] if parent_type=="ortholog": p = max(p,self.loss_down_ortholog*parent_p) elif parent_type=="paralog": p = max(p,self.loss_down_paralog*parent_p) self.hog_group_trees[self.qtl_gene_roots[gene]].loc[group,"p_down"] = p for protein in proteins.index: p_protein = self.hog_group_genes[self.qtl_gene_roots[gene]].loc[protein,"p_initial"] if type=="ortholog": p_protein = max(self.loss_down_ortholog*p,p_protein) elif type=="paralog": p_protein = max(self.loss_down_paralog*p,p_protein) self.hog_group_genes[self.qtl_gene_roots[gene]].loc[protein,"p_final"] = p_protein for child in children.index: set_p_down(gene, child) for qtl in self.qtls: for gene in qtl: if gene in self.qtl_gene_roots.keys(): print("Compute for "+gene) #reset self.hog_group_trees[self.qtl_gene_roots[gene]].loc[:,"p_up"] = 0.0 self.hog_group_trees[self.qtl_gene_roots[gene]].loc[:,"p_down"] = 0.0 self.hog_group_genes[self.qtl_gene_roots[gene]].loc[:,"p_final"] = 0.0 #go up get_p_up(gene, self.qtl_gene_roots[gene]) #go down set_p_down(gene, self.qtl_gene_roots[gene]) else: print("Skip "+gene) class SEARCH: def __init__(self, url_pbg, url_oma, url_uniprot): #define cache directory self.cache = "cache/" #define url self.url_pbg = url_pbg self.url_oma = url_oma self.url_uniprot = url_uniprot #define sparql self.sparql_pbg = SPARQLWrapper(self.url_pbg) self.sparql_pbg.setReturnFormat(JSON) self.sparql_oma = SPARQLWrapper(self.url_oma) self.sparql_oma.setReturnFormat(JSON) self.sparql_uniprot = SPARQLWrapper(self.url_uniprot) self.sparql_uniprot.setReturnFormat(JSON) self.sparql_uniprot.setRequestMethod("postdirectly") self.sparql_uniprot.setMethod("POST") def cache_name(self, method, parameters) : key = method+"_"+hashlib.md5(pickle.dumps(parameters)).hexdigest() return(key) def get_location(self, id): filename = self.cache + self.cache_name("get_location", id) try: infile = open(filename,"rb") new_object = pickle.load(infile) infile.close() return(new_object) except FileNotFoundError: file = open("queries/gene_location.sparql", "r") query = file.read() file.close() self.sparql_pbg.setQuery(query % id) # JSON example response = self.sparql_pbg.query().convert() result = [] if response["results"]["bindings"]: for item in response["results"]["bindings"]: result.append([ item["gene_id"]["value"], item["location"]["value"], item["begin_ref"]["value"], item["begin_pos"]["value"], item["end_ref"]["value"], item["end_pos"]["value"]]) df = pd.DataFrame(result) df.columns = ["gene_id", "location", "begin_ref", "begin_pos", "end_ref", "end_pos" ] df = df.set_index("gene_id") df["begin_pos"] = pd.to_numeric(df["begin_pos"]) df["end_pos"] = pd.to_numeric(df["end_pos"]) #cache outfile = open(filename,"wb") pickle.dump(df, outfile) outfile.close() return df else: return pd.DataFrame() def compute_interval(self, g1, g2): locations = pd.concat([self.get_location(g1), self.get_location(g2)]) display(locations[["location"]]) if(len(locations.index)!=2) : print("unexpected number of rows in locations:",len(locations.index)) elif(locations.iloc[0]['end_pos']>locations.iloc[1]['begin_pos']) & (g1!=g2) : print("unexpected order",locations.index[0],"and",locations.index[1]) else : result = [] if locations.iloc[0]["end_pos"]>locations.iloc[0]["begin_pos"] : result.append(["begin", locations.iloc[0]["end_ref"], locations.iloc[0]["end_pos"]]) else : result.append(["begin", locations.iloc[0]["begin_ref"], locations.iloc[0]["begin_pos"]]) if locations.iloc[1]["begin_pos"]<locations.iloc[1]["end_pos"] : result.append(["end", locations.iloc[1]["begin_ref"], locations.iloc[1]["begin_pos"]]) else : result.append(["end", locations.iloc[1]["end_ref"], locations.iloc[1]["end_pos"]]) df = pd.DataFrame(result) df.columns = ["type", "ref", "pos" ] df = df.set_index("type") return df def make_interval(self, ref, start, end): result = [] result.append(["begin",ref,start]) result.append(["end",ref,end]) df = pd.DataFrame(result) df.columns = ["type", "ref", "pos" ] df = df.set_index("type") return df def interval_genes(self, interval): filename = self.cache + self.cache_name("interval_genes", interval) try: infile = open(filename,"rb") new_object = pickle.load(infile) infile.close() return(new_object) except FileNotFoundError: file = open("queries/interval_genes.sparql", "r") query = file.read() file.close() self.sparql_pbg.setQuery(query % {"beginRef" : interval.loc["begin"]["ref"], "beginPos" : interval.loc["begin"]["pos"], "endRef" : interval.loc["end"]["ref"], "endPos" : interval.loc["end"]["pos"]}) # JSON example response = self.sparql_pbg.query().convert() result = [] if response["results"]["bindings"]: for item in response["results"]["bindings"]: row = [] row.append(item["gene_id"]["value"]) row.append(item["location"]["value"]) result.append(row) df = pd.DataFrame(result) df.columns = ["gene_id", "location"] df = df.set_index("gene_id") #cache outfile = open(filename,"wb") pickle.dump(df, outfile) outfile.close() return df else: return pd.DataFrame() def get_parent_groups(self, protein): filename = self.cache + self.cache_name("get_parent_groups", protein) try: infile = open(filename,"rb") new_object = pickle.load(infile) infile.close() return(new_object) except FileNotFoundError: file = open("queries/parent_groups.sparql", "r") query = file.read() file.close() self.sparql_oma.setQuery(query % {"protein" : "\""+protein+"\""}) # JSON example response = self.sparql_oma.query().convert() result = [] if response["results"]["bindings"]: for item in response["results"]["bindings"]: result.append([ item["level"]["value"], item["group"]["value"], item["type"]["value"], item["protein"]["value"]]) df = pd.DataFrame(result) df.columns = ["level", "group", "type", "protein" ] df.drop_duplicates(subset ="group", keep = "first", inplace = True) df = df.set_index("group") df["level"] = pd.to_numeric(df["level"]) #cache outfile = open(filename,"wb") pickle.dump(df, outfile) outfile.close() return df else: return pd.DataFrame() #get only group paths that end with a uniprot annotated protein def get_child_groups(self, parent): filename = self.cache + self.cache_name("get_child_groups", parent) try: infile = open(filename,"rb") new_object = pickle.load(infile) infile.close() return(new_object) except FileNotFoundError: file = open("queries/child_groups.sparql", "r") query = file.read() file.close() self.sparql_oma.setQuery(query % {"parent" : "<"+parent+">"}) # JSON example response = self.sparql_oma.query().convert() result = [] if response["results"]["bindings"]: for item in response["results"]["bindings"]: row = [ item["group"]["value"], item["type"]["value"] ] if "parent" in item.keys() : row.append(item["parent"]["value"]) else: row.append(None) if "parent_type" in item.keys() : row.append(item["parent_type"]["value"]) else: row.append(None) if "label" in item.keys() : row.append(item["label"]["value"]) else: row.append(None) if "parent_label" in item.keys(): row.append(item["parent_label"]["value"]) else: row.append(None) result.append(row) df = pd.DataFrame(result) df.columns = ["group", "type", "parent", "parent_type", "label", "parent_label" ] df.drop_duplicates(subset ="group", keep = "first", inplace = True) df = df.set_index("group") #cache outfile = open(filename,"wb") pickle.dump(df, outfile) outfile.close() return df else: return pd.DataFrame() #get uniprot annotated proteins and their group def get_child_proteins_uniprot(self, parent): filename = self.cache + self.cache_name("get_child_proteins_uniprot", parent) try: infile = open(filename,"rb") new_object = pickle.load(infile) infile.close() return(new_object) except FileNotFoundError: file = open("queries/child_proteins_uniprot.sparql", "r") query = file.read() file.close() self.sparql_oma.setQuery(query % {"parent" : "<"+parent+">"}) # JSON example response = self.sparql_oma.query().convert() result = [] if response["results"]["bindings"]: for item in response["results"]["bindings"]: row = [ item["group"]["value"], item["protein"]["value"] ] if "protein_uniprot" in item.keys() : row.append(item["protein_uniprot"]["value"]) else: row.append(None) if "group_label" in item.keys() : row.append(item["group_label"]["value"]) else: row.append(None) result.append(row) df = pd.DataFrame(result) df.columns = ["group", "protein", "uniprot", "label" ] df.drop_duplicates(subset ="uniprot", keep = "first", inplace = True) df = df.set_index("uniprot") #cache outfile = open(filename,"wb") pickle.dump(df, outfile) outfile.close() return df else: return pd.DataFrame() #get proteins and their group def get_child_proteins(self, parent): filename = self.cache + self.cache_name("get_child_proteins", parent) try: infile = open(filename,"rb") new_object = pickle.load(infile) infile.close() return(new_object) except FileNotFoundError: file = open("queries/child_proteins.sparql", "r") query = file.read() file.close() self.sparql_oma.setQuery(query % {"parent" : "<"+parent+">"}) # JSON example response = self.sparql_oma.query().convert() result = [] if response["results"]["bindings"]: for item in response["results"]["bindings"]: row = [ item["group"]["value"], item["protein"]["value"] ] if "group_label" in item.keys() : row.append(item["group_label"]["value"]) else: row.append(None) result.append(row) df = pd.DataFrame(result) df.columns = ["group", "protein", "label" ] df.drop_duplicates(subset ="protein", keep = "first", inplace = True) df = df.set_index("protein") #cache outfile = open(filename,"wb") pickle.dump(df, outfile) outfile.close() return df else: return pd.DataFrame() #get child annotations def get_child_annotations(self, go_annotation): filename = self.cache + self.cache_name("get_child_annotations", go_annotation) try: infile = open(filename,"rb") new_object = pickle.load(infile) infile.close() return(new_object) except FileNotFoundError: file = open("queries/child_annotations.sparql", "r") query = file.read() file.close() self.sparql_pbg.setQuery(query % {"annotation" : go_annotation}) # JSON example response = self.sparql_pbg.query().convert() result = [] if response["results"]["bindings"]: for item in response["results"]["bindings"]: row = [ item["go_annotation"]["value"], item["label"]["value"] ] result.append(row) df = pd.DataFrame(result) df.columns = ["go_annotation", "label" ] df.drop_duplicates(subset ="go_annotation", keep = "first", inplace = True) df = df.set_index("go_annotation") #cache outfile = open(filename,"wb") pickle.dump(df, outfile) outfile.close() return df else: return
pd.DataFrame()
pandas.DataFrame
import pandas as pd codes = pd.read_csv("./data/London_District_codes.csv") socio = pd.read_spss("./data/London_ward_data_socioeconomic.sav") health = pd.read_sas("./data/london_ward_data_health.sas7bdat", format='sas7bdat', encoding='latin1') health = health.drop('Population2011Census', axis=1) env = pd.read_csv("./data/London_ward_data_environment.csv") demo = pd.read_csv("./data/London_ward_data_demographics.dat", delimiter='\t') socio['Districtcode'] = socio['Wardcode'].str[:-2] socio_env = pd.merge(socio, env, on='Wardcode') codes['Districtcode'] = codes['Districtcode']\ .replace(r'\s', '', regex=True) health[ ['District', 'Ward', 'remove', 'remove'] ] = health['Wardname'].str.split('-', expand=True) health['District'] = health['District'].str[:-1] health = health.drop(['Wardname', 'remove'], axis=1) total_df = pd.merge(socio_env, codes, on='Districtcode') total_df =
pd.merge(total_df, health, on='District')
pandas.merge