pip install backtrader yfinance pandas
python main.py
import yfinance as yf
import backtrader as bt
import pandas as pd
# Define the trading strategy
class IntradayStrategy(bt.Strategy):
params = (
('stop_loss', 0.02), # Stop loss at 2%
('target', 0.06), # Target at 6%
('cash', 100000), # Starting cash
)
def __init__(self):
# Keep track of the first trade of the day
self.first_trade = None
self.orders = []
# Initialize a DataFrame to store trade results
self.trade_results = []
# Calculate the 1-week average volume using a built-in indicator
self.volume_avg_1week = bt.indicators.SimpleMovingAverage(self.data.volume, period=5)
def next(self):
# Check if we need to execute the filter and trade logic
if self.first_trade is None:
# Execute the filter and trading entry logic
self.filter_and_trade()
# Check for stop loss or target
self.check_stop_loss_target()
def filter_and_trade(self):
# Fetch necessary data for the filter
volume = self.data.volume[0]
volume_avg_1week = self.volume_avg_1week[0]
return_1day = (self.data.close[0] - self.data.close[-1]) / self.data.close[-1]
return_1week = (self.data.close[0] - self.data.close[-5]) / self.data.close[-5]
market_cap = self.data.market_cap[0]
# Filter based on the provided conditions
if (
2.5 * volume_avg_1week < volume and
market_cap > 500 and
return_1week < 0.05 and
return_1day > 0.02
):
# Place an entry order
self.first_trade = True
order = self.buy(size=1)
self.orders.append(order)
def check_stop_loss_target(self):
# Check for stop loss or target conditions
if self.position:
# Calculate entry price
entry_price = self.position.price
# Calculate current price
current_price = self.data.close[0]
# Calculate the stop loss and target prices
stop_loss_price = entry_price * (1 - self.params.stop_loss)
target_price = entry_price * (1 + self.params.target)
# Check for stop loss
if current_price <= stop_loss_price:
self.close()
self.trade_results.append((self.data._name, entry_price, current_price, "Loss"))
self.first_trade = None
# Check for target
elif current_price >= target_price:
self.close()
self.trade_results.append((self.data._name, entry_price, current_price, "Profit"))
self.first_trade = None
def notify_trade(self, trade):
if trade.isclosed:
# Print trade details when trade is closed
print(f"Stock: {trade.data._name}, Entry: {trade.price:.2f}, Exit: {trade.pnl:.2f}")
print(f"Profit or Loss: {trade.pnl:.2f}")
print(f"Total balance: {self.broker.getvalue():.2f}")
# Store trade result
self.trade_results.append({
'Stock': trade.data._name,
'Entry': trade.price,
'Exit': trade.value,
'Profit or Loss': trade.pnl,
'Total balance': self.broker.getvalue()
})
# Define your list of Indian stocks to backtest
stock_symbols = ['RELIANCE.NS', 'TCS.NS', 'INFY.NS']
# Create a cerebro engine instance
cerebro = bt.Cerebro()
# Set initial cash
cerebro.broker.set_cash(100000)
# Set commission (optional, depending on your broker)
cerebro.broker.setcommission(commission=0.001)
# Add your strategy
cerebro.addstrategy(IntradayStrategy)
# Add data feeds for each stock
for symbol in stock_symbols:
data = yf.download(symbol, start="2023-01-01", end="2024-01-01", interval='1d')
if data.empty:
print(f"No data found for {symbol}. Skipping this stock.")
continue
data['market_cap'] = data['Close'] * data['Volume'] / 1e6
feed = bt.feeds.PandasData(dataname=data, name=symbol)
cerebro.adddata(feed)
# Run the backtest
cerebro.run()
# Print the final balance
print(f"Final Portfolio Value: ${cerebro.broker.getvalue():.2f}")
# Print the trade results
if hasattr(cerebro, 'strategies') and cerebro.strategies:
df_results = pd.DataFrame(cerebro.strategies[0].trade_results)
print(df_results)
else:
print("No strategy results found.") Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
| Name | Description |
|---|---|
| NumPy | NumPy python library helps users to work on arrays with ease |
| SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
| SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
| Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
| DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |