Skip to content

Instantly share code, notes, and snippets.

@arshpreetsingh
Last active March 20, 2017 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arshpreetsingh/2fe8cdbe916afd4e5f00eddde26ad1f7 to your computer and use it in GitHub Desktop.
Save arshpreetsingh/2fe8cdbe916afd4e5f00eddde26ad1f7 to your computer and use it in GitHub Desktop.
"""
Important notes about model
Training Machine-Learning model is trained every Monday (I found that if I train my model every-day it shows less returns)
Trading is happening after each 10 minutes
Machine_learning Model:
I am using two independent Features: '5 minutes price change' and '15 minutes price change'
Dependent Feature: '10 minutes returns' (if -ve buy the stock, if +ve or 0 sell the stock)
Machine_learning Algorithm: Random-Forest(Ensemble-Learning)
Returns: around 110%
Sharp Ratio: 0.91
"""
from sklearn.ensemble import RandomForestClassifier
from sklearn import tree
from sklearn import preprocessing
import numpy as np
import pandas as pd
def initialize(context):
context.assets = sid(8554)
context.model = RandomForestClassifier()
schedule_function(create_model, date_rules.week_start(),time_rules.market_open(minutes=1))
total_minutes = 6*60 + 30
for i in range(1, total_minutes):
# Every 10 minutes run schedule
if i % 10 == 0:
schedule_function(trade,
date_rules.every_day(),
time_rules.market_open(minutes=i),True)
def create_model(context, data):
hello_price = data.history(context.assets, "price", 10000, "1m")
my_df = pd.DataFrame(index=hello_price.index)
my_df['price'] = hello_price.values
my_df['15mins_return'] = my_df['price'].pct_change(15)
my_df['15_mins_return_filled'] = my_df['15mins_return'].fillna(my_df['15mins_return'].mean())
my_df['5mins_return'] = my_df['price'].pct_change(5)
my_df['5_mins_return_filled'] = my_df['5mins_return'].fillna(my_df['5mins_return'].mean())
my_df['returns_per_10_minutes'] = my_df['price'].pct_change(10)
my_df['10minutes_direction'] = np.sign(my_df['returns_per_10_minutes'][10:])
X = my_df[['5_mins_return_filled','15_mins_return_filled']]
X_scaled = preprocessing.scale(X)
Y = my_df['10minutes_direction']
context.model.fit(X_scaled, Y)
def trade(context, data):
if context.model:
hello_hello = data.history(context.assets, "price",30, "1m")
my_df = pd.DataFrame(index=hello_hello.index)
my_df['price'] = hello_hello.values
my_df['15mins_return'] = my_df['price'].pct_change(15)
my_df['5mins_return'] = my_df['price'].pct_change(5)
X = [(my_df['15mins_return'][15:]).mean(),my_df['5mins_return'][5:].mean()]
X_scaled = preprocessing.scale(X)
prediction = context.model.predict(X_scaled)
if prediction < 0:
order_target_percent(context.assets, 1.0)
elif prediction > 0 and prediction==0:
order_target_percent(context.assets, -1.0)
else:
pass
def handle_data(context, data):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment