# QuantFin
A toolkit for asset pricing.
Working... ...
### Install
```consol
pip install QuantFin
```
### Get started
#### Momentum Effects
1) Calculat momentum value on stocks (MOM)
2) Sort stocks on MOM into 10 decile portfolio
3) Report
```Python
import numpy as np
import pandas as pd
from QuantFin import univariate_sorting, cal_portfolio_rets
# Read CRSP monthly dataset (Source: WRDS)
crsp = ''
crsp.columns = crsp.columns.str.lower()
"""
Screen the sample
1) The sample includes only stocks that are ordinary common share. E.g., shrcd == 10 or 11.
2) The sample includes only stocks listed on NYSE, AMEX or NASDAQ. E.g., exchcd is 1,2,3,31,32 or 33.
3) The sample includes only stocks with valid share price. E.g., prc > 0.
"""
crsp.query("shrcd==10 or shrcd==11", inplcae=True)
crsp.query("exchcd==1 or exchcd==31 or exchcd==2 or exchcd==32 or exchcd==3 or exchcd==33", inplcae=True)
crsp.query('prc > 0', inplcae=True)
crsp.drop_duplicates(['date', 'permno'], inplcae=True)
crsp.set_index(['date', 'permno'], inplcae=True)
crsp = crsp['ret']
"""
# measure mom effects in an efficient way but ignore the requirement of minimum observations
mom = rollingGeometricReturn(mom, 11)
mom = 100*mom
"""
# measure mom effects
mom = mom + 1
mom = mom.rolling(window=11, min_periods=9).apply(pd.DataFrame.prod)
mom = 100*(mom-1)
# skip the most recent month, mom[-11, -1]
mom = mom.shift(1)
mom = mom.unstack().rename('mom').reset_index()
mom = mom.merge(crsp, on=['permno', 'date'], how='left')
# sort stocks based on last period's mom, mom(t-1)
mom = mom.sort_values(['permno', 'date'])
mom.loc[:, 'mom(t-1)'] = mom.groupby(['permno'])['mom'].shift(1)
mom = univariate_sorting(mom, on='mom(t-1)', time_label='date', port_label='port', method='smart')
# calculate returns on the formed portfolis
sample = mom.query("'1963-06-30' <= date <= '2021-12-31'")
samp_ret = cal_portfolio_rets(panel_data=sample, ret_label='ret', time_label='date', port_label='port')
#samp_ret = cal_portfolio_rets(panel_data=sample, ret_label='ret', time_label='date', port_label='port', weight_on='marketCap') # calcualte value-weighted returns for portfolios
np.log(samp_ret+1).cumsum().plot(figsize=(16,8), title='Momentum Portfolios Cumulative Returns')
```
![Momentum Portfolios Returns](momPortsRets.png)
Print summary performance of portfolios, including mean returns and alphas(FF5):
```python
from QuantFin import Performance
samp_ret['10-1'] = samp_ret.loc[:, 10] - samp_ret.loc[:, 1]
print(Performance(samp_ret, models=['FF5']).summary())
```
![Momentum Portfolios Returns](momRetsMean2.png)
Run PanelOLS/Fama-MacBeth regressions and collect results:
```python
from QuantFin import multiregs
formulas = {
"Customised FixedEffects": "rets ~ 1 + mom', fe(permno year)",
"Filter data": "rets ~ 1 + mom if date >= '2000-01-01', fe(permno year)",
"Cluster Standard Errors": "rets ~ 1 + mom if date >= '2000-01-01', fe(permno year), cluster(permno)",
"FamaMacbeth": "rets ~ 1 + mom if date >= '2000-01-01', famamacbeth, robust",
"logFunct": "mom ~ 1 + log(marketCap) + bm + illiq + turnover, fe(permno date), cluster(permno)",
"Interaction": "mom ~ 1 + log(marketCap)##bm + illiq +turnover, fe(permno date), cluster(date)"
}
multiregs(formulas, data=sample)
```
Raw data
{
"_id": null,
"home_page": "https://github.com/yuz0101/QuantFin",
"name": "QuantFin",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "ACADEMIC,EMPIRICAL,FIANCE,RESEARCH,QUANT,PORTFOLIO",
"author": "Stephen Zhang",
"author_email": "stephen_se@outlook.com",
"download_url": "https://files.pythonhosted.org/packages/bd/7a/4bfae4b353cdcd570c64819c3983be0242c7891e736e0730bae8c2d2ab0d/QuantFin-0.0.10.tar.gz",
"platform": null,
"description": "# QuantFin\r\nA toolkit for asset pricing.\r\nWorking... ...\r\n\r\n### Install\r\n\r\n```consol\r\npip install QuantFin\r\n```\r\n\r\n### Get started\r\n\r\n#### Momentum Effects\r\n\r\n1) Calculat momentum value on stocks (MOM)\r\n2) Sort stocks on MOM into 10 decile portfolio\r\n3) Report \r\n\r\n```Python\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom QuantFin import univariate_sorting, cal_portfolio_rets\r\n\r\n# Read CRSP monthly dataset (Source: WRDS)\r\ncrsp = ''\r\ncrsp.columns = crsp.columns.str.lower()\r\n\r\n\"\"\"\r\nScreen the sample\r\n\r\n1) The sample includes only stocks that are ordinary common share. E.g., shrcd == 10 or 11.\r\n2) The sample includes only stocks listed on NYSE, AMEX or NASDAQ. E.g., exchcd is 1,2,3,31,32 or 33.\r\n3) The sample includes only stocks with valid share price. E.g., prc > 0.\r\n\"\"\"\r\n\r\ncrsp.query(\"shrcd==10 or shrcd==11\", inplcae=True)\r\ncrsp.query(\"exchcd==1 or exchcd==31 or exchcd==2 or exchcd==32 or exchcd==3 or exchcd==33\", inplcae=True)\r\ncrsp.query('prc > 0', inplcae=True)\r\ncrsp.drop_duplicates(['date', 'permno'], inplcae=True)\r\ncrsp.set_index(['date', 'permno'], inplcae=True)\r\ncrsp = crsp['ret']\r\n\r\n\"\"\"\r\n# measure mom effects in an efficient way but ignore the requirement of minimum observations\r\nmom = rollingGeometricReturn(mom, 11)\r\nmom = 100*mom\r\n\"\"\"\r\n\r\n# measure mom effects\r\nmom = mom + 1\r\nmom = mom.rolling(window=11, min_periods=9).apply(pd.DataFrame.prod)\r\nmom = 100*(mom-1)\r\n\r\n# skip the most recent month, mom[-11, -1]\r\nmom = mom.shift(1) \r\nmom = mom.unstack().rename('mom').reset_index()\r\nmom = mom.merge(crsp, on=['permno', 'date'], how='left')\r\n\r\n# sort stocks based on last period's mom, mom(t-1)\r\nmom = mom.sort_values(['permno', 'date'])\r\nmom.loc[:, 'mom(t-1)'] = mom.groupby(['permno'])['mom'].shift(1)\r\nmom = univariate_sorting(mom, on='mom(t-1)', time_label='date', port_label='port', method='smart')\r\n\r\n# calculate returns on the formed portfolis\r\nsample = mom.query(\"'1963-06-30' <= date <= '2021-12-31'\")\r\nsamp_ret = cal_portfolio_rets(panel_data=sample, ret_label='ret', time_label='date', port_label='port')\r\n#samp_ret = cal_portfolio_rets(panel_data=sample, ret_label='ret', time_label='date', port_label='port', weight_on='marketCap') # calcualte value-weighted returns for portfolios\r\nnp.log(samp_ret+1).cumsum().plot(figsize=(16,8), title='Momentum Portfolios Cumulative Returns')\r\n```\r\n![Momentum Portfolios Returns](momPortsRets.png)\r\n\r\nPrint summary performance of portfolios, including mean returns and alphas(FF5):\r\n```python\r\nfrom QuantFin import Performance\r\nsamp_ret['10-1'] = samp_ret.loc[:, 10] - samp_ret.loc[:, 1]\r\nprint(Performance(samp_ret, models=['FF5']).summary())\r\n```\r\n\r\n![Momentum Portfolios Returns](momRetsMean2.png)\r\n\r\nRun PanelOLS/Fama-MacBeth regressions and collect results:\r\n\r\n```python\r\nfrom QuantFin import multiregs\r\n\r\nformulas = {\r\n \"Customised FixedEffects\": \"rets ~ 1 + mom', fe(permno year)\",\r\n \"Filter data\": \"rets ~ 1 + mom if date >= '2000-01-01', fe(permno year)\",\r\n \"Cluster Standard Errors\": \"rets ~ 1 + mom if date >= '2000-01-01', fe(permno year), cluster(permno)\",\r\n \"FamaMacbeth\": \"rets ~ 1 + mom if date >= '2000-01-01', famamacbeth, robust\",\r\n \"logFunct\": \"mom ~ 1 + log(marketCap) + bm + illiq + turnover, fe(permno date), cluster(permno)\",\r\n \"Interaction\": \"mom ~ 1 + log(marketCap)##bm + illiq +turnover, fe(permno date), cluster(date)\" \r\n}\r\n\r\nmultiregs(formulas, data=sample)\r\n```\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Library for Academic Research on Asset Pricing",
"version": "0.0.10",
"project_urls": {
"Download": "https://github.com/yuz0101/QuantFin/archive/refs/tags/0.0.10",
"Homepage": "https://github.com/yuz0101/QuantFin"
},
"split_keywords": [
"academic",
"empirical",
"fiance",
"research",
"quant",
"portfolio"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "bd7a4bfae4b353cdcd570c64819c3983be0242c7891e736e0730bae8c2d2ab0d",
"md5": "7c13ea846fdc86d4120941e320665d03",
"sha256": "59590304a90ac9690bf15f672ce56bc052dca87e8aec00b54afffcf39cb389cf"
},
"downloads": -1,
"filename": "QuantFin-0.0.10.tar.gz",
"has_sig": false,
"md5_digest": "7c13ea846fdc86d4120941e320665d03",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 183028,
"upload_time": "2024-02-27T16:57:28",
"upload_time_iso_8601": "2024-02-27T16:57:28.293171Z",
"url": "https://files.pythonhosted.org/packages/bd/7a/4bfae4b353cdcd570c64819c3983be0242c7891e736e0730bae8c2d2ab0d/QuantFin-0.0.10.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-02-27 16:57:28",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "yuz0101",
"github_project": "QuantFin",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [],
"lcname": "quantfin"
}