Python primer for Trading

UberMachine

Well-Known Member
#64
You would often need to analyze data by day, month and year.
To do this, first check whether your date column is in datetime type.
Run,
Python:
df.info()
1536938960285.png

You could see the timestamp column is in the datetime64[ns] format. This is the format we need to get date/time analytics.
If this is in an another format such as float, int or object, then use
Python:
df['timestamp'] = pd.to_datetime(df['timestamp'])

# In case if the format is dayfirst which is the case for India, then use
df['timestamp'] = pd.to_datetime(df['timestamp'], dayfirst=True)
Now, run df.info() and check whether the required column is in datetime format
 

UberMachine

Well-Known Member
#65
Once your date is in datetime format. Now add the year and month columns.
I assume your timestamp column contains only date information, not hour and minute
Python:
df['year'] = df['timestamp'].dt.year
dt['month'] = df['timestamp'].dt.month
Now you have 2 extra columns year and month. Say you need to get the total_profit daywise, Then
Python:
df.groupby(['timestamp'])['total_profit'].sum()

# If you need more than 2 columns in result
df.groupby(['timestamp'])[['qty', 'total_profit']].sum()

# You can also use a different function
df.groupby(['timestamp'])[['qty', 'total_profit']].mean()
To get year wise,
Python:
df.groupby(['year'])['total_profit'].sum()
To get year and then by month,
Python:
df.groupby(['year', 'month'])['total_profit'].sum()
If you just group by month only, it would aggregate for months across years.
If your data has minute and second information, you could add a column with
Python:
df['minute'] = df['timestamp'].dt.minute
The dt function has the following options
  • year
  • month
  • week
  • weekday
  • weeknum
  • day
  • hour
  • minute
  • second
So, you could download all your trades from your broker and analyze your performance
 
#66
Techincally, you can use the kite connect API to download real time data for a select number of instruments (I am successful implementing it).
But creating and updating your own charts for live trading is a bit too much complex and I see the existing tools are good enough.
Is there any specific use case for implementing this?
Dear Sir,

I am know python. I am new to trading related code.
Could you please give me a sample code to use Supertrend strategy in kite connect

-Mullangi