<s> import matplotlib . pyplot as plt <EOL> from sklearn . ensemble import RandomForestRegressor <EOL> import numpy as np <EOL> import matplotlib . ticker as mtick <EOL> def fit_and_trade ( data , cols , split , threshold ) : <EOL> '''<STR_LIT>''' <EOL> data = data [ data . width > <NUM_LIT:0> ] <EOL> X = data [ cols ] <EOL> y = data . mid30 <EOL> X_train = X . iloc [ : split ] <EOL> X_test = X . iloc [ split : ] <EOL> y_train = y . iloc [ : split ] <EOL> y_test = y . iloc [ split : ] <EOL> regressor = RandomForestRegressor ( n_estimators = <NUM_LIT:100> , <EOL> min_samples_leaf = <NUM_LIT> , <EOL> random_state = <NUM_LIT> , <EOL> n_jobs = - <NUM_LIT:1> ) <EOL> regressor . fit ( X_train . values , y_train . values ) <EOL> trade ( X_test . values , y_test . values , regressor , threshold ) <EOL> def trade ( X , y , index , model , threshold ) : <EOL> '''<STR_LIT>''' <EOL> print '<STR_LIT>' , model . score ( X , y ) <EOL> preds = model . predict ( X ) <EOL> trades = np . zeros ( len ( preds ) ) <EOL> count = <NUM_LIT:0> <EOL> active = False <EOL> for i , pred in enumerate ( preds ) : <EOL> if active : <EOL> count += <NUM_LIT:1> <EOL> if count == <NUM_LIT:30> : <EOL> count = <NUM_LIT:0> <EOL> active = False <EOL> elif abs ( pred ) > threshold : <EOL> active = True <EOL> trades [ i ] = np . sign ( pred ) <EOL> returns = trades * y * <NUM_LIT:100> <EOL> trades_only = returns [ trades != <NUM_LIT:0> ] <EOL> mean_return = trades_only . mean ( ) <EOL> accuracy = sum ( trades_only > <NUM_LIT:0> ) * <NUM_LIT:1.> / len ( trades_only ) <EOL> profit = np . cumsum ( returns ) <EOL> plt . figure ( dpi = <NUM_LIT> ) <EOL> fig , ax = plt . subplots ( ) <EOL> plt . plot ( index , profit ) <EOL> plt . title ( '<STR_LIT>' <EOL> . format ( threshold * <NUM_LIT:100> ) ) <EOL> plt . ylabel ( '<STR_LIT>' ) <EOL> plt . xticks ( rotation = <NUM_LIT> ) <EOL> formatter = mtick . FormatStrFormatter ( '<STR_LIT>' ) <EOL> ax . yaxis . set_major_formatter ( formatter ) <EOL> return_text = '<STR_LIT>' . format ( mean_return ) <EOL> trades_text = '<STR_LIT>' . format ( len ( trades_only ) ) <EOL> accuracy_text = '<STR_LIT>' . format ( accuracy * <NUM_LIT:100> ) <EOL> plt . text ( <NUM_LIT> , <NUM_LIT> , return_text , transform = ax . transAxes ) <EOL> plt . text ( <NUM_LIT> , <NUM_LIT> , trades_text , transform = ax . transAxes ) <EOL> plt . text ( <NUM_LIT> , <NUM_LIT> , accuracy_text , transform = ax . transAxes ) <EOL> plt . show ( ) </s>
