'Modify a trading strategy around Trump's tweets

I'm trying to modify a trading strategy around a dataset of Trump's tweets. The current strategy acts upon new messages by placing new trades without clearing the old ones - allowing leverage to grow unlimited. Something in the code needs to be tweaked in order for the strategy to trade without leverage, but I'm not sure what part. Could someone please help me? Also, how can I compare the strategies against each other?

test_dataset2=pd.DataFrame({'Predict':model.predict(test_dataset['text']), 'LongOnly':test_dataset['toclose']})

test_dataset2.index=test_dataset['created_at']
test_dataset2.sort_index(inplace=True)
test_dataset2['Strategy']=0
for i in range(0,len(test_dataset2)):
   if (test_dataset2.iloc[i,0]=='Up'):
      test_dataset2.iloc[i,2]=test_dataset2.iloc[i,1]
   else:
      test_dataset2.iloc[i,2]=-test_dataset2.iloc[i,1]

((1 + test_dataset2[['LongOnly','Strategy']]).cumprod() - 1).plot()
plt.xlabel('Date')
plt.ylabel('Cumulative Return')
plt.show()

import pickle 

with open("test_dataset2.pickle", "wb") as f1:
   pickle.dump(test_dataset2, f1)

f1.close()



Solution 1:[1]

If you are using an API to submit your orders, use calls to manage your leverage. For example:

import tradeapi as api

condition_met_tweet = True
trades_taken = 0

while True:
    if condition_met_tweet == True and trades_taken < 20:
        # Sumbit order
        api.submit_order(
            {
                "symbol": "SPY",
                "side": "long",
                "notional_value": float(api.get_account_balance())/20 # 5% balance
            }
        )

        # Add to trade counter
        trades_taken += 1

This will prevent the program from taking more than 20 trades.

Pros

  • Very easy to set up.
  • Easy to debug, as your trade counter is in-house and monitored.

Cons

  • The API is unaware of your restriction.
  • Once you've taken twenty trades, even if some of them are closed by bracket/target/stop, you can't take any more.

For this reason, it's better to calculate the buying power available using your API.

import tradeapi as api
import math

condition_met_tweet = True

while True:
    if condition_met_tweet == True:
        # Calculate quantity
        account_bal = float(api.get_account_balance())
        asset_price = float(api.get_last_trade('SPY'))
        quantity = math.floor((account_bal/20)/asset_price)
        account_bp = float(api.get_account_buying_power())

        if quantity == 0 or (quantity*asset_price) > account_bp:
            continue # don't submit an order, re-loop 

        # Sumbit order
        api.submit_order(
            {
                "symbol": "SPY",
                "side": "long",
                "quantity": quantity
            }
        )

        # Add to trade counter
        trades_taken += 1

This will calculate the ideal quantity when your entry is triggered, then skip the order-entry portion in the case that your ideal quantity (rounded down) is 0. It will also behave this way if you "can't afford" the next trade, defined by you not having enough available buying power to execute it.

This system will work as long as you are able to call the following values in real-time from your API:

  • Account balance
  • Asset prices
  • Account buying power

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 preritdas