python 我的背景设置1和2
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 我的背景设置1和2相关的知识,希望对你有一定的参考价值。
# *****************************************************************
# IMPORTS
# ******************************************************************
import pandas as pd
from datetime import datetime,timezone
import pytz
from fintools import compute_weights_RS_DM, compute_weights_PMA
# *****************************************************************
# VARIABLES
# ******************************************************************
start = datetime(2010, 1, 1, 0, 0, 0, 0, pytz.utc)
end = datetime.today().replace(tzinfo=timezone.utc)
# *****************************************************************
# STRATEGIES
# ******************************************************************
strategies = {
'RS0001': {'assets': ['VCVSX', 'VWEHX', 'VFIIX', 'FGOVX', 'VWAHX'],
'start': start, 'end': end,
'rs_lookback': 1, 'risk_lookback': 1, 'n_top': 2, 'frequency': 'M',
'cash_proxy': 'CASHX', 'risk_free': 0},
'PMA001': {'assets': ['VCVSX', 'VFIIX'],
'start': start, 'end': end,
'risk_lookback': 3, 'frequency': 'M', 'allocations': [0.6, 0.4],
'cash_proxy': 'VUSTX'}
}
# *****************************************************************
# STRATEGY TYPES
# ******************************************************************
s = [k for k in strategies.keys()]
common_parameters = ['assets', 'start', 'end', 'cash_proxy', 'risk_lookback', 'frequency']
RS_DM_parameters = ['risk_free', 'rs_lookback', 'n_top', ]
PMA_parameters = ['allocations']
RS_DM_p = [p for p in common_parameters + RS_DM_parameters]
PMA_p = [p for p in common_parameters + PMA_parameters]
# Dictionaries for multiple strategies
strategy_values = pd.DataFrame(columns=strategies.keys())
security_weights = {}
security_holdings = {}
security_prices = {}
# *****************************************************************
# RUN STRATEGIES
# ******************************************************************
for name in [k for k in strategies.keys()]:
if (set(strategies[name]) == set(RS_DM_p)):
print(name, 'RS_DM_p')
s_value, s_holdings, s_weights, s_prices = compute_weights_RS_DM(name, strategies[name])
elif (set(strategies[name]) == set(PMA_p)):
print(name, 'PMA_p')
s_value, s_holdings, s_weights, s_prices = compute_weights_PMA(name, strategies[name])
else:
print(name + ' IS UNDEFINED')
# s_value.plot(figsize=(15, 10), grid=True)
strategy_values[name] = s_value
security_weights[name] = s_weights
security_holdings[name] = s_holdings
security_prices[name] = s_prices
#print (strategy_values,security_weights,security_holdings,security_prices)
%matplotlib inline
strategy_values['RS0001'].plot(figsize=(15, 10), grid=True)
strategy_values['PMA001'].plot(figsize=(15, 10), grid=True)
# *****************************************************************
# IMPORTS
# ******************************************************************
import pandas_datareader.data as pdr
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime,timezone,timedelta
import pytz
import talib
import itable
import ffn
from fintools import get_DataArray, compute_weights_RS_DM, compute_weights_PMA, \
Parameters, endpoints, backtest, show_return_table, show_annual_returns
%matplotlib inline
# *****************************************************************
# VARIABLES (UNLESS IN 'STRATEGIES' BELOW)
# ******************************************************************
assets = ['VCVSX', 'VWEHX', 'VFIIX', 'VWAHX', 'FGOVX'] # list of unique and valid assets
start = datetime(2010, 1, 1, 0, 0, 0, 0, pytz.utc) # zone-aware date-times
end = datetime.today().replace(tzinfo=timezone.utc) # zone-aware date-times
cash_proxy = 'CASHX' # None | 'CASHX' | '<valid asset'
risk_lookback = 1 # integer > 0
frequency = 'M' # integer 0 < n < 27(?) |'M'|'Q'|'B'|'Y'
risk_free = 0 # 0 | '<valid asset'
rs_lookback = 1 # integer > 0
n_top = 2 # integer > 0 < number of elligible assets
# allocations = [1./len(assets) for a in assets] # list of percentages of each asset, sum = 1.0
# *****************************************************************
# CREATE TICKERS (UNLESS USING COMPUTE_WEIGHTS_RS_DM OR _PMA)
# ******************************************************************
tickers = assets.copy()
if cash_proxy != 'CASHX':
tickers = list(set(tickers + [cash_proxy]))
if isinstance(risk_free, str):
tickers = list(set(tickers + [risk_free]))
# *****************************************************************
# PRICES
# ******************************************************************
# forward-fill to remove NaNs
pnl = get_DataArray(assets, start, end).to_pandas().transpose(1,2,0).ffill()
data = pnl[:,:,'adj close']
prices = data.copy().dropna()
# *****************************************************************
# INCEPTION DATES (IF REQUIRED)
# ******************************************************************
# inception_dates = pd.DataFrame([data[ticker].first_valid_index() for ticker in data.columns],
# index=data.keys(), columns=['inception'])
# print(inception_dates)
# *****************************************************************
# END POINTS & PRICES AT END POINTS
# ******************************************************************
end_points = endpoints(period=frequency, trading_days=prices.index)
prices_m = prices.loc[end_points]
print(prices_m[:3])
# *****************************************************************
# STRATEGY DATA - FACTORS AND FILTERS
# ******************************************************************
# FACTORS
returns = prices_m[tickers].pct_change(rs_lookback)[rs_lookback:]
MA = prices_m.rolling(2).mean()[tickers]
if isinstance(risk_free, int) :
excess_returns = returns
else :
risk_free_returns = prices_m[risk_free].pct_change(rs_lookback)[rs_lookback:]
excess_returns = returns.subtract(risk_free_returns, axis=0).dropna()
# FILTERS
# absolute_momentum_rule = returns > 0
absolute_momentum_rule = MA > 0
# rebalance_dates = excess_returns.index.join(absolute_momentum_rule.index, how='inner')
rebalance_dates = excess_returns.index
# *****************************************************************
# RANKING AND ELLIGIBILITY
# ******************************************************************
# RANKS
# ranked1 = excess_returns.reindex(rebalance_dates)[assets].rank(ascending=False, axis=1, method='dense')
ranked = excess_returns[assets].rank(ascending=False, axis=1, method='dense')
# ELLIGIBILITY
# elligibility rule - top n_top ranked securities
elligible = ranked[ranked<=n_top] > 0
# *****************************************************************
# ALLOCATIONS AND WEIGHTS
# ******************************************************************
# ALLOCATIONS
# equal weight allocations
elligible = elligible.multiply(1./elligible.sum(1), axis=0)
# WEIGHTS
weights = pd.DataFrame(0.,index=elligible.index, columns=prices.columns)
# downside protection
if cash_proxy == 'CASHX' :
weights[cash_proxy] = 0
prices[cash_proxy] = 1.
weights[assets] = (elligible * absolute_momentum_rule).dropna()
weights[cash_proxy] += 1 - weights[assets].sum(axis=1)
# backtest
p_value, p_holdings, p_weights = backtest(prices, weights, 10000., offset=0, commission=10.)
p_value.plot(figsize=(15,10), grid=True)
# print (strategy_values,security_weights,security_holdings,security_prices)
#ffn.calc_perf_stats(p_value).display()
#show_return_table(p_value)
#show_annual_returns(p_value)
以上是关于python 我的背景设置1和2的主要内容,如果未能解决你的问题,请参考以下文章
4.11Python数据处理篇之Matplotlib系列---图例,网格,背景的设置