Skip to main content

package for quant finance lecture

Project description


nav_calc


It is a lib for backtesting.

multi_assets

This function is used to test strategies involving mutliple assets, like multi-factors model.

params:

  • prz: dataframe, index = dates, columns = stocks

  • w_tar: dataframe, target weight, index = dates, columns = stocks

It is worthwhile to note that the dates in w_tar does not need to be the same as the dates in prz, it can be a subset of the dates in prz.

  • dates_reb: array, rebalance dates

If you want to balance at every w_tar's dates, set dates_reb to w_tar.index

  • fee: fee rate, default = 0

return a dataframe

It has the following columns:

  • reb: 1 indicate it is a rebalance date, 0 for not a rebalance date

  • ret_gross: return before fee

  • fee: fees to substract from ret_gross

  • ret_net: return after fee

  • nav: net asset value of the strategy

time_series

This function is used to test timing strategies, like CTA strategies.

params:

  • prz: array

  • pos: array, indicate the strategy's position

It must be the same size with prz

  • fee: fee rate, default 0

  • ret_ext: whether to return the extended information; if False(default), return an array which represents the nav of the strategy; if True, return a DataFrame(see below)

return a dataframe

(ret_ext = True)

It has the following columns:

  • price: the price of the underlying asset

  • position: the strategy's position

  • return: pct_change of the price

  • value: position * price

  • fee: trading fees

  • strategy_return_before_fee:

  • strategy_return: post-fee return

  • nav: nav of the strategy (post_fee)

  • nav_before_fee:

  • nav_price: the normalized price


nav_analysis


It is a lib for analysis nav (which maybe from nav_calc).

calc_mdd

Function to calculate max drawdown

params

  • arr: an array that represents nav or price

return a dict

The dict has the following keys:

  • mdd_value: the max drawdown in value

  • mdd_pct: the max drawdown in percentage

calc_ann_ret

Function to calculate the annualized return, assuming daily data.

parmas

  • arr: an array that represents nav or price

return a value

  • annualized return

stats

Function to return both ret and mdd

params

  • arr: an array that represents nav or price

return a dict which has the following keys

  • ret: the total return (not annualized return)

  • mdd: the max drawdown in percentage

stats_yearly

params

  • s: a series that represents nav or price

The index of s should be date and must be in the form like "20181010".

return a dataframe which has the following columns:

  • ret: the total return (not annualized return)

  • mdd: the max drawdown in percentage

The index of the dataframe is 'year'.

stats_yearly_multi_assets

params

  • df: a dataframe whose each column represents a nav of an asset or strategy.

return a dataframe which has two-level columns

Level I: the asset or strategy

Level II: ret and mdd, the same meaning as in stats_yearly


general


to_db_code

params

  • ts_code: security code like '600000.SH'

return

  • db_code: code format in database like 'SH_600000'

example

  • to_db_code('600000.SH') returns 'SH_600000'

to_ts_code

params:

  • db_code: code format in database like 'SH_600000'

return:

  • ts_code: security code like '600000.SH'

example:

  • to_ts_code('SH_600000') returns '600000.SH'

real_round_2

precise round to 0.01 (用于计算涨跌停价)

param

  • a number

return

  • number rounded

example

-read_round_2(5.347) returns 5.35

check_df_struct

check if two dataframe have identical struct: same shape, same index and same columns

params

  • df1, df2

return

  • True if the two dataframe have the same shape, same index and same columns, else False

example

check_df_struct(df1, df2)


utils


grouping1d

assign groupid to an array, used to group stocks according a factor

params

  • arr: the factor array
  • nog: number of group
  • ST = 999: the number need to be specially treated

return

an array that contained groupid, nan will be assigned to the 0 group, ST will be assigned to the -1 group

example

grouping1d(np.arange(100),5)

get_clean_factor_and_forward_returns

param

  • factor: a mult-index series with index = ['date', 'asset'], value = factor value

  • prices: a dataframe with index = daily dates and columns = the universe of stocks interested

  • bins = 5: number of group (use bins as the variable name in order to be consistence with alphalens)

  • periods = (20,60): the holding periods to be tested

return

a multi-index dataframe with index = ['date', 'asset'] and columns:

  • XD(i.e. 20D, 60D,...): the forward return

  • factor: the factor value

  • factor_quantile: the group id (also, to be consistence with alphalens)

example

factor_data = get_clean_factor_and_forward_returns(factor, prices)

reference

alphalens: http://quantopian.github.io/alphalens/index.html

convert_date_in_factor_data

convert the type of index 'date' in factor_data to datetime

param

factor_data: with be changed inplace

return

None

example

convert_date_in_factor_data(factor_data)


SAA


risk_budget

params

  • data: the DataFrame consists of asset price data
  • b: the risk budget (list or array)

return

  • a Series representing the weights

risk_budget_weight_resample

params

  • data: the DataFrame consists of asset price data
  • b: the risk budget (list or array)
  • lb: the lookback period
  • freq: the rebalace frequency (str or int)

return

  • a DataFrame representing the weights at each rebalance date

risk_parity

params

  • data: the DataFrame consists of asset price data

return

  • a Series representing the weights

rp_weight_resample

params

  • data: the DataFrame consists of asset price data
  • lb: the lookback period
  • freq: the rebalace frequency (str or int)

return

  • a DataFrame representing the weights at each rebalance date

equalweight_resample

params

  • data: the DataFrame consists of asset price data
  • freq: the rebalace frequency (str or int)

return

  • a DataFrame representing the weights at each rebalance date

calc_nav

params

  • data: the DataFrame consists of asset price data
  • wegiths: the DataFrame representing the weights at each rebalance date
  • fee: fee rate

return

  • df_nav: a DataFrame the contains the backtested nav of the strategy
  • df: a muli_level DataFrame that contains the raw data, the weights and the period return of that assets, at each rebalace data

cta


有关 CTA 研究的方法

get_pos_1l

当价格位于指标线上方时,做多;当价格位于指标线下方时,做空。

params:

  • prz: array

  • line: array,指标线。也可以为标量,表示水平线。

return an array

仓位

get_pos_2l

当价格位于 upper 上方时,做多;当价格位于 lower 下方时,做空。

params:

  • prz: array

  • upper / lower: array,指标线。也可以为标量,表示水平线。

return an array

仓位

get_pos_3l

当价格位于 upper 上方时,做多;下穿 mid 时平仓。当价格位于 lower 下方时,做空;上穿 mid 时平仓。注意,做多时有可能直接下穿 lower,此时应平多做空,反之亦然。

params:

  • prz: array

  • upper / lower / mid: array,指标线。也可以为标量,表示水平线。

return an array

仓位

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyquantfin-0.0.4.tar.gz (3.6 MB view details)

Uploaded Source

File details

Details for the file pyquantfin-0.0.4.tar.gz.

File metadata

  • Download URL: pyquantfin-0.0.4.tar.gz
  • Upload date:
  • Size: 3.6 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.4.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.7.4

File hashes

Hashes for pyquantfin-0.0.4.tar.gz
Algorithm Hash digest
SHA256 21b17d39ad56da108dd587cf66398c3572f577593d7529ea22c0cb830f721df4
MD5 1b63ed49fd899139532ed8a87421ba8d
BLAKE2b-256 08b224a30cfb9fde1f7d9b5e92168e394b00ede64158f70cecb9afe4d4ea4537

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page