Overall Statistics
Total Trades
1202
Average Win
0.72%
Average Loss
-0.40%
Compounding Annual Return
14.516%
Drawdown
31.800%
Expectancy
0.575
Net Profit
276.480%
Sharpe Ratio
0.766
Loss Rate
44%
Win Rate
56%
Profit-Loss Ratio
1.80
Alpha
0.032
Beta
0.926
Annual Standard Deviation
0.188
Annual Variance
0.035
Information Ratio
0.169
Tracking Error
0.134
Treynor Ratio
0.155
Total Fees
$30188.21
 
 
#https://quantpedia.com/strategies/net-current-asset-value-effect/
from QuantConnect.Data.UniverseSelection import *
import math
import numpy as np
import pandas as pd
import scipy as sp

class NetCurrentAssetValueEffect(QCAlgorithm):

    def Initialize(self):

        self.SetStartDate(2010, 1, 1)   
        self.SetEndDate(datetime.now())          
        self.SetCash(1000000)            
        self.UniverseSettings.Resolution = Resolution.Daily
        self.sorted_by_ncav = None
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
        self.AddEquity("SPY", Resolution.Daily)
        self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY"), self.rebalance)
        # Count the number of months that have passed since the algorithm starts
        self.months = -1
        self.yearly_rebalance = True
    def CoarseSelectionFunction(self, coarse):
        if self.yearly_rebalance:
            # drop stocks which have no fundamental data or have low price
            self.filtered_coarse = [x.Symbol for x in coarse if (x.HasFundamentalData)]
            return self.filtered_coarse
        else: 
            return []       

    def FineSelectionFunction(self, fine):
        if self.yearly_rebalance:
            # Filter stocks with nonzero Total Assets
            fine = [x for x in fine if (x.FinancialStatements.BalanceSheet.TotalAssets.TwelveMonths != 0)] 
            for i in fine:
                i.MarketCap = float(i.EarningReports.BasicAverageShares.ThreeMonths * (i.EarningReports.BasicEPS.TwelveMonths*i.ValuationRatios.PERatio))
            fine = [x for x in fine if (x.MarketCap != 0)] 
            
            fine = [x for x in fine if ((x.ValuationRatios.WorkingCapitalPerShare*x.EarningReports.BasicAverageShares.Value)/x.MarketCap > 1.5)] 
            self.sorted_by_ncav = [i.Symbol for i in fine] 
            self.Debug(str(len(fine)))
            for i in fine:
                self.Debug(str(i.ValuationRatios.WorkingCapitalPerShare*i.EarningReports.BasicAverageShares.Value/i.MarketCap))

            return self.sorted_by_ncav
        else:
            return []

    def rebalance(self):
        # yearly rebalance
        self.months += 1
        if self.months%12 == 0:
            self.yearly_rebalance = True


    def OnData(self, data):
         if not self.yearly_rebalance: return 
         if self.sorted_by_ncav:
            portfolio_size = int(len(self.sorted_by_ncav))
            stocks_invested = [x.Key for x in self.Portfolio]
            for i in stocks_invested:
                #liquidate the stocks not in the filtered 
                if i not in self.sorted_by_ncav:
                    self.Liquidate(i) 
                #long the stocks in the list
                elif i in self.sorted_by_ncav:
                    self.SetHoldings(i, 1/(portfolio_size))
            self.yearly_rebalance = False                        
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![QuantConnect Logo](https://cdn.quantconnect.com/web/i/qc_notebook_logo_rev0.png)\n",
    "## Welcome to The QuantConnect Research Page\n",
    "#### Refer to this page for documentation https://www.quantconnect.com/docs#Introduction-to-Jupyter\n",
    "#### Contribute to this template file https://github.com/QuantConnect/Lean/blob/master/Jupyter/BasicQuantBookTemplate.ipynb"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## QuantBook Basics\n",
    "\n",
    "### Start QuantBook\n",
    "- Add custom references and imports. QuantConnect modules are already loaded as well as `numpy` as `np`, `pandas` as `pd` and `matplotlib.pyplot` as `plt`\n",
    "- Create a QuantBook instance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an instance\n",
    "qb = QuantBook()\n",
    "\n",
    "# Select asset data\n",
    "spy = qb.AddEquity(\"SPY\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Historical Data Requests\n",
    "\n",
    "We can use the QuantConnect API to make Historical Data Requests. The data will be presented as multi-index pandas.DataFrame where the first index is the Symbol.\n",
    "\n",
    "For more information, please follow the [link](https://www.quantconnect.com/docs#Historical-Data-Historical-Data-Requests)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Gets historical data from the subscribed assets, the last 360 datapoints with daily resolution\n",
    "h1 = qb.History(qb.Securities.Keys, 360, Resolution.Daily)\n",
    "\n",
    "# Plot closing prices from \"SPY\" \n",
    "h1.loc[\"SPY\"][\"close\"].plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Indicators\n",
    "\n",
    "We can easily get the indicator of a given symbol with QuantBook. \n",
    "\n",
    "For all indicators, please checkout QuantConnect Indicators [Reference Table](https://www.quantconnect.com/docs#Indicators-Reference-Table)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Example with BB, it is a datapoint indicator\n",
    "# Define the indicator\n",
    "bb = BollingerBands(30, 2)\n",
    "\n",
    "# Gets historical data of indicator\n",
    "bbdf = qb.Indicator(bb, \"SPY\", 360, Resolution.Daily)\n",
    "\n",
    "# drop undesired fields\n",
    "bbdf = bbdf.drop('standarddeviation', 1)\n",
    "\n",
    "# Plot\n",
    "bbdf.plot()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}