|
| 1 | +### !pip install yfinance |
| 2 | +### !pip install mplfinance |
| 3 | +import yfinance as yf |
| 4 | +import mplfinance as mpf |
| 5 | +import numpy as np |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | +# get the data from yfiance |
| 9 | +df=yf.download('BTC-USD',start='2008-01-04',end='2021-06-3',interval='1d') |
| 10 | + |
| 11 | +#code snippet 5.1 |
| 12 | +# Fit linear regression on close |
| 13 | +# Return the t-statistic for a given parameter estimate. |
| 14 | +def tValLinR(close): |
| 15 | + #tValue from a linear trend |
| 16 | + x = np.ones((close.shape[0],2)) |
| 17 | + x[:,1] = np.arange(close.shape[0]) |
| 18 | + ols = sm1.OLS(close, x).fit() |
| 19 | + return ols.tvalues[1] |
| 20 | + |
| 21 | + #code snippet 5.2 |
| 22 | +''' |
| 23 | + #search for the maximum absolutet-value. To identify the trend |
| 24 | + # - molecule - index of observations we wish to labels. |
| 25 | + # - close - which is the time series of x_t |
| 26 | + # - span - is the set of values of L (look forward period) that the algorithm will #try (window_size) |
| 27 | +# The L that maximizes |tHat_B_1| (t-value) is choosen - which is the look-forward #period |
| 28 | +# with the most significant trend. (optimization) |
| 29 | +''' |
| 30 | +def getBinsFromTrend(molecule, close, span): |
| 31 | + |
| 32 | + #Derive labels from the sign of t-value of trend line |
| 33 | + #output includes: |
| 34 | + # - t1: End time for the identified trend |
| 35 | + # - tVal: t-value associated with the estimated trend coefficient |
| 36 | + #- bin: Sign of the trend (1,0,-1) |
| 37 | + #The t-statistics for each tick has a different look-back window. |
| 38 | + |
| 39 | + #- idx start time in look-forward window |
| 40 | + #- dt1 stop time in look-forward window |
| 41 | + #- df1 is the look-forward window (window-size) |
| 42 | + #- iloc ? |
| 43 | + |
| 44 | + out = pd.DataFrame(index=molecule, columns=['t1', 'tVal', 'bin', 'windowSize']) |
| 45 | + hrzns = range(*span) |
| 46 | + windowSize = span[1] - span[0] |
| 47 | + maxWindow = span[1]-1 |
| 48 | + minWindow = span[0] |
| 49 | + for idx in close.index: |
| 50 | + idx += (maxWindow*pd.Timedelta('1 day')) |
| 51 | + if idx >= close.index[-1]: |
| 52 | + break |
| 53 | + df_tval = pd.Series(dtype='float64') |
| 54 | + iloc0 = close.index.get_loc(idx) |
| 55 | + if iloc0+max(hrzns) > close.shape[0]: |
| 56 | + continue |
| 57 | + for hrzn in hrzns: |
| 58 | + dt1 = close.index[iloc0-hrzn+1] |
| 59 | + df1 = close.loc[dt1:idx] |
| 60 | + df_tval.loc[dt1] = tValLinR(df1.values) #calculates t-statistics on period |
| 61 | + dt1 = df_tval.replace([-np.inf, np.inf, np.nan], 0).abs().idxmax() #get largest t-statistics calculated over span period |
| 62 | + |
| 63 | + print(df_tval.index[-1]) |
| 64 | + print(dt1) |
| 65 | + print(abs(df_tval.values).argmax() + minWindow) |
| 66 | + out.loc[idx, ['t1', 'tVal', 'bin', 'windowSize']] = df_tval.index[-1], df_tval[dt1], np.sign(df_tval[dt1]), abs(df_tval.values).argmax() + minWindow #prevent leakage |
| 67 | + out['t1'] = pd.to_datetime(out['t1']) |
| 68 | + out['bin'] = pd.to_numeric(out['bin'], downcast='signed') |
| 69 | + |
| 70 | + #deal with massive t-Value outliers - they dont provide more confidence and they ruin the scatter plot |
| 71 | + tValueVariance = out['tVal'].values.var() |
| 72 | + tMax = 20 |
| 73 | + if tValueVariance < tMax: |
| 74 | + tMax = tValueVariance |
| 75 | + |
| 76 | + out.loc[out['tVal'] > tMax, 'tVal'] = tMax #cutoff tValues > 20 |
| 77 | + out.loc[out['tVal'] < (-1)*tMax, 'tVal'] = (-1)*tMax #cutoff tValues < -20 |
| 78 | + return out.dropna(subset=['bin']) |
| 79 | + |
| 80 | +if __name__ == '__main__': |
| 81 | + #snippet 5.3 |
| 82 | + idx_range_from = 3 |
| 83 | + idx_range_to = 10 |
| 84 | + df1 = getBinsFromTrend(df.index, df['Close'], [idx_range_from,idx_range_to,1]) #[3,10,1] = range(3,10) This is the issue |
| 85 | + tValues = df1['tVal'].values #tVal |
| 86 | + |
| 87 | + doNormalize = False |
| 88 | + #normalise t-values to -1, 1 |
| 89 | + if doNormalize: |
| 90 | + np.min(tValues) |
| 91 | + minusArgs = [i for i in range(0, len(tValues)) if tValues[i] < 0] |
| 92 | + tValues[minusArgs] = tValues[minusArgs] / (np.min(tValues)*(-1.0)) |
| 93 | + |
| 94 | + plus_one = [i for i in range(0, len(tValues)) if tValues[i] > 0] |
| 95 | + tValues[plus_one] = tValues[plus_one] / np.max(tValues) |
| 96 | + |
| 97 | + #+(idx_range_to-idx_range_from+1) |
| 98 | + plt.scatter(df1.index, df0.loc[df1.index].values, c=tValues, cmap='viridis') #df1['tVal'].values, cmap='viridis') |
| 99 | + plt.plot(df0.index, df0.values, color='gray') |
| 100 | + plt.colorbar() |
| 101 | + plt.show() |
| 102 | + plt.savefig('fig5.2.png') |
| 103 | + plt.clf() |
| 104 | + plt.df['Close']() |
| 105 | + plt.scatter(df1.index, df0.loc[df1.index].values, c=df1['bin'].values, cmap='vipridis') |
| 106 | + |
| 107 | + #Test methods |
| 108 | + ols_tvalue = tValLinR( np.array([3.0, 3.5, 4.0]) ) |
0 commit comments