ml-finance-python

python scripts for finance machine learning

git clone https://9o.is/git/ml-finance-python.git

deflated_sharpe_ratio.py

(2049B)


      1 #!/usr/bin/env python
      2 # On 20140607 by lopezdeprado@lbl.gov
      3 from itertools import product
      4 
      5 import numpy as np
      6 import pandas as pd
      7 import scipy.stats as ss
      8 
      9 
     10 def get_analytical_max_sr(mu, sigma, num_trials):
     11     """Compute the expected maximum Sharpe ratio (Analytically)"""
     12 
     13     # Euler-Mascheroni constant
     14     emc = 0.5772156649
     15 
     16     maxZ = (1 - emc) * ss.norm.ppf(1 - 1. / num_trials) + emc * ss.norm.ppf(1 - 1 / (num_trials * np.e))
     17     return mu + sigma * maxZ
     18 
     19 
     20 def get_numerical_max_sr(mu, sigma, num_trials, n_iter):
     21     """Compute the expected maximum Sharpe ratio (Numerically)"""
     22     max_sr, count = [], 0
     23     while count < n_iter:
     24         count += 1
     25         series = np.random.normal(mu, sigma, num_trials)
     26         max_sr.append(max(series))
     27     return np.mean(max_sr), np.std(max_sr)
     28 
     29 
     30 def simulate(mu, sigma, num_trials, n_iter):
     31     """Get analytical and numerical solutions"""
     32     expected_max_sr = get_analytical_max_sr(mu, sigma, num_trials)
     33     mean_max_sr, stdmean_max_sr = get_numerical_max_sr(mu, sigma, num_trials, n_iter)
     34     return expected_max_sr, mean_max_sr, stdmean_max_sr
     35 
     36 
     37 def main():
     38     n_iter, sigma, output, count = 1e4, 1, [], 0
     39     for i, prod_ in enumerate(product(np.linspace(-100, 100, 101), range(10, 1001, 10)), 1):
     40         if i % 1000 == 0:
     41             print(i, end=' ', flush=True)
     42         mu, num_trials = prod_[0], prod_[1]
     43         expected_max_sr, mean_max_sr, std_max_sr = simulate(mu, sigma, num_trials, n_iter)
     44         err = expected_max_sr - mean_max_sr
     45         output.append([mu, sigma, num_trials, n_iter,
     46                        expected_max_sr, mean_max_sr,
     47                        std_max_sr, err])
     48     output = pd.DataFrame(output,
     49                           columns=['mu', 'sigma', 'num_trials', 'n_iter',
     50                                    'expected_max_sr', 'mean_max_sr',
     51                                    'std_max_sr', 'err'])
     52     print(output.info())
     53     output.to_csv('DSR.csv')
     54 
     55 
     56 # df = pd.read_csv('DSR.csv')
     57 # print(df.info())
     58 # print(df.head())
     59 
     60 if __name__ == '__main__':
     61     main()