Overall Statistics
Total Trades
113
Average Win
1.55%
Average Loss
-1.92%
Compounding Annual Return
1.266%
Drawdown
10.900%
Expectancy
0.046
Net Profit
3.849%
Sharpe Ratio
0.151
Probabilistic Sharpe Ratio
3.881%
Loss Rate
42%
Win Rate
58%
Profit-Loss Ratio
0.81
Alpha
0.013
Beta
-0.015
Annual Standard Deviation
0.078
Annual Variance
0.006
Information Ratio
-0.397
Tracking Error
0.137
Treynor Ratio
-0.78
Total Fees
$1319.57
Estimated Strategy Capacity
$3700000.00
Lowest Capacity Asset
TSLA UNU3P8Y3WFAD
from nltk.sentiment import SentimentIntensityAnalyzer

class Cookbook(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2014, 1, 1)
        self.SetEndDate(2017, 1, 1)
        self.SetCash(100000)
        
        self.tsla = self.AddEquity("TSLA", Resolution.Minute).Symbol
        self.musk = self.AddData(MuskTweet, "MUSKTWTS", Resolution.Minute).Symbol
        
        self.Schedule.On(self.DateRules.EveryDay(self.tsla),
                 self.TimeRules.BeforeMarketClose(self.tsla, 15),      
                 self.ExitPositions)

    def OnData(self, data):
        if self.musk in data:
            score = data[self.musk].Value
            content = data[self.musk].Tweet
            
            if score > 0.5:
                self.SetHoldings(self.tsla, 1)
            elif score < -0.5:
                self.SetHoldings(self.tsla, -1)
                
            if abs(score) > 0.5:
                self.Log("Score: " + str(score) + ", Tweet: " + content)

    def ExitPositions(self):
        self.Liquidate()


class MuskTweet(PythonData):

    sia = SentimentIntensityAnalyzer()

    def GetSource(self, config, date, isLive):
        source = "https://www.dropbox.com/s/ovnsrgg1fou1y0r/MuskTweetsPreProcessed.csv?dl=1"
        return SubscriptionDataSource(source, SubscriptionTransportMedium.RemoteFile);

    def Reader(self, config, line, date, isLive):
        if not (line.strip() and line[0].isdigit()):
            return None
        
        data = line.split(',')
        tweet = MuskTweet()
        
        try:
            tweet.Symbol = config.Symbol
            tweet.Time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') + timedelta(minutes=1)
            content = data[1].lower()
            
            if "tsla" in content or "tesla" in content:
                tweet.Value = self.sia.polarity_scores(content)["compound"]
            else:
                tweet.Value = 0
            
            tweet["Tweet"] = str(content)
            
        except ValueError:
            return None
        
        return tweet